<?php

/**
 * BaseForm class
 *
 * @package
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */

namespace Openbizx\View;

use Openbizx\Object\Statefullable;
use Openbizx\Helpers\MessageHelper;
use Openbizx\Core\Expression;
use Openbizx\Object\MetaObject;
use Openbizx\Easy\FormRenderer;

include_once "FormHelper.php";

class BaseForm extends MetaObject implements Statefullable
{

    // metadata vars are public, necessary for metadata inheritance
    public $title;
    public $icon;
    public $jsClass;
    public $dataObjName;
    // FormAction handles actions from client
    public $formAction;
    // FormRenderer draws data to given format (html/xml) output
    public $formRenderer;
    // FormEventManager triggers external event observers on certain events
    public $formEventManager;

    /**
     * Name of inherited form (meta-form)
     * @var string
     */
    public $inheritFrom;
    public $panels;

    /**
     * Data Panel object
     * @var Panel
     */
    public $dataPanel;

    /**
     * Action Panel object
     * @var Panel
     */
    public $actionPanel;

    /**
     * Navigation Panel object
     * @var Panel
     */
    public $navPanel;

    /**
     * Search Panel object
     * @var Panel
     */
    public $searchPanel;
    public $height;
    public $width;
    public $templateEngine;
    public $templateFile;
    public $subForms = null;
    public $cacheLifeTime = 0;
    // basic form vars
    protected $dataObj;
    public $messageFile = null;
    protected $objectMessages;
    protected $directMethodList = array(); //list of method that can directly from browser
    protected $formHelper;

    /**
     * Initialize BizForm with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
        $this->inheritParentObj();
        $this->formHelper = new FormHelper($this);
    }

    public function allowAccess($access = null)
    {
        $result = parent::allowAccess($access);
        return $result;
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->inheritFrom = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["INHERITFROM"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["INHERITFROM"] : null;
        $this->title = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["TITLE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["TITLE"] : null;
        $this->icon = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["ICON"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["ICON"] : null;
        $this->objectDescription = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["DESCRIPTION"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["DESCRIPTION"] : null;
        $this->jsClass = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["JSCLASS"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["JSCLASS"] : null;
        $this->height = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["HEIGHT"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["HEIGHT"] : null;
        $this->width = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["WIDTH"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["WIDTH"] : null;
        $this->templateEngine = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["TEMPLATEENGINE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["TEMPLATEENGINE"] : null;
        $this->templateFile = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["TEMPLATEFILE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["TEMPLATEFILE"] : null;
        $this->formType = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["FORMTYPE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["FORMTYPE"] : null;

        $this->objectName = $this->prefixPackage($this->objectName);
        if ($this->inheritFrom == '@sourceMeta')
            $this->inheritFrom = '@' . $this->objectName;
        else
            $this->inheritFrom = $this->prefixPackage($this->inheritFrom);
        $this->dataObjName = $this->prefixPackage($xmlArr["EASYFORM"]["ATTRIBUTES"]["BIZDATAOBJ"]);

        $this->dataPanel = new Panel($xmlArr["EASYFORM"]["DATAPANEL"]["ELEMENT"], "", $this);
        $this->actionPanel = new Panel($xmlArr["EASYFORM"]["ACTIONPANEL"]["ELEMENT"], "", $this);
        $this->navPanel = new Panel($xmlArr["EASYFORM"]["NAVPANEL"]["ELEMENT"], "", $this);
        $this->searchPanel = new Panel($xmlArr["EASYFORM"]["SEARCHPANEL"]["ELEMENT"], "", $this);
        $this->panels = array($this->dataPanel, $this->actionPanel, $this->navPanel, $this->searchPanel);

        $this->eventName = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["EVENTNAME"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["EVENTNAME"] : null;

        $this->messageFile = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["MESSAGEFILE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["MESSAGEFILE"] : null;
        $this->objectMessages = MessageHelper::loadMessage($this->messageFile, $this->package);

        $this->cacheLifeTime = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["CACHELIFETIME"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["CACHELIFETIME"] : "0";

        // parse access
        if ($this->access) {
            $arr = explode(".", $this->access);
            $this->resource = $arr[0];
        }
        if ($this->jsClass == "jbForm" && strtoupper($this->formType) == "LIST")
            $this->jsClass = "Openbizx.TableForm";
        if ($this->jsClass == "jbForm")
            $this->jsClass = "Openbizx.Form";

        $this->translate(); // translate for multi-language support
    }

    /**
     * Inherit from parent object. Name, Package, Class cannot be inherited
     *
     * @return void
     */
    protected function inheritParentObj()
    {
        if (!$this->inheritFrom)
            return;
        $parentObj = Openbizx::getObject($this->inheritFrom);

        $this->title = $this->title ? $this->title : $parentObj->title;
        $this->icon = $this->icon ? $this->icon : $parentObj->icon;
        $this->objectDescription = $this->objectDescription ? $this->objectDescription : $parentObj->objectDescription;
        $this->jsClass = $this->jsClass ? $this->jsClass : $parentObj->jsClass;
        $this->height = $this->height ? $this->height : $parentObj->height;
        $this->width = $this->width ? $this->width : $parentObj->width;
        $this->templateEngine = $this->templateEngine ? $this->templateEngine : $parentObj->templateEngine;
        $this->templateFile = $this->templateFile ? $this->templateFile : $parentObj->templateFile;
        $this->formType = $this->formType ? $this->formType : $parentObj->formType;
        $this->range = $this->range ? $this->range : $parentObj->range;
        $this->fixSearchRule = $this->fixSearchRule ? $this->fixSearchRule : $parentObj->fixSearchRule;
        $this->defaultFixSearchRule = $this->defaultFixSearchRule ? $this->defaultFixSearchRule : $parentObj->defaultFixSearchRule;
        $this->dataObjName = $this->dataObjName ? $this->dataObjName : $parentObj->dataObjName;
        $this->eventName = $this->eventName ? $this->eventName : $parentObj->eventName;
        $this->messageFile = $this->messageFile ? $this->messageFile : $parentObj->messageFile;
        $this->objectMessages = MessageHelper::loadMessage($this->messageFile, $this->package);
        $this->cacheLifeTime = $this->cacheLifeTime ? $this->cacheLifeTime : $parentObj->cacheLifeTime;

        $this->dataPanel->merge($parentObj->dataPanel);
        $this->actionPanel->merge($parentObj->actionPanel);
        $this->navPanel->merge($parentObj->navPanel);
        $this->searchPanel->merge($parentObj->searchPanel);

        if ($this->dataPanel->current()) {
            foreach ($this->dataPanel as $elem)
                $elem->adjustFormName($this->objectName);
        }
        if ($this->actionPanel->current()) {
            foreach ($this->actionPanel as $elem)
                $elem->adjustFormName($this->objectName);
        }
        if ($this->navPanel->current()) {
            foreach ($this->navPanel as $elem)
                $elem->adjustFormName($this->objectName);
        }
        if ($this->searchPanel->current()) {
            foreach ($this->searchPanel as $elem)
                $elem->adjustFormName($this->objectName);
        }
        $this->panels = array($this->dataPanel, $this->actionPanel, $this->navPanel, $this->searchPanel);
    }

// -------------------------- Session Methods ---------------------- //

    public function loadStatefullVars($sessionContext)
    {

    }

    public function saveStatefullVars($sessionContext)
    {

    }

// -------------------------- Attribute Methods ---------------------- //
    /**
     * Get message, and translate it
     *
     * @param string $messageId message Id
     * @param array $params
     * @return string message string
     */
    public function getMessage($messageId, $params = array())
    {
        $message = isset($this->objectMessages[$messageId]) ? $this->objectMessages[$messageId] : constant($messageId);
        //$message = I18n::getInstance()->translate($message);
        $message = I18n::t($message, $messageId, $this->getModuleName($this->objectName));
        $msg = @vsprintf($message, $params);
        if (!$msg) { //maybe in translation missing some %s can cause it returns null
            $msg = $message;
        }
        return $msg;
    }

    /**
     * Get object property
     * This method get element object if propertyName is "Elements[elementName]" format.
     *
     * @param string $propertyName
     * @return <type>
     */
    public function getProperty($propertyName)
    {
        $ret = parent::getProperty($propertyName);
        if ($ret !== null) {
            return $ret;
        }

        $pos1 = strpos($propertyName, "[");
        $pos2 = strpos($propertyName, "]");
        if ($pos1 > 0 && $pos2 > $pos1) {
            $propType = substr($propertyName, 0, $pos1);
            $elementName = substr($propertyName, $pos1 + 1, $pos2 - $pos1 - 1);
            $result = $this->getElement($elementName);
            return $result;
        }
    }

    /**
     * Get object instance of {@link BizDataObj} defined in it's metadata file
     *
     * @return BizDataObj
     */
    public function getDataObj()
    {
        if (!$this->dataObj) {
            if ($this->dataObjName) {
                $this->dataObj = Openbizx::getObject($this->dataObjName);
            }
            if ($this->dataObj) {
                $this->dataObj->bizFormName = $this->objectName;
            } else {
                //Openbizx::$app->getClientProxy()->showErrorMessage("Cannot get DataObj of ".$this->dataObjName.", please check your metadata file.");
                return null;
            }
        }
        return $this->dataObj;
    }

    /**
     * Set data object {@link BizDataObj} with specified instant from parameter
     *
     * @param BizDataObj $dataObj
     * @return void
     */
    final public function setDataObj($dataObj)
    {
        $this->dataObj = $dataObj;
    }

    /**
     * Get view object
     *
     * @global BizSystem $g_BizSystem
     * @return WebPage
     */
    public function getWebpageObject()
    {
        $viewName = Openbizx::$app->getCurrentViewName();
        if (!$viewName) {
            return null;
        }
        $viewObj = Openbizx::getObject($viewName);
        return $viewObj;
    }

    /**
     * Get sub form of this form
     *
     * @return EasyForm
     */
    public function getSubForms()
    {
        // ask view to give its subforms if not set yet
        return $this->subForms;
    }

    /**
     * Get an element object
     *
     * @param string $elementName - name of the control
     * @return Element
     */
    public function getElement($elementName)
    {
        if ($this->dataPanel->get($elementName)) {
            return $this->dataPanel->get($elementName);
        }
        if ($this->actionPanel->get($elementName)) {
            return $this->actionPanel->get($elementName);
        }
        if ($this->navPanel->get($elementName)) {
            return $this->navPanel->get($elementName);
        }
        if ($this->searchPanel->get($elementName)) {
            return $this->searchPanel->get($elementName);
        }
        if ($this->wizardPanel) {
            if ($this->wizardPanel->get($elementName))
                return $this->wizardPanel->get($elementName);
        }
    }

    /**
     * Get error elements
     *
     * @param array $fields
     * @return array
     */
    public function getErrorElements($fields)
    {
        $errElements = array();
        foreach ($fields as $field => $error) {
            $element = $this->dataPanel->getByField($field);
            $errElements[$element->objectName] = $error;
        }
        return $errElements;
    }

    public function setRecordId($val)
    {
        $this->recordId = $val;
    }

    public function setFormInputs($inputArr = null)
    {
        if (!$inputArr) {
            $inputArr = $this->formInputs;
        }
        if (!is_array($inputArr)) {
            $inputArr = array();
        }
        foreach ($this->dataPanel as $element) {
            if (isset($inputArr[$element->objectName])) {
                $element->setValue($inputArr[$element->objectName]);
            }
        }

        foreach ($this->searchPanel as $element) {
            if (isset($inputArr[$element->objectName])) {
                $element->setValue($inputArr[$element->objectName]);
            }
        }
        return $inputArr;
    }

// -------------------------- Render Methods ---------------------- //
    /**
     * Render this form (return html content),
     * called by WebPage's render method (called when form is loaded).
     * Query is issued before returning the html content.
     *
     * @return string - HTML text of this form's read mode
     * @example ../../../example/FormObject.php
     */
    public function render()
    {
        if (!$this->allowAccess())
            return "";
        //$this->setClientScripts();

        if ($this->cacheLifeTime > 0 && $this->subForms == null) {
            $cache_id = md5($this->objectName);
            //try to process cache service.
            $cacheSvc = Openbizx::getService(CACHE_SERVICE, 1);
            $cacheSvc->init($this->objectName, $this->cacheLifeTime);
            if ($cacheSvc->test($cache_id)) {
                Openbizx::$app->getLog()->log(LOG_DEBUG, "FORM", "Cache Hit. form name = " . $this->objectName);
                $output = $cacheSvc->load($cache_id);
            } else {
                Openbizx::$app->getLog()->log(LOG_DEBUG, "FORM", "Set cache. form name = " . $this->objectName);
                $output = FormRenderer::render($this);
                $cacheSvc->save($output, $cache_id);
            }
            return $output;
        }

        //Moved the renderHTML function infront of declaring subforms
        $output = FormRenderer::render($this);

        // lazy subform loading - prepare the subforms' dataobjs, since the subform relates to parent form by dataobj association
        $this->prepareSubFormsDataObj();

        return $output;
    }

    /**
     * Rerender this form (form is rendered already) .
     *
     * @param boolean $redrawForm - whether render this form again or not, optional default true
     * @param boolean $hasRecordChange - if record change, need to render subforms, optional default true
     * @return string - HTML text of this form's read mode
     */
    public function rerender($redrawForm = true, $hasRecordChange = true)
    {
        if ($redrawForm) {
            Openbizx::$app->getClientProxy()->redrawForm($this->objectName, FormRenderer::render($this));
        }

        if ($hasRecordChange) {
            $this->rerenderSubForms();
        }
    }

    /**
     * Rerender sub forms who has dependecy on this form.
     * This method is called when parent form's change affect the sub forms
     *
     * @return void
     */
    protected function rerenderSubForms()
    {
        if (!$this->subForms) {
            return;
        }
        $this->prepareSubFormsDataObj();
        foreach ($this->subForms as $subForm) {
            $formObj = Openbizx::getObject($subForm);
            $formObj->rerender();
        }
        return;
    }

    protected function prepareSubFormsDataObj()
    {
        if ($this->subForms && $this->getDataObj()) {
            foreach ($this->subForms as $subForm) {
                $formObj = Openbizx::getObject($subForm);
                $dataObj = $this->getDataObj()->getRefObject($formObj->dataObjName);
                if ($dataObj) {
                    $formObj->setDataObj($dataObj);
                }
            }
        }
    }

    /**
     * Get output attributs as array
     *
     * @return array array of attributs
     * @todo rename to getOutputAttribute or getAttribute (2.5?)
     */
    public function outputAttrs()
    {
        $output['name'] = $this->objectName;
        $output['title'] = Expression::evaluateExpression($this->title, $this);
        $output['icon'] = $this->icon;
        return $output;
    }

// -------------------------- Misc Methods ---------------------- //

    public function setRequestParams($paramFields)
    {

    }

    /**
     * Validate request from client (browser)
     *
     * @param string $methodName called from the client
     * @return boolean
     */
    public function validateRequest($methodName)
    {
        $methodName = strtolower($methodName);
        foreach ($this->directMethodList as $value) {
            if ($methodName == $value)
                return true;
        }
    }

    /**
     * Get activeRecord
     *
     * @param mixed $recId
     * @return array - record array
     */
    public function getActiveRecord($recId = null)
    {
        if ($this->activeRecord != null) {
            if ($this->activeRecord['Id'] != null) {
                return $this->activeRecord;
            }
        }

        if ($recId == null || $recId == '')
            $recId = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');
        if ($recId == null || $recId == '')
            return null;
        $this->recordId = $recId;

        // TODO: may consider cache the current record in session or pass the record from client
        if ($this->getDataObj()) {
            $this->getDataObj()->setActiveRecordId($this->recordId);
            $rec = $this->getDataObj()->getActiveRecord();

            // update the record row
            $this->dataPanel->setRecordArr($rec);

            $this->activeRecord = $rec;
        }
        return $rec;
    }

    /**
     * Set active record
     *
     * @param array $record
     * @return void
     */
    protected function setActiveRecord($record)
    {
        // update the record row
        $this->dataPanel->setRecordArr($record);

        foreach ($record as $key => $value) {
            //if($key=='extend')continue;
            $this->activeRecord[$key] = $record[$key];
        }
    }

    /**
     * Switch to other form
     *
     * @param string $formName to-be-swtiched form name. if empty, then switch to default form
     * @param string $id id value of the target form
     * @return void
     * @access remote
     */
    public function switchForm($formName = null, $id = null)
    {
        $this->formHelper->switchForm($formName, $id);
    }

    public function loadDialog($formName = null, $id = null)
    {
        $this->formHelper->loadDialog($formName, $id);
    }

// -------------------------- Tranlation Methods ---------------------- //

    protected function translate()
    {
        $module = $this->getModuleName($this->objectName);
        if (!empty($this->title)) {
            $trans_string = I18n::t($this->title, $this->getTransKey('Title'), $module, $this->getTransPrefix());
            if ($trans_string) {
                $this->title = $trans_string;
            }
        }
        if (!empty($this->icon)) {
            $trans_string = I18n::t($this->icon, $this->getTransKey('Icon'), $module, $this->getTransPrefix());
            if ($trans_string) {
                $this->icon = $trans_string;
            }
        }
        if (!empty($this->objectDescription)) {
            $trans_string = I18n::t($this->objectDescription, $this->getTransKey('Description'), $module, $this->getTransPrefix());
            if ($trans_string) {
                $this->objectDescription = $trans_string;
            }
        }
    }

    protected function getTransPrefix()
    {
        $nameArr = explode(".", $this->objectName);
        for ($i = 1; $i < count($nameArr) - 1; $i++) {
            $prefix .= strtoupper($nameArr[$i]) . "_";
        }
        return $prefix;
    }

    protected function getTransKey($name)
    {
        $shortFormName = substr($this->objectName, intval(strrpos($this->objectName, '.')) + 1);
        return strtoupper($shortFormName . '_' . $name);
    }

}

?>


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Modules\Assets;

use Assetic\Asset\AssetCollection;
use Assetic\Filter\CssMinFilter;
use Assetic\Filter\PackerFilter;

/**
 * AssetCollection class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class AssetsCollection
{
    /**
     * @var array
     */
    protected $assets;

    /**
     * @var string
     */
    protected $meta_type = null;

    /**
     * @param array $assets
     */
    public function __construct(array $assets)
    {
        $this->assets = $assets;
    }

    /**
     * @param Asset $asset
     */
    public function addAsset(Asset $asset)
    {
        $this->assets[] = $asset;
    }

    /**
     * @return array
     */
    public function getAssets()
    {
        return $this->assets;
    }

    /**
     * @return string
     */
    public function getMetaType()
    {
        if (!is_null($this->meta_type)) {
            return $this->meta_type;
        }
        $this->meta_type = empty($this->assets) ? 'js' : $this->assets[0]->getMetaType();
        return $this->meta_type;
    }

    /**
     * @param string $assets_dir
     * @param array $filters
     *
     * @return string
     */
    public function dump($assets_dir, array $filters = [])
    {
        $assets        = [];
        $assets_pathes = [];

        foreach ($this->assets as $asset) {
            $assets[]        = $asset->getFileAsset($assets_dir);
            $assets_pathes[] = $asset->getTempPath();
        }

        $collection = new AssetCollection($assets, $filters);
        $collection_dump = $collection->dump();

        foreach ($assets_pathes as $asset_path) {
            @unlink($asset_path);
        }
        return $collection_dump;
    }

    /**
     * @param string $assets_dir
     *
     * @return string
     */
    public function dumpCompress($assets_dir)
    {
        $filters = [];
        if ($this->assets[0]->getType() === 'js') {
            $filters[] = new PackerFilter();
        } else {
            $filters[] = new CssMinFilter();
        }

        return $this->dump($assets_dir, $filters);
    }

    /**
     * @return integer
     *
     * @throws \RuntimeException
     */
    public function getLastModified()
    {
        $last_modified = 0;
        foreach ($this->assets as $asset) {
            if (!file_exists($asset->getPath())) {
                throw new \RuntimeException(sprintf('The source file "%s" doesn`t exists: ', $asset->getURL()));
            }

            $asset_last_modified = filemtime($asset->getPath());
            if ($asset_last_modified > $last_modified) {
                $last_modified = $asset_last_modified;
            }
        }
        return $last_modified;
    }
}


<?php
/*
 * This file is part of the RedKite CMS Application and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://redkite-labs.com
 *
 * @license    MIT License
 */

namespace RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\Bundle;

use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Exception\InvalidJsonParameterException;

/**
 * Parses a json autoloader and converts it into an object
 *
 * @author RedKite Labs <info@redkite-labs.com>
 */
class Bundle
{
    private $name = null;
    private $class = null;
    private $overrides = null;

    /**
     * Returns the bundle name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the class that defines the bundle
     *
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * Sets the bundle class
     *
     * @param  string                                               $class
     * @return \RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\Bundle\Bundle
     * @throws InvalidJsonParameterException
     */
    public function setClass($class)
    {
        preg_match('/\\\([\w]+Bundle)$/', $class, $match);
        if (empty($match[1])) {
            throw new InvalidJsonParameterException(sprintf("The class %s does not seem to be a valid bundle class. Check your autoloader.json file", $class));
        }
        $this->name = basename($match[1]);
        $this->class = $class;

        return $this;
    }

    /**
     * Returns an array which contains the overrided bundles or null
     *
     * @return array|null
     */
    public function getOverrides()
    {
        return $this->overrides;
    }

    /**
     * Sets the overrides bundles
     *
     * @param  array                                                $overrides
     * @return \RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\Bundle\Bundle
     */
    public function setOverrides(array $overrides)
    {
        $this->overrides = $overrides;

        return $this;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: sicmouse
 * Date: 2018/9/25
 * Time: 下午1:42
 */

namespace DdvPhp\DdvUtil\Laravel\Proxy\Traits;

use Closure;

trait NextTransaction
{
    /**
     * 保存一个闭包
     * @var array|callable|Closure|string
     */
    protected $nextHander;

    /**
     * 传入一个闭包
     * NextTransaction constructor.
     * @param array|callable|Closure|string|null $nextHander
     */
    public function __construct($nextHander = null)
    {
        if (!is_null($nextHander)) {
            $this->nextHander = $nextHander;
        }
    }

    /**
     * 调用下一个事物
     * @return bool
     */
    public function __invoke()
    {
        return $this->next();
    }

    /**
     * 调用下一个事物
     * @return bool
     */
    public function next()
    {
        if (isset($this->nextHander)) {
            // 存储
            $hander = &$this->nextHander;
            // 释放
            unset($this->nextHander);
            // 调用
            return call_user_func($hander);
        }
        return false;
    }
}


<?php namespace FelipeeDev\Utilities;

abstract class Dictionary
{
    /**
     * @var string
     */
    protected $prefix = 'dictionary';

    /**
     * Words with a static keys.
     *
     * @var array
     */
    protected $words = [];

    /**
     * Get a value by a given key from dictionary.
     *
     * @param $key
     * @return string
     */
    public function get($key)
    {
        return array_get($this->words, $key, $key);
    }

    /**
     * Get translation key.
     *
     * @param string|int $key
     * @return string
     */
    public function getTranslationKey($key): string
    {
        return sprintf('%s.%s', $this->prefix, kebab_case($this->get($key)));
    }

    /**
     * Get translated word from dictionary by given key.
     *
     * @param string|int $key
     * @return string
     */
    public function trans($key)
    {
        return trans($this->getTranslationKey($key));
    }

    /**
     * Get full list of dictionary.
     *
     * @return array
     */
    public function words(): array
    {
        return $this->words;
    }

    /**
     * Get full list of dictionary with translated words from dictionary.
     *
     * @return array
     */
    public function lists(): array
    {
        $data = [];
        foreach (array_keys($this->words) as $key) {
            $data[$key] = $this->trans($key);
        }

        return $data;
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: cacheService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

use Zend\Cache\StorageFactory;

/**
 * accessService class is the plug-in service of handling cache
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class cacheService
{
    public $cache = "Disbaled";
    public $cacheEngine = "File";
    protected $cacheOptions = array();
    protected $cacheEngineOptions = array();
    protected $cacheObj = null;

    /**
     * Initialize accessService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    /**
     * Destroy cache
     *
     * @return void
     */
    public function destroy()
    {
        //$this->cache = null;
        //$this->cacheEngine = null;
        //$this->cacheObj = null;
        //$this->cacheOptions = null;
        //$this->cacheEngineOptions = null;
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->cache = isset($xmlArr["PLUGINSERVICE"]["CACHESETTING"]["ATTRIBUTES"]["MODE"]) ? $xmlArr["PLUGINSERVICE"]["CACHESETTING"]["ATTRIBUTES"]["MODE"] : "Enabled";
        $this->cacheEngine = isset($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["ATTRIBUTES"]["TYPE"]) ? $xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["ATTRIBUTES"]["TYPE"] : "FileCache";
        // process Cache settings
        if (strtoupper($this->cache) == "ENABLED") {
            $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHESETTING"]["CONFIG"], $this->cacheOptions);
        }
        switch (strtoupper($this->cacheEngine)) {
            case "FILE":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["FILE"]["CONFIG"], $this->cacheEngineOptions);
                //no break there , because all other engine is inherit from FileCache
                break;

            case "SQLITE":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["SQLITE"]["CONFIG"], $this->cacheEngineOptions);
                break;

            case "MEMCACHED":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["MEMCACHED"]["CONFIG"], $this->cacheEngineOptions);
                break;

            case "XCACHE":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["XCACHE"]["CONFIG"], $this->cacheEngineOptions);
                break;

            case "APC":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["APC"]["CONFIG"], $this->cacheEngineOptions);
                break;

            case "ZENDPLATFORM":
                $this->loadConfig($xmlArr["PLUGINSERVICE"]["CACHEENGINE"]["ZENDPLATFORM"]["CONFIG"], $this->cacheEngineOptions);
                break;
        }
    }

    /**
     * Load cache configuratoon
     *
     * @param array $configs
     * @param array $options
     * @return void
     */
    private function loadConfig(&$configs, &$options)
    {
        foreach ($configs as $config) {
            $value_up = strtoupper($config["ATTRIBUTES"]["VALUE"]);
            if ($value_up == "Y") {
                $config["ATTRIBUTES"]["VALUE"] = true;
            } elseif ($value_up == "N") {
                $config["ATTRIBUTES"]["VALUE"] = false;
            }
            $options[$config["ATTRIBUTES"]["NAME"]] = $config["ATTRIBUTES"]["VALUE"];
            if ($config["ATTRIBUTES"]["NAME"] == 'cache_dir') {
                $options[$config["ATTRIBUTES"]["NAME"]] = OPENBIZ_CACHE_PATH . "/" . $config["ATTRIBUTES"]["VALUE"];
            }
        }
    }

    /**
     * Initialize cache
     *
     * @param string $objName
     * @param number $lifeTime
     * @return boolean|\Zend_Cache
     */
    public function init($objName = "", $lifeTime = 0)
    {
        if (strtoupper($this->cache) == "ENABLED") {
            if (strtoupper($this->cacheEngine) == "FILE" && $objName != "") {
                $objfolder = str_replace(".", "/", $objName) . "/";
                $objfolder = str_replace(array(':', ' '), '_', $objfolder);
                if (!strpos($this->cacheEngineOptions['cache_dir'], $objfolder)) {
                    $this->cacheEngineOptions['cache_dir'].=$objfolder;
                }
            }

            if (!file_exists($this->cacheEngineOptions['cache_dir'])) {
                $this->_makeDirectory($this->cacheEngineOptions['cache_dir'], 0777);
            }

            $this->cacheOptions['automatic_serialization'] = true;

            if ((int) $lifeTime > 0) {
                $this->cacheOptions['lifetime'] = (int) $lifeTime;
            }

            //require_once 'Zend/Cache.php';
            $this->cacheObj = \Zend_Cache::factory(
                            'Core', $this->cacheEngine, $this->cacheOptions, $this->cacheEngineOptions
            );
            return $this->cacheObj;
        } else {
            return false;
        }
    }

    /**
     * Save cache
     *
     * @param mixed $data
     * @param string $id
     * @return boolean true if no problem
     */
    public function save($data, $id)
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->save($data, $id);
        } else {
            return false;
        }
    }

    /**
     * Load cache
     *
     * @param string $id cache id
     * @return mixed cached datas (or false)
     */
    public function load($id)
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->load($id);
        } else {
            return false;
        }
    }

    /**
     * Test cache
     *
     * @param string $id cache id
     * @return boolean true is a cache is available, false else
     */
    public function test($id)
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->test($id);
        } else {
            return false;
        }
    }

    /**
     * Remove a cache
     *
     * @param string $id cache id to remove
     * @return boolean true if ok
     */
    public function remove($id)
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->remove($id);
        } else {
            return false;
        }
    }

    /**
     * get a list of all caches
     *
     * @return array ids
     */
    public function getIds()
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->getIds();
        } else {
            return false;
        }
    }

    /**
     * clean all cache
     *
     * @return boolean true if ok
     */
    public function cleanAll()
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->clean(\Zend_Cache::CLEANING_MODE_ALL);
        } else {
            return false;
        }
    }

    /**
     * clean Expired
     *
     * @return boolean true if ok
     */
    public function cleanExpired()
    {
        if ($this->cacheObj && strtoupper($this->cache) == "ENABLED") {
            return $this->cacheObj->clean(\Zend_Cache::CLEANING_MODE_OLD);
        } else {
            return false;
        }
    }

    /**
     * Make directory recursively
     *
     * @param string $pathName The directory path.
     * @param int $mode<p>
     * The mode is 0777 by default, which means the widest possible
     * access. For more information on modes, read the details
     * on the chmod page.
     * @return bool Returns true on success or false on failure.
     * @todo need move to utility class or helper?
     */
    private function _makeDirectory($pathName, $mode)
    {
        is_dir(dirname($pathName)) || $this->_makeDirectory(dirname($pathName), $mode);
        return is_dir($pathName) || @mkdir($pathName, $mode);
    }

}


<?php

namespace Herald\Client;

// use GuzzleHttp\Post\PostFile;
use GuzzleHttp\Client as GuzzleClient;

class Client implements MessageSenderInterface
{
    private $apiUrl;
    private $baseUrl;
    private $username;
    private $password;
    private $transportAccount;
    private $templateNamePrefix = '';
    private $toAddressOverride = null;
    private $account;
    private $library;

    public function __construct(
        $username,
        $password,
        $apiUrl,
        $account,
        $library,
        $transportAccount = null
    ) {
        $this->username = $username;
        $this->password = $password;
        $this->apiUrl = $apiUrl;
        $this->account = $account;
        $this->library = $library;
        if (!$transportAccount) {
            $transportAccount = '-';
        }
        $this->transportAccount = $transportAccount;
        $this->baseUrl = $apiUrl.'/'.$account.'/'.$library;
    }

    public static function fromDsn($dsn)
    {
        if (!filter_var($dsn, FILTER_VALIDATE_URL)) {
            throw new RuntimeException('DSN is an invalid URL: '.$dsn);
        }

        $part = parse_url($dsn);
        $port = $part['port'] ? ':'.$part['port'] : '';

        $username = $part['user'];
        $password = $part['pass'];
        $apiUrl = $part['scheme'].'://'.$part['host'].$port.'/api/v2';
        $part['path'] = trim($part['path'], '/');
        $pathPart = explode('/', $part['path']);
        if ((count($pathPart) < 2) || (count($pathPart) > 3)) {
            throw new RuntimeException('Expecting url path with exactly 2 or 3 parts: '.$part['path']);
        }

        $account = $pathPart[0];
        $library = $pathPart[1];
        $transportAccount = null;
        if (count($pathPart) > 2) {
            $transportAccount = $pathPart[2];
        }

        return new self($username, $password, $apiUrl, $account, $library, $transportAccount);
    }

    public function send(MessageInterface $message, $skipNamePrefix = false)
    {
        $guzzleclient = new GuzzleClient();

        $url = $this->baseUrl.'/send/';
        $url .= $this->transportAccount.'/';
        $url .= $this->patchTemplateName($message->getTemplate(), $skipNamePrefix);
        $url .= '?to='.($this->toAddressOverride ? $this->toAddressOverride : $message->getToAddress());

        $res = $guzzleclient->post($url, [
            'auth' => [$this->username, $this->password],
            'headers' => ['content-type' => 'application/json'],
            'body' => $message->serializeData(),
        ]);

        return 200 == $res->getStatusCode();
    }

    public function templateExists($templateName, $skipNamePrefix = false)
    {
        $guzzleclient = new GuzzleClient();

        $url = $this->baseUrl.'/checktemplate/'.$this->patchTemplateName($templateName, $skipNamePrefix);

        $res = $guzzleclient->post($url, [
            'auth' => [$this->username, $this->password],
        ]);

        $body = json_decode($res->getBody());

        if ('OK' == strtoupper($body->code)) {
            return true;
        }

        return false;
    }

    private function patchTemplateName($templateName, $skipNamePrefix = false)
    {
        if ($skipNamePrefix) {
            return $this->escapeTemplateName($templateName);
        } else {
            return $this->escapeTemplateName($this->templateNamePrefix.$templateName);
        }
    }

    private function escapeTemplateName($templateName)
    {
        return str_replace('/', '___', $templateName);
    }

    public function getMessages()
    {
        $guzzleclient = new GuzzleClient();

        $url = $this->baseUrl.'/messages';

        $res = $guzzleclient->post($url, [
            'auth' => [$this->username, $this->password],
        ]);

        $body = $res->getBody();
        if ($body) {
            if ('ok' == $body->read(2)) {
                return true;
            }
        }
        $content = (string) $body;
        $data = json_decode($content, true);
        //print_r($data);

        /*
        // This return object //

        $messages = array();

        foreach ($data['items'] as $m) {
            $message = $this->arrayToMessage($m);
            $messages[] = $message;
        }

        return $messages;
        */
        return $data;
    }

    public function getMessageById($messageId)
    {
        $guzzleclient = new GuzzleClient();

        $url = $this->baseUrl.'/messages/'.$messageId;

        $res = $guzzleclient->post($url, [
            'auth' => [$this->username, $this->password],
        ]);

        $body = $res->getBody();
        if ($body) {
            if ('ok' == $body->read(2)) {
                return true;
            }
        }
        $content = (string) $body;
        $data = json_decode($content, true);

        // This return object //
        // $message = $this->arrayToMessage($data);
        // return $message;

        return $data;
    }

    // -----------------------------------------------------------

    private function doQuery($method, $url, $data = null)
    {
        $guzzleclient = new GuzzleClient();

        if (false !== stristr($method, 'get')) {
            $res = $guzzleclient->get($this->baseUrl.'/'.$url, [
                'auth' => [$this->username, $this->password],
            ]);
        } else {
            $res = $guzzleclient->post($this->baseUrl.'/'.$url, [
                'auth' => [$this->username, $this->password],
                'json' => $data,
            ]);
        }

        return json_decode($res->getBody(), true);
    }

    public function getLists()
    {
        return $this->doQuery('GET', 'list');
    }

    public function getContacts($listId)
    {
        return $this->doQuery('GET', 'list/'.$listId);
    }

    public function getListConditions($listId)
    {
        return $this->doQuery('GET', 'list/'.$listId.'/conditions');
    }

    public function viewContact($contactId)
    {
        return $this->doQuery('GET', 'contact/'.$contactId);
    }

    public function deleteContact($contactId)
    {
        return $this->doQuery('GET', 'contact/'.$contactId.'/delete');
    }

    public function addContact($listId, $address)
    {
        return $this->doQuery('GET', 'contact/add/'.$listId.'/'.$address, []);
    }

    public function getContactProperties($contactId)
    {
        return $this->doQuery('GET', 'contact/'.$contactId.'/contact_property');
    }

    public function deleteProperty($propertyId)
    {
        return $this->doQuery('GET', 'contact_property/'.$propertyId.'/delete');
    }

    public function addProperty($contactId, $fieldId, $value)
    {
        return $this->doQuery('POST', 'contact_property/add', [
            'fieldId' => $fieldId,
            'contactId' => $contactId,
            'value' => $value,
        ]);
    }

    //---------------------------- -----------------------------
    // ------------ Message convert to Object-------------------
    private function arrayToMessage($m)
    {
        $message = new Message();
        $message->setId($m['id']);
        $message->setUuid($m['uuid']);
        $message->setUser($m['user']);
        $message->setStamp($m['stamp']);
        $message->setStatus($m['status']);
        $message->setFromAddress($m['fromAddress']);
        $message->setFromName($m['fromName']);

        $addresses = $this->parseAddresses($m['to']);
        $message->setTo($addresses);

        $addresses = $this->parseAddresses($m['cc']);
        $message->setCc($addresses);

        $addresses = $this->parseAddresses($m['bcc']);
        $message->setBcc($addresses);

        $message->setSubject($m['subject']);

        if (isset($m['template'])) {
            $t = $m['template'];
            $template = new Template();
            $template->setId($t['id']);
            //$template->setUuid($m['template']['uuid']);
            $template->setCode($t['code']);
            $template->setUser($t['user']);
            $template->setStatus($t['status']);
            $template->setFromAddress($t['fromEmail']);
            $template->setFromName($t['fromName']);

            $addresses = $this->parseAddresses($t['cc']);
            $template->setCc($addresses);

            $addresses = $this->parseAddresses($t['bcc']);
            $template->setBcc($addresses);

            $template->setBody($t['body']);
            $template->setBodyMarkup($t['bodyMarkup']);

            if (isset($t['layout'])) {
                $l = $t['layout'];
                $layout = new Layout();
                $layout->setId($l['id']);
                $layout->setCode($l['code']);
                $layout->setBody($l['body']);
                $template->setLayout($layout);
            }
            $message->setTemplate($template);
        }

        return $message;
    }

    /*
     * Current server returns a JSON string, not actual array data
     * This method detects strings and decodes them
     * Then it instantiates a new Address object for every item and returns
     * an array of Address objects
     */
    private function parseAddresses($addresses)
    {
        if (!$addresses) {
            return array();
        }
        if (is_string($addresses)) {
            // old format json string, parse to array
            if ('[' != $addresses[0]) {
                // Expecting a json array, assuming single address
                $address = new Address();
                //todo: parse in id, uuid and type if set
                $address->setIdentifier($addresses);
                $address->setName('');
                $address->setType('email');

                return array($address);
            }
            $addresses = json_decode($addresses, true);
        }

        $res = array();
        foreach ($addresses as $a) {
            $address = new Address();
            //todo: parse in id, uuid and type if set
            $address->setIdentifier($a['identifier']);
            $address->setName($a['name']);
            $address->setType('email');
            $res[] = $address;
        }

        return $res;
    }

    public function setTemplateNamePrefix($prefix)
    {
        $this->templateNamePrefix = $prefix;
        return $this;
    }

    public function setToAddressOverride($address)
    {
        $this->toAddressOverride = $address;

        return $this;
    }

    public function getTemplates()
    {
        return $this->doQuery('GET', 'templates');
    }

    public function changeContactAddress($oldAddress, $newAddress)
    {
        return $this->doQuery('POST', 'contact/change', [
            'from' => $oldAddress,
            'to' => $newAddress,
        ]);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: hua
 * Date: 2018/9/16
 * Time: 下午3:44
 */

namespace DdvPhp\DdvUtil\Laravel\Proxy\Traits;

use Closure;

trait Response
{
    // 结果集合
    protected $responses = array();
    // 处理闭包
    protected $toResponse = null;

    /**
     * @param $key
     * @param $value
     */
    public function setResponse($key, $value)
    {
        if ($key === static::RESPONSES_DATA_ARRAY_MERGE) {
            // 如果$key为false就是需要强制重写所有输出
            if (is_array($value)) {
                $this->responses = array_merge($this->responses, $value);
            } else {
                $this->responses = $value;
            }
        } else if ($key === static::RESPONSES_DATA_ARRAY_REPLACE) {
            // 如果$key为true就是需要强制重写所有输出
            $this->responses = $value;
        } else if (isset($key) && (is_string($key) || is_numeric($key))) {
            // 把返回数据保存起来
            $this->responses[(string)$key] = $value;
        }
        // 释放内存
        unset($key, $value);
        //
        return $this;
    }

    /**
     * @param Closure $fn
     * @return $this
     */
    public function setToResponseClosure(Closure $fn)
    {
        $this->toResponse = $fn;
        return $this;
    }

    /**
     * @return $this
     */
    public function clearToResponseClosure()
    {
        $this->toResponse = null;
        return $this;
    }

    /**
     * 获取返回结果
     * @return mixed|array
     */
    public function getResponse()
    {
        /**
         * @var Closure $toResponse
         */
        $toResponse = $this->toResponse;

        if ($toResponse instanceof Closure) {
            $res = $toResponse($this->responses, $this);
        } else {
            $res = empty($this->responses) ? null : $this->responses;
        }
        return $res;
    }

    /**
     * 获取分页数据和数据库数据
     * @return array $res [分页数据和查询数据]
     */
    public function toArray()
    {
        return ['data' => $this->getResponse()];
    }

    /**
     * Convert the object into something JSON serializable.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }

    /**
     * Convert the object to its JSON representation.
     *
     * @param  int $options
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->jsonSerialize(), $options);
    }

    /**
     * Convert the object to its JSON representation.
     *
     * @param  int $options
     * @return string
     */
    public function __toString()
    {
        return $this->toJson();
    }

}


<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 13/11/2018
 * Time: 23:42
 */

namespace vr\core\validators;

use yii\helpers\ArrayHelper;

/**
 * Trait ArrayFilterTrait
 * @package vr\core\validators
 */
trait ArrayFilterTrait
{
    /**
     * @param $entity
     *
     * @return array|string
     */
    public static function getAllowedAttributes($entity)
    {
        /** @noinspection PhpUndefinedMethodInspection */
        $validators = (new self())->getActiveValidators($entity);
        foreach ($validators as $validator) {
            if ($validator instanceof ArrayFilterValidator) {
                return ArrayHelper::getValue($validator, 'allowed');
            }
        }

        return [];
    }
}


<?php

namespace Environaut\Config;

use Environaut\Checks\Validator;
use Environaut\Config\BaseConfigHandler;
use Environaut\Config\Reader\IConfigReader;
use Environaut\Config\Reader\JsonConfigReader;
use Environaut\Config\Reader\PhpConfigReader;
use Environaut\Config\Reader\XmlConfigReader;

/**
 * Default config handler that reads a config file from the
 * given locations. Supported are JSON, XML and PHP config
 * file formats.
 */
class ConfigHandler extends BaseConfigHandler
{
    /**
     * @var array supported config file extensions
     */
    protected $supported_file_extensions = array('json', 'xml', 'php');

    /**
     * @var array default config file names (order is important)
     */
    protected $default_filenames = array('environaut.xml', 'environaut.json', 'environaut.php');

    /**
     * Reads a config file from the given location and returns it's
     * data as an associative array.
     *
     * @param mixed $location location of config file (as a string with a file or directory path)
     *
     * @return array config data
     *
     * @throws \InvalidArgumentException on errors like missing config file
     */
    protected function readLocation($location)
    {
        $reader = null;

        if (is_dir($location)) {
            $base_location = Validator::fixPath(Validator::fixRelativePath($location));
            foreach ($this->default_filenames as $filename) {
                $file = $base_location . $filename;
                if (is_readable($file)) {
                    try {
                        $reader = $this->getReaderByExtension($file);
                        break; // found possible config file \o/
                    } catch (\InvalidArgumentException $e) {
                        // next attempt as extension has no handler
                    }
                }
                // next attempt, as file is not readable or does not exist
            }

            if (!$reader instanceof IConfigReader) {
                throw new \InvalidArgumentException(
                    'Could not find an environaut config file in "' . $base_location . '".' . PHP_EOL .
                    'Attempted files were: ' . implode(', ', $this->default_filenames) . '.' . PHP_EOL .
                    'Try calling from a different folder or specify a file using the "--config" option.'
                );
            }
        } elseif (is_file($location)) {
            $reader = $this->getReaderByExtension($location);
        } else {
            throw new \InvalidArgumentException(
                'Currently only regular files and directories are supported for config file reading.'
            );
        }

        $config_data = $reader->getConfigData($location);

        return $config_data;
    }

    /**
     * Returns a specific reader instance depending on the file
     * extension of the given config file location.
     *
     * @param string $location
     *
     * @return IConfigReader
     *
     * @throws \InvalidArgumentException in case of unsupported file extensions
     */
    protected function getReaderByExtension($location)
    {
        $ext = pathinfo($location, PATHINFO_EXTENSION);

        $reader = null;

        switch ($ext) {
            case 'json':
                $reader = new JsonConfigReader();
                break;
            case 'xml':
                $reader = new XmlConfigReader();
                break;
            case 'php':
                $reader = new PhpConfigReader();
                break;
            default:
                throw new \InvalidArgumentException(
                    'File could not be read: ' . $location . PHP_EOL .
                    'Supported config file extensions are: ' . implode(', ', $this->supported_file_extensions)
                );
                break;
        }

        return $reader;
    }
}


<?php
/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace TwitterWidgets\Options;

use InvalidArgumentException;
use Zend\Stdlib\AbstractOptions;

/**
 * Class for the client side cumtomization
 *
 * @license MIT
 * @link    https://dev.twitter.com/web/embedded-timelines#customization
 * @author  mpalourdio <mpalourdio@gmail.com>
 */
class WidgetOptions extends AbstractOptions implements WidgetOptionsInterface
{
    /**
     * @var string
     *
     * CSS class for the timeline. Provides the twitter one by default
     */
    protected $class = 'twitter-timeline';
    /**
     * @var string
     *
     * Timeline URL
     */
    protected $href;

    /**
     * @var string
     *
     * Text for the link that appears above the timeline
     * ie: tweets from @mpalourdio
     */
    protected $hrefText;

    /**
     * @var string
     *
     * Your widget ID
     */
    protected $dataWidgetId;
    /**
     * @var string
     *
     * Set by adding a data-theme="dark" attribute to the embed code.
     */
    protected $dataTheme;
    /**
     * @var string
     *
     * Theme: Set by adding a data-link-color="#cc0000" attribute.
     * Note that some icons in the widget will also appear this color.
     */
    protected $dataLinkColor;

    /**
     * @var int
     *
     * Set using the standard HTML width attribute on the embed code (units are pixels.)
     */
    protected $width;
    /**
     * @var int
     *
     * Set using the standard HTML height attribute on the embed code (units are pixels.)
     */
    protected $height;
    /**
     * @var string
     *
     * Control the widget layout and chrome
     */
    protected $dataChrome;
    /**
     * @var string
     *
     * Change the border color used by the widget. Takes an #abc123 hex format color e.g. data-border-color="#cc0000"
     */
    protected $dataBorderColor;

    /**
     * @var string
     *
     * The widget language is detected from the page, based on the HTML lang attribute of your content.
     * You can also set the HTML lang attribute on the embed code itself.
     */
    protected $language;
    /**
     * @var int
     *
     * To fix the size of a timeline to a preset number of Tweets, use the data-tweet-limit="5" attribute with any value
     * between 1 and 20 Tweets. The timeline will render the specified number of Tweets from the timeline, expanding the
     * height of the widget to display all Tweets without scrolling. Since the widget is of a fixed size, it will not
     * poll for updates when using this option.
     */
    protected $dataTweetLimit;
    /**
     * @var string
     *
     * As per the Tweet and follow buttons, you may provide a comma-separated list of user screen names as suggested
     * followers to a user after they reply, Retweet, or favorite a Tweet in the timeline. Use a
     * data-related="benward,endform" attribute on the embed code.
     */
    protected $dataRelated;
    /**
     * @var string
     *
     * ARIA is an accessibility system that aids people using assistive technology interacting with dynamic web content.
     * Read more about ARIA on W3C’s website. By default, the embedded timeline uses the least obtrusive
     * setting: aria-polite="polite". If you’re using an embedded timeline as a primary source of content on your
     * page, you may wish to override this to the assertive setting, using data-aria-polite="assertive".
     */
    protected $dataAriaPolite;

    /**
     * @return string
     */
    public function getDataChrome()
    {
        return $this->dataChrome;
    }

    /**
     * @param  string $dataChrome
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataChrome($dataChrome)
    {
        if (!is_string($dataChrome) && null !== $dataChrome) {
            throw new InvalidArgumentException('An string is expected for chrome parameter');
        }

        $this->dataChrome = $dataChrome;

        return $this;
    }

    /**
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * @param  string $class
     * @throws InvalidArgumentException
     * @return self
     */
    public function setClass($class)
    {
        if (!is_string($class) && null !== $class) {
            throw new InvalidArgumentException('String expected for class parameter');
        }

        $this->class = $class;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataAriaPolite()
    {
        return $this->dataAriaPolite;
    }

    /**
     * @param  string $dataAriaPolite
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataAriaPolite($dataAriaPolite)
    {
        if (!is_string($dataAriaPolite) && null !== $dataAriaPolite) {
            throw new InvalidArgumentException('String expected for dataAriaPolite parameter');
        }

        $this->dataAriaPolite = $dataAriaPolite;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataBorderColor()
    {
        return $this->dataBorderColor;
    }

    /**
     * @param  string $dataBorderColor
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataBorderColor($dataBorderColor)
    {
        if (!is_string($dataBorderColor) && null !== $dataBorderColor) {
            throw new InvalidArgumentException('String expected for dataBorderColor parameter');
        }

        $this->dataBorderColor = $dataBorderColor;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataLinkColor()
    {
        return $this->dataLinkColor;
    }

    /**
     * @param  string $dataLinkColor
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataLinkColor($dataLinkColor)
    {
        if (!is_string($dataLinkColor) && null !== $dataLinkColor) {
            throw new InvalidArgumentException('String expected for dataLinkColor parameter');
        }

        $this->dataLinkColor = $dataLinkColor;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataRelated()
    {
        return $this->dataRelated;
    }

    /**
     * @param  string $dataRelated
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataRelated($dataRelated)
    {
        if (!is_string($dataRelated) && null !== $dataRelated) {
            throw new InvalidArgumentException('String expected for dataRelated parameter');
        }

        $this->dataRelated = $dataRelated;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataTheme()
    {
        return $this->dataTheme;
    }

    /**
     * @param  string $dataTheme
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataTheme($dataTheme)
    {
        if (!is_string($dataTheme) && null !== $dataTheme) {
            throw new InvalidArgumentException('String expected for dataTheme parameter');
        }

        $this->dataTheme = $dataTheme;

        return $this;
    }

    /**
     * @return int
     */
    public function getDataTweetLimit()
    {
        return $this->dataTweetLimit;
    }

    /**
     * @param  int $dataTweetLimit
     * @throws InvalidArgumentException
     * @return self
     */
    public function setDataTweetLimit($dataTweetLimit)
    {
        if (!is_int($dataTweetLimit) && null !== $dataTweetLimit) {
            throw new InvalidArgumentException('Integer expected for dataTweetLimit parameter');
        }

        $this->dataTweetLimit = $dataTweetLimit;

        return $this;
    }

    /**
     * @return string
     */
    public function getDataWidgetId()
    {
        return $this->dataWidgetId;
    }

    /**
     * @param  string $dataWidgetId
     * @throws InvalidArgumentException
     * @return self
     *
     * Note: long integers will be converted to float (32 bits). Give this setter a string
     */
    public function setDataWidgetId($dataWidgetId)
    {
        if (!is_string($dataWidgetId) && null !== $dataWidgetId) {
            throw new InvalidArgumentException(
                'String is expected for dataWidgetId (long int can lead to float conversion)'
            );
        }

        $this->dataWidgetId = $dataWidgetId;

        return $this;
    }

    /**
     * @return int
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * @param  int $height
     * @throws InvalidArgumentException
     * @return self
     */
    public function setHeight($height)
    {
        if (!is_int($height) && null !== $height) {
            throw new InvalidArgumentException('Integer expected for height parameter');
        }

        $this->height = $height;

        return $this;
    }

    /**
     * @return string
     */
    public function getHref()
    {
        return $this->href;
    }

    /**
     * @param  string $href
     * @throws InvalidArgumentException
     * @return self
     */
    public function setHref($href)
    {
        if (!is_string($href) && null !== $href) {
            throw new InvalidArgumentException('String expected for href parameter');
        }

        $this->href = $href;

        return $this;
    }

    /**
     * @return string
     */
    public function getHrefText()
    {
        return $this->hrefText;
    }

    /**
     * @param  string $hrefText
     * @throws InvalidArgumentException
     * @return self
     */
    public function setHrefText($hrefText)
    {
        if (!is_string($hrefText) && null !== $hrefText) {
            throw new InvalidArgumentException('String expected for hrefText parameter');
        }

        $this->hrefText = $hrefText;

        return $this;
    }

    /**
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @param  string $language
     * @throws InvalidArgumentException
     * @return self
     */
    public function setLanguage($language)
    {
        if (!is_string($language) && null !== $language) {
            throw new InvalidArgumentException('String expected for language parameter');
        }

        $this->language = $language;

        return $this;
    }

    /**
     * @return int
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * @param  int $width
     * @throws InvalidArgumentException
     * @return self
     */
    public function setWidth($width)
    {
        if (!is_int($width) && null !== $width) {
            throw new InvalidArgumentException('Integer expected for width parameter');
        }

        $this->width = $width;

        return $this;
    }
}


<?php

namespace Limber\Router;

class RouteBranch
{
    /**
     * Full path.
     *
     * @var string
     */
    protected $path;

    /**
     * Routes indexed by HTTP method.
     *
     * @var array<string, Route>
     */
    protected $routes = [];

    /**
     * Further branches dangling from this branch.
     *
     * @var array<string, RouteBranch>
     */
    protected $branches = [];

    /**
     * RouteBranch constructor.
     *
     * @param string $path
     */
    public function __construct(string $path = null)
    {
        if( $path ){
            $this->path = $path;
        }
    }

    /**
     * Get the route that responds to this method.
     *
     * @param string $method
     * @return Route|null
     */
    public function getRouteForMethod(string $method): ?Route
    {
        return $this->routes[$method] ?? null;
    }

    /**
     * Add a branch dangling from this branch.
     *
     * @param string $key
     * @param RouteBranch $routeBranch
     * @return RouteBranch
     */
    protected function addBranch(string $key): RouteBranch
    {
        if( array_key_exists($key, $this->branches) ){
            throw new \Exception("{$key} branch already exists for this node.");
        }

        $this->branches[$key] = new RouteBranch("{$this->path}/{$key}");
        return $this->branches[$key];
    }

    /**
     * Add route to this leaf.
     *
     * @param Route $route
     * @return void
     */
    public function addRoute(Route $route): void
    {
        foreach( $route->getMethods() as $method ){

            if( array_key_exists($method, $this->routes) ){
                throw new \Exception("{$method}#{$this->path} route has already been defined.");
            }

            $this->routes[$method] = $route;
        }
    }

    /**
     * Find the matching branch for the given URI path part.
     *
     * @param string $part
     * @return RouteBranch|null
     */
    public function findBranch(string $part): ?RouteBranch
    {
        // Try finding an exact match first.
        if( array_key_exists($part, $this->branches) ){
            return $this->branches[$part];
        }

        // Loop through each branch key and match it using a regex.
        foreach( $this->branches as $key => $branch ){
            if( preg_match("/^{$key}$/", $part) ){
                return $branch;
            }
        }

        return null;
    }

    /**
     * Get the next branch or create a new one.
     *
     * @param string $uriPart
     * @return RouteBranch
     */
    public function next(string $uriPart): RouteBranch
    {
        foreach( $this->branches as $key => $branch ){

            if( $uriPart === $key ){
                return $branch;
            }
        }

        return $this->addBranch($uriPart);
    }

    /**
     * Get all the HTTP methods this branch responsds to.
     *
     * @return array<string>
     */
    public function getMethods(): array
    {
        return array_keys($this->routes);
    }
}


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Askedio\Laravelcp\Models\Role;
use Askedio\Laravelcp\Models\User;
use Askedio\Laravelcp\Models\Permission;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::insert([
            'name' => 'admin',
            'email' => 'admin@localhost',
            'password' => bcrypt('password'),
        ]);

        User::first()->attachRole(Role::create([
            'name' => 'Admin',
            'slug' => 'admin',
            'description' => '', // optional
            'parent_id' => NULL, // optional, set to NULL by default
        ]));

        Role::first()->attachPermission(Permission::create([
            'name' => 'Admin Dashboard',
            'slug' => 'admin.dashboard',
            'description' => '', // optional
        ]));

    }
}


<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: RowCheckbox.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\InputElement;

/**
 * RowCheckbox class is input element for render RowCheckbox
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class RowCheckbox extends InputElement
{
	protected  $checkStatus;

    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->checkStatus = isset($xmlArr["ATTRIBUTES"]["CHECKSTATUS"]) ? $xmlArr["ATTRIBUTES"]["CHECKSTATUS"] : null;
    }
    /**
     * Render label
     *
     * @return string HTML text
     */
    public function renderLabel()
    {
        $formName = $this->formName;
        $name = $this->objectName.'[]';
        $sHTML = "<INPUT TYPE=\"CHECKBOX\"  onclick=\"Openbizx.Util.checkAll(this, $('$formName').select('input[name=\'$name\']'));\"/>";
        return $sHTML;
    }

    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $value = $this->value;
        $name = $this->objectName.'[]';
        $style = $this->getStyle();
        if($this->checkStatus)
        {
        	$formObj = $this->getFormObj();
        	$testResult = Expression::evaluateExpression($this->checkStatus, $formObj);
        	if($testResult)
        	{
        		$checkStatus = " checked=\"checked\" ";
        	}
        	else
        	{
        		$checkStatus = "";
        	}
        }
        else
        {
        	$checkStatus = "";
        }
        $sHTML = "<INPUT TYPE=\"CHECKBOX\" $checkStatus NAME=\"$name\" VALUE='$value' onclick=\"event.cancelBubble=true;\" $this->htmlAttr $style/>";
        return $sHTML;
    }
}

?>


<?php

/*
 * This file is part of the Kreta package.
 *
 * (c) Beñat Espiña <benatespina@gmail.com>
 * (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Kreta\Component\Comment\Repository;

use Kreta\Component\Core\Repository\EntityRepository;
use Kreta\Component\Issue\Model\Interfaces\IssueInterface;
use Kreta\Component\User\Model\Interfaces\UserInterface;

/**
 * Class CommentRepository.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 */
class CommentRepository extends EntityRepository
{
    /**
     * Finds all the comments of issue given ordering by createdAt.
     * The result can be more strict adding user and createAt criteria.
     * Can do limit and offset.
     *
     * @param \Kreta\Component\Issue\Model\Interfaces\IssueInterface $issue     The issue
     * @param \DateTime                                              $createdAt The created at
     * @param string                                                 $writtenBy The email of user
     * @param int                                                    $limit     The limit
     * @param int                                                    $offset    The offset
     *
     * @return \Kreta\Component\Comment\Model\Interfaces\CommentInterface[]
     */
    public function findByIssue(
        IssueInterface $issue,
        \DateTime $createdAt = null,
        $writtenBy = null,
        $limit = null,
        $offset = null
    ) {
        $queryBuilder = $this->getQueryBuilder();
        if ($createdAt instanceof \DateTime) {
            $this->addCriteria($queryBuilder, ['between' => ['createdAt' => $createdAt]]);
        }
        if ($writtenBy !== null) {
            $this->addCriteria($queryBuilder, ['wb.email' => $writtenBy]);
        }
        $this->addCriteria($queryBuilder, ['issue' => $issue]);
        $this->orderBy($queryBuilder, ['createdAt' => 'ASC']);

        if ($limit) {
            $queryBuilder->setMaxResults($limit);
        }
        if ($offset) {
            $queryBuilder->setFirstResult($offset);
        }

        return $queryBuilder->getQuery()->getResult();
    }

    /**
     * Finds the comments of given id if the user given is its writer.
     *
     * @param string                                               $commentId The comment id
     * @param \Kreta\Component\User\Model\Interfaces\UserInterface $user      The user
     *
     * @return \Kreta\Component\Comment\Model\Interfaces\CommentInterface
     */
    public function findByUser($commentId, UserInterface $user)
    {
        return $this->findOneBy(['id' => $commentId, 'writtenBy' => $user], false);
    }

    /**
     * {@inheritdoc}
     */
    protected function getQueryBuilder()
    {
        return parent::getQueryBuilder()
            ->addSelect(['i', 'wb'])
            ->join('c.issue', 'i')
            ->join('c.writtenBy', 'wb');
    }

    /**
     * {@inheritdoc}
     */
    protected function getAlias()
    {
        return 'c';
    }
}


<?php

namespace GetOlympus\Field;

use GetOlympus\Zeus\Field\Controller\Field;
use GetOlympus\Zeus\Translate\Controller\Translate;

/**
 * Builds Wordpress field.
 *
 * @package Field
 * @subpackage Wordpress
 * @author Achraf Chouk <achrafchouk@gmail.com>
 * @since 0.0.1
 *
 * @see https://olympus.readme.io/v1.0/docs/wordpress-field
 *
 */

class Wordpress extends Field
{
    /**
     * Prepare variables.
     */
    protected function setVars()
    {
        $this->getModel()->setFaIcon('fa-wordpress');
        $this->getModel()->setTemplate('wordpress.html.twig');
    }

    /**
     * Prepare HTML component.
     *
     * @param array $content
     * @param array $details
     */
    protected function getVars($content, $details = [])
    {
        // Build defaults
        $defaults = [
            'id' => '',
            'title' => Translate::t('wordpress.title', [], 'wordpressfield'),
            'default' => [],
            'description' => '',
            'mode' => 'posts',
            'multiple' => false,
            'options' => [],
            'value' => '',

            // Texts
            't_items' => Translate::t('wordpress.items', [], 'wordpressfield'),
        ];

        // Build defaults data
        $vars = array_merge($defaults, $content);

        // Check if an id is defined at least
        $postid = !isset($details['post_id']) ? 0 : $details['post_id'];

        // Retrieve field value
        $vars['val'] = $this->getValue($content['id'], $details, $vars['default']);
        $vars['val'] = !is_array($vars['val']) ? [$vars['val']] : $vars['val'];

        // Get the categories
        $vars['contents'] = $this->getWPContents(
            $vars['mode'],
            $vars['multiple'],
            $vars['options'],
            $postid,
            $vars['value']
        );

        // Field description
        if (!empty($vars['contents']) && 1 <= count($vars['contents'])) {
            $description = $vars['multiple'] ? Translate::t('wordpress.description', [], 'wordpressfield').'
' : '';
        } else {
            $translate = $vars['multiple'] ? 'wordpress.no_items_found' : 'wordpress.no_item_found';
            $description = sprintf(Translate::t($translate, [], 'wordpressfield'), $vars['mode']).'
';
        }

        // Update description
        $vars['description'] = $description.$vars['description'];

        // Update vars
        $this->getModel()->setVars($vars);
    }

    /**
     * Get Wordpress contents already registered.
     *
     * @param   string  $type       Wordpress content type to return
     * @param   boolean $multiple   Define if there is multiselect or not
     * @param   array   $options    Define options if needed
     * @param   integer $post_id    Define the post ID for meta boxes
     * @param   string  $value      Define the value of each select options
     * @return  array   $wpcontents Array of Wordpress content type registered
     */
    protected function getWPContents($type = 'posts', $multiple = false, $options = [], $post_id = 0, $value = '')
    {
        // Access WordPress contents
        $wpcontents = [];

        // Exclude current item
        if (isset($options['exclude']) && 'current' === $options['exclude']) {
            $options['exclude'] = $post;
        }

        // Get asked contents
        $authorized = [
            'categories', 'category',
            'menus', 'menu',
            'pages', 'page',
            'posts', 'post',
            'posttypes', 'posttype',
            'tags', 'tag',
            'taxonomies', 'taxonomy',
            'terms', 'term'
        ];

        // Check contents
        if (!in_array($type, $authorized)) {
            return [];
        }

        // Data retrieved
        if (in_array($type, ['categories', 'category'])) {
            $wptype = 'Categories';
        } else if (in_array($type, ['menus', 'menu'])) {
            $wptype = 'Menus';
        } else if (in_array($type, ['pages', 'page'])) {
            $wptype = 'Pages';
        } else if (in_array($type, ['posts', 'post'])) {
            $wptype = 'Posts';
        } else if (in_array($type, ['posttypes', 'posttype'])) {
            $wptype = 'Posttypes';
        } else if (in_array($type, ['tags', 'tag'])) {
            $wptype = 'Tags';
        } else if (in_array($type, ['taxonomies', 'taxonomy'])) {
            $wptype = 'Taxonomies';
        } else {
            $wptype = 'Terms';
        }

        // Get contents
        $function = 'getWP'.$wptype;
        $wpcontents = $this->$function($options, $value);

        // Return value
        return $wpcontents;
    }

    /**
     * Get WordPress Categories registered.
     *
     * @uses get_categories()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPCategories($options = [], $value = 'cat_ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.category', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => 0,
            'orderby' => 'name',
            'order' => 'ASC',
            'parent' => 0,
        ], $options);

        // Build request
        $categories_obj = get_categories($args);

        // Iterate on categories
        if (!empty($categories_obj)) {
            foreach ($categories_obj as $cat) {
                // For Wordpress version < 3.0
                if (empty($cat->cat_ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($cat->$value) ? $cat->$value : $cat->cat_ID;

                // Get the id and the name
                $contents[0][$item] = $cat->cat_name;

                // Get children
                $contents = $this->getWPSubCategories($contents, $cat->cat_ID, $value);
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Sub Categories registered.
     *
     * @uses get_categories()
     *
     * @param   array   $contents   Define all already set contents
     * @param   integer $parent     Define parent category
     * @param   string  $value      Define the value of each select options
     * @param   string  $prefix     Define text to display before name
     * @return  array   $wpcontents Array of WordPress items
     */
    protected function getWPSubCategories($contents = [], $parent = 0, $value = 'cat_ID', $prefix = '— ')
    {
        // Build request
        $categories_obj = get_categories([
            'hide_empty' => 0,
            'orderby' => 'name',
            'order' => 'ASC',
            'parent' => $parent,
        ]);

        // Iterate on categories
        if (!empty($categories_obj)) {
            foreach ($categories_obj as $cat) {
                // For Wordpress version < 3.0
                if (empty($cat->cat_ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($cat->$value) ? $cat->$value : $cat->cat_ID;

                // Get the id and the name
                $contents[0][$item] = $prefix.$cat->cat_name;

                // Get children
                $contents = $this->getWPSubCategories($contents, $cat->cat_ID, $value, $prefix.'— ');
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Menus registered.
     *
     * @uses wp_get_nav_menus()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPMenus($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.menu', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => false,
            'orderby' => 'none'
        ], $options);

        // Build request
        $menus_obj = wp_get_nav_menus($args);

        // Iterate on menus
        if (!empty($menus_obj)) {
            foreach ($menus_obj as $menu) {
                // For Wordpress version < 3.0
                if (empty($menu->term_id)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($menu->$value) ? $menu->$value : $menu->term_id;

                // Get the id and the name
                $contents[0][$item] = $menu->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Pages registered.
     *
     * @uses get_pages()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPPages($options = [], $value = 'ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.page', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'sort_column' => 'post_parent,menu_order'
        ], $options);

        // Build request
        $pages_obj = get_pages($args);

        // Iterate on pages
        if (!empty($pages_obj)) {
            foreach ($pages_obj as $pag) {
                // For Wordpress version < 3.0
                if (empty($pag->ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($pag->$value) ? $pag->$value : $pag->ID;

                // Get the id and the name
                $contents[0][$item] = $pag->post_title;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Posts registered.
     *
     * @uses wp_get_recent_posts()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPPosts($options = [], $value = 'ID')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.post', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'post_type' => 'post',
            'post_status' => 'publish'
        ], $options);

        // Build request
        $posts_obj = wp_get_recent_posts($args, OBJECT);

        // Iterate on posts
        if (!empty($posts_obj)) {
            foreach ($posts_obj as $pos) {
                // For Wordpress version < 3.0
                if (empty($pos->ID)) {
                    continue;
                }

                // Check value
                $item = !empty($value) && isset($pos->$value) ? $pos->$value : $pos->ID;

                // Get the id and the name
                $contents[$pos->post_type][$item] = $pos->post_title;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Post Types registered.
     *
     * @uses get_post_types()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPPosttypes($options = [], $value = 'name')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.posttype', [], 'wordpressfield');

        // Build options
        $args = array_merge([], $options);

        // Build request
        $types_obj = get_post_types($args, 'object');

        // Iterate on posttypes
        if (!empty($types_obj)) {
            foreach ($types_obj as $typ) {
                // Check value
                $item = !empty($value) && isset($typ->$value) ? $typ->$value : $typ->name;

                // Get the the name
                $contents[0][$item] = $typ->labels->name.' ('.$typ->name.')';
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Tags registered.
     *
     * @uses get_the_tags()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPTags($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.tag', [], 'wordpressfield');

        // Build options
        $args = array_merge([], $options);

        // Build request
        $tags_obj = get_the_tags();

        // Iterate on tags
        if (!empty($tags_obj)) {
            foreach ($tags_obj as $tag) {
                // Check value
                $item = !empty($value) && isset($tag->$value) ? $tag->$value : $tag->term_id;

                // Get the id and the name
                $contents[0][$item] = $tag->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Taxonomies registered.
     *
     * @uses get_taxonomies()
     * @uses get_taxonomy()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPTaxonomies($options = [], $value = '')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.taxonomy', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'public' => 1
        ], $options);

        // Build request
        $taxs_obj = get_taxonomies($args);

        // Iterate on tags
        if (!empty($taxs_obj)) {
            foreach ($taxs_obj as $tax) {
                // Get taxonomy details
                $taxo = get_taxonomy($tax);

                // Get the id and the name
                $contents[0][$tax] = $taxo->labels->name.' ('.$taxo->name.')';
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }

    /**
     * Get WordPress Terms registered.
     *
     * @uses get_terms()
     *
     * @param   array  $options     Define options if needed
     * @param   string $value       Define the value of each select options
     * @return  array  $wpcontents  Array of WordPress items
     */
    protected function getWPTerms($options = [], $value = 'term_id')
    {
        // Build contents
        $contents = [];
        $contents[-1] = Translate::t('wordpress.choose.term', [], 'wordpressfield');

        // Build options
        $args = array_merge([
            'hide_empty' => false,
        ], $options);

        // Build request
        $terms_obj = get_terms($args);

        // Iterate on tags
        if (!empty($terms_obj) && ! is_wp_error($terms_obj)) {
            foreach ($terms_obj as $term) {
                // Check value
                $item = !empty($value) && isset($term->$value) ? $term->$value : $term->term_id;

                // Get the id and the name
                $contents[0][$item] = $term->name;
            }
        }

        // Return all values in a well formatted way
        return $contents;
    }
}