<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Block;
use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\TinyMCEWysiwygStrategy;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelBundle\Document\Area;

/**
 * Class LegalDataGenerator
 */
class LegalDataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
        $htmlContent = <<<EOF

Entreprise

Open Orchestra est une marque déposée de Business & Decision

Dénomination sociale : Business & Decision S.A. (tél : 01 56 21 21 21)

Société anonyme au capital de 551 808,25 €

Enregistré au RCS Paris : 384 518 114 B

Siége social: 153 rue de Courcelles, 75817 Paris cedex 17

Directeur de publication: Patrick Bensabat, PDG

EOF;
        $name = "Mentions Légales";
        $language = "fr";
        $routePattern = "mentions-legales";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeEn()
    {
        $htmlContent = <<<EOF

Éditeur

Open Orchestra is a registered trademark of Business & Decision

Company name: Business & Decision S.A. (Tel.: 01 56 21 21 21)

Public limited company with a capital of EUR 551,808.25

Registered at RCS Paris under number: 384 518 114 B

Headquarters: 153 rue de Courcelles, 75817 Paris cedex 17

Publication Director: Patrick Bensabat, CEO

EOF;
        $name = "Legal Notice";
        $language = "en";
        $routePattern = "legal-page";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeDe()
    {
        $htmlContent = <<<EOF

Geschäft

Offene Orchester ist ein eingetragenes Warenzeichen von Business & Decision

Firmenname : Business & Decision S.A. (tél : 01 56 21 21 21)

Aktiengesellschaft mit einem Kapital von 551 808,25 €

Aufgenommen in RCS Paris : 384 518 114 B

Sitz der Gesellschaft : 153 rue de Courcelles, 75817 Paris cedex 17

Herausgeber : Patrick Bensabat, PDG

EOF;
        $name = "Rechtliche Hinweise";
        $language = "de";
        $routePattern = "rechtliche-hinweise";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @param string $htmlContent
     * @param string $name
     * @param string $language
     * @param string $routePattern
     *
     * @return Node
     */
    protected function generateNodeGlobal($htmlContent, $name, $language, $routePattern)
    {
        $nodeLegalBlock = new Block();
        $nodeLegalBlock->setLabel('Wysiwyg');
        $nodeLegalBlock->setLanguage($language);
        $nodeLegalBlock->setComponent(TinyMCEWysiwygStrategy::NAME);
        $nodeLegalBlock->setAttributes(array(
            "htmlContent" => $htmlContent
        ));

        $nodeLegalBlock = $this->generateBlock($nodeLegalBlock);

        $main = new Area();
        $main->addBlock($nodeLegalBlock);

        $nodeLegal = $this->createBaseNode();
        $nodeLegal->setArea('main', $main);

        $nodeLegal->setNodeId('fixture_page_legal_mentions');
        $nodeLegal->setName($name);
        $nodeLegal->setVersionName($this->getVersionName($nodeLegal));
        $nodeLegal->setLanguage($language);
        $nodeLegal->setParentId(NodeInterface::ROOT_NODE_ID);
        $nodeLegal->setOrder(10);
        $nodeLegal->setRoutePattern($routePattern);
        $nodeLegal->setInFooter(true);
        $nodeLegal->setInMenu(false);

        return $nodeLegal;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\widgets\grid;

use canis\helpers\Html;

/**
 * LinkPager [[@doctodo class_description:cascade\components\web\widgets\grid\LinkPager]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class LinkPager extends \yii\widgets\LinkPager
{
    /**
     * @var [[@doctodo var_type:_state]] [[@doctodo var_description:_state]]
     */
    protected $_state;

    /**
     * Get state.
     *
     * @return unknown
     */
    public function getState()
    {
        return $this->_state;
    }

    /**
     * Set state.
     *
     * @param unknown $state
     */
    public function setState($state)
    {
        $this->_state = $state;
    }

    /**
     * Renders a page button.
     * You may override this method to customize the generation of page buttons.
     *
     * @param string  $label    the text label for the button
     * @param integer $page     the page number
     * @param string  $class    the CSS class for the page button.
     * @param boolean $disabled whether this page button is disabled
     * @param boolean $active   whether this page button is active
     *
     * @return string the rendering result
     */
    protected function renderPageButton($label, $page, $class, $disabled, $active)
    {
        if ($active) {
            $class .= ' ' . $this->activePageCssClass;
        }
        if ($disabled) {
            $class .= ' ' . $this->disabledPageCssClass;
        }
        $state = $this->getState();
        $state['page'] = $page + 1;
        $jsonState = json_encode($state);

        $class .= ' stateful';
        $class = trim($class);
        $options = ['data-state' => $jsonState, 'class' => $class === '' ? null : $class];

        return Html::tag('li', Html::a($label, $this->pagination->createUrl($page), ['data-page' => $page]), $options);
    }
}


<?php
namespace HtSettingsModule\Mapper\FileSystem;

use HtSettingsModule\Entity\ParameterInterface;
use HtSettingsModule\Exception;
use League\Flysystem\FilesystemInterface;
use HtSettingsModule\Mapper\SettingsMapperInterface;

class FileSystemMapper implements SettingsMapperInterface
{
    /**
     * @var ParameterInterface
     */
    protected $entityPrototype;

    /**
     * @var FilesystemInterface
     */
    protected $fileSystem;

    /**
     * @var Adapter\AdapterInterface
     */
    protected $adapter;

    /**
     * Constructor
     *
     * @param FilesystemInterface $fileSystem
     * @param ParameterInterface  $entityPrototype
     */
    public function __construct(FilesystemInterface $fileSystem, ParameterInterface $entityPrototype, Adapter\AdapterInterface $adapter)
    {
        $this->fileSystem = $fileSystem;
        $this->entityPrototype = $entityPrototype;
        $this->adapter = $adapter;
    }

    /**
     * {@inheritDoc}
     */
    public function findByNamespace($namespace)
    {
        $data = $this->read($namespace);
        $parameters = [];
        foreach ($data as $name => $value) {
            $parameter = clone $this->entityPrototype;
            $parameter->setName($name);
            $parameter->setValue($value);
            $parameter->setNamespace($namespace);
            $parameters[] = $parameter;
        }

        return $parameters;
    }

    /**
     * {@inheritDoc}
     */
    public function insertParameter(ParameterInterface $parameter)
    {
        $this->updateParameter($parameter);
    }

    /**
     * {@inheritDoc}
     */
    public function updateParameter(ParameterInterface $parameter)
    {
        $data = $this->read($parameter->getNamespace());
        $data[$parameter->getName()] = $parameter->getValue();
        $this->write($parameter->getNamespace(), $data);
    }

    /**
     * {@inheritDoc}
     */
    public function deleteParameter(ParameterInterface $parameter)
    {
        $data = $this->read($parameter->getNamespace());
        unset($data[$parameter->getName()]);

        $this->write($parameter->getNamespace(), $data);
    }

    /**
     * {@inheritDoc}
     */
    public function findParameter($parameter, $name = null)
    {
        if ($parameter instanceof ParameterInterface) {
            $namespace = $parameter->getNamespace();
            $name = $parameter->getName();
            $data = $this->read($namespace);
            $parameter->setValue($data[$name]);

            return $parameter;
        } elseif (!is_string($parameter)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be string or an instance of HtSettingsModule\Entity\ParameterInterface, %s provided instead',
                    __METHOD__,
                    is_object($parameter) ? get_class($parameter) : gettype($parameter)
                )
            );
        }

        $namespace = $parameter;
        $data = $this->read($namespace);
        $parameter = clone $this->entityPrototype;
        $parameter->setName($name);
        $parameter->setValue($data[$name]);
        $parameter->setNamespace($namespace);

        return $parameter;
    }

    /**
     * Reads settings content of a namespace
     *
     * @param  string $namespace
     * @return array
     */
    protected function read($namespace)
    {
        $file = $this->adapter->getFileName($namespace);
        if (!$this->fileSystem->has($file)) {
            return [];
        }

        return $this->adapter->onRead($this->fileSystem->read($file));
    }

    /**
     * Write settings content of a namespace
     *
     * @param  string $namespace
     * @param  array  $data
     * @return void
     */
    protected function write($namespace, array $data)
    {
        $file = $this->adapter->getFileName($namespace);
        $contents = $this->adapter->prepareForWriting($data);
        if (!$this->fileSystem->has($file)) {
            $this->fileSystem->write($file, $contents);
        }

        $this->fileSystem->update($file, $contents);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: las
 * Date: 28/06/2016
 * Time: 22:22
 */
namespace Venus\lib\Request;

class Files implements RequestInterface
{
    /**
     * get parameter
     * @param string $name
     * @param string $default
     * @return string
     */
    public function get(string $name, string $default = null)
    {
        if (isset($_FILES[$name]) && $_FILES[$name] != '') {
            return $_FILES[$name];
        }
        else if ($default !== null) {
            return $default;
        }
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application 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://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Rendering\Controller\Queue;

use RedKiteCms\Rendering\Controller\BaseController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class SaveQueueController is the object assigned to save the operations from the frontend to the backend
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Block
 */
abstract class SaveQueueController extends BaseController
{
    /**
     * Implements the action to save the queue
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function save(array $options)
    {
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);
        $this->options = $resolver->resolve($options);

        $request = $options["request"];
        $queue = $request->get('queue');
        if (null !== $queue) {
            $this->options["queue_manager"]->queue($queue);
        }
        $username = $this->fetchUserName($options["security"], $options["configuration_handler"]);

        $result = $this->options["queue_manager"]->execute($username);
        if ( ! $result) {
            $content = $this->options["queue_manager"]->renderQueue();

            return new Response($content);
        }

        return new Response("Queue saved");
    }

    /**
     * Configures the base options for the resolver
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(
            array(
                'request',
                'security',
                'configuration_handler',
                'queue_manager'
            )
        );

        $resolver->setAllowedTypes(
            array(
                'request' => '\Symfony\Component\HttpFoundation\Request',
                'configuration_handler' => '\RedKiteCms\Configuration\ConfigurationHandler',
                'security' => '\Symfony\Component\Security\Core\SecurityContext',
                'queue_manager' => '\RedKiteCms\Rendering\Queue\QueueManager',
            )
        );
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Component\Grid;

use ItePHP\Core\Request;

/**
 * Generator grid. Support for mapping data, pagination and generate html code.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class GridBuilder{

    /**
     * @var GridFormatter
     */
	private $formatter;

    /**
     * @var GridDataManager
     */
	private $dataManager;

    /**
     * @var int
     */
	private $limit=10;

    /**
     * @var int
     */
	private $page=1;

    /**
     * @var Column[]
     */
	private $columns=[];

	/**
	 * @var Request $request
	 */
	private $request;

	/**
	 * Constructor
	 *
	 * @param Request $request
	 */
	public function __construct(Request $request){
		$this->request=$request;
	}

	/**
	 * Set formatter with html rule pattern
	 *
	 * @param GridFormatter $formatter
	 */
	public function setFormatter(GridFormatter $formatter){
		$this->formatter=$formatter;
	}

	/**
	 * Set formatter with html rule pattern
	 *
	 * @param GridDataManager $dataManager
	 */
	public function setDataManager(GridDataManager $dataManager){
		$this->dataManager=$dataManager;
	}

	/**
	 * Get DataManager
	 *
	 * @return GridDataManager
	 */
	public function getDataManager(){
		return $this->dataManager;
	}

	/**
	 * Get columns data
	 *
	 * @return Column[]
	 */
	public function getColumns(){
		return $this->columns;
	}

	/**
	 * Get records
	 *
	 * @return mixed[]
	 */
	public function getRecords(){
		$query=$this->request->getQuery();
		$sort=null;
		if(isset($query['sort']) && isset($this->columns[$query['sort']])){
			$sort=$this->columns[$query['sort']]->getSortKeys();
		}
		if (isset($query['page'])) {
			$this->page=$query['page'];
		}

		return $this->dataManager->getRecords($this->limit,$this->page,$sort);
	}

	/**
	 * Get total count records
	 *
	 * @return int
	 */
	public function getTotalCount(){
		return $this->dataManager->getTotalCount();
	}

	/**
	 * Set limit records on single page
	 *
	 * @param int $limit - items on page
	 */
	public function setLimit($limit){
		$this->limit=$limit;
	}

	/**
	 * Set current page
	 *
	 * @param int $page - current page
	 */
	public function setPage($page){
		$this->page=$page;
	}

	/**
	 * Add column
	 *
	 * @param Column $column
	 * @since 0.17.0
	 */
	public function addColumn(Column $column){
		$this->columns[]=$column;
	}

	/**
	 * Generate html grid string
	 *
	 * @return string with html form
	 */
	public function render(){
		$sort=0;
		$query=$this->request->getQuery();
		if(isset($query['sort']) && isset($this->columns[$query['sort']])){
			$sort=$query['sort'];
		}

		return $this->formatter->render($this->columns
			,$this->getRecords()
			,$this->dataManager->getTotalCount(),$this->limit,$this->page,$sort);
	}

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

}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\widgets;

use canis\base\collector\CollectedObjectTrait;
use Yii;

/**
 * Widget [[@doctodo class_description:cascade\components\web\widgets\Widget]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Widget extends BaseWidget implements \canis\base\WidgetInterface, \canis\base\collector\CollectedObjectInterface
{
    use CollectedObjectTrait;

    /**
     * @var [[@doctodo var_type:icon]] [[@doctodo var_description:icon]]
     */
    public $icon = false;
    /**
     * @var [[@doctodo var_type:section]] [[@doctodo var_description:section]]
     */
    public $section = false;
    /**
     * @inheritdoc
     */
    public $defaultDecoratorClass = 'cascade\components\web\widgets\decorator\PanelDecorator';
    /**
     * @var [[@doctodo var_type:gridCellClass]] [[@doctodo var_description:gridCellClass]]
     */
    public $gridCellClass = 'canis\web\grid\Cell';
    /**
     * @var [[@doctodo var_type:gridClass]] [[@doctodo var_description:gridClass]]
     */
    public $gridClass = 'canis\web\grid\Grid';

    /**
     * @inheritdoc
     */
    public $params = [];
    /**
     * @var [[@doctodo var_type:recreateParams]] [[@doctodo var_description:recreateParams]]
     */
    public $recreateParams = [];
    /**
     * @inheritdoc
     */
    public $htmlOptions = ['class' => 'ic-widget'];

    /**
     * @var [[@doctodo var_type:_widgetId]] [[@doctodo var_description:_widgetId]]
     */
    protected $_widgetId;
    /**
     * @var [[@doctodo var_type:_title]] [[@doctodo var_description:_title]]
     */
    protected $_title  = false;

    /**
     * @var [[@doctodo var_type:_lazy]] [[@doctodo var_description:_lazy]]
     */
    protected $_lazy  = false;

    /**
     * [[@doctodo method_description:stateKeyName]].
     *
     * @param [[@doctodo param_type:key]] $key [[@doctodo param_description:key]]
     *
     * @return [[@doctodo return_type:stateKeyName]] [[@doctodo return_description:stateKeyName]]
     */
    public function stateKeyName($key)
    {
        return 'widget.' . $this->systemId . '.' . $key;
    }

    /**
     * Get refresh instructions.
     *
     * @return [[@doctodo return_type:getRefreshInstructions]] [[@doctodo return_description:getRefreshInstructions]]
     */
    public function getRefreshInstructions()
    {
        $i = [];
        $i['type'] = 'widget';
        $i['systemId'] = $this->collectorItem->systemId;
        $i['recreateParams'] = $this->recreateParams;
        if ($this->section) {
            $i['section'] = $this->section->systemId;
        }

        return $i;
    }

    /**
     * Get lazy.
     *
     * @return [[@doctodo return_type:getLazy]] [[@doctodo return_description:getLazy]]
     */
    public function getLazy()
    {
        if (!Yii::$app->collectors['widgets']->lazy) {
            return false;
        }

        return $this->_lazy;
    }

    /**
     * Set lazy.
     *
     * @param [[@doctodo param_type:lazy]] $lazy [[@doctodo param_description:lazy]]
     */
    public function setLazy($lazy)
    {
        $this->_lazy = $lazy;
    }

    /**
     * Get state.
     *
     * @param [[@doctodo param_type:key]]     $key     [[@doctodo param_description:key]]
     * @param [[@doctodo param_type:default]] $default [[@doctodo param_description:default]] [optional]
     *
     * @return [[@doctodo return_type:getState]] [[@doctodo return_description:getState]]
     */
    public function getState($key, $default = null)
    {
        return Yii::$app->webState->get($this->stateKeyName($key), $default);
    }

    /**
     * Set state.
     *
     * @param [[@doctodo param_type:key]]   $key   [[@doctodo param_description:key]]
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @return [[@doctodo return_type:setState]] [[@doctodo return_description:setState]]
     */
    public function setState($key, $value)
    {
        return Yii::$app->webState->set($this->stateKeyName($key), $value);
    }

    /**
     * Get header menu.
     *
     * @return [[@doctodo return_type:getHeaderMenu]] [[@doctodo return_description:getHeaderMenu]]
     */
    public function getHeaderMenu()
    {
        return [];
    }

    /**
     * Get title.
     *
     * @return [[@doctodo return_type:getTitle]] [[@doctodo return_description:getTitle]]
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     * Set title.
     *
     * @param [[@doctodo param_type:title]] $title [[@doctodo param_description:title]]
     */
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    /**
     * [[@doctodo method_description:ensureAssetBundles]].
     */
    public function ensureAssetBundles()
    {
        foreach ($this->assetBundles as $bundleClass) {
            $bundleClass::register(Yii::$app->view);
        }
    }

    /**
     * Get asset bundles.
     *
     * @return [[@doctodo return_type:getAssetBundles]] [[@doctodo return_description:getAssetBundles]]
     */
    public function getAssetBundles()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function generate()
    {
        Yii::beginProfile(get_called_class() . ':' . __FUNCTION__);
        $this->ensureAssetBundles();
        $this->ensureDecorator();
        $content = $this->generateContent();
        if ($content === false) {
            return;
        }
        if (($widgetAreas = $this->widgetAreas) && !empty($widgetAreas)) {
            $contentCell = ['class' => $this->gridCellClass, 'content' => $content];
            $contentRow = [Yii::createObject($contentCell)];
            $topRow = [];
            $bottomRow = [];
            foreach ($widgetAreas as $widgetArea) {
                if (!is_object($widgetArea)) {
                    $widgetArea = Yii::createObject($widgetArea);
                }
                $widgetArea->parentWidget = $this;
                $widgetAreaCell = $widgetArea->cell;
                if (!$widgetArea->isReady) {
                    continue;
                }
                switch ($widgetArea->location) {
                    case 'bottom':
                        array_push($bottomRow, $widgetAreaCell);
                    break;
                    case 'top':
                        array_push($topRow, $widgetAreaCell);
                    break;
                    case 'left':
                        array_unshift($contentRow, $widgetAreaCell);
                    break;
                    case 'right':
                        array_push($contentRow, $widgetAreaCell);
                    break;
                }
            }
            $grid = Yii::createObject(['class' => $this->gridClass]);
            if (!empty($topRow)) {
                $grid->addRow($topRow);
            }
            $grid->addRow($contentRow);
            if (!empty($bottomRow)) {
                $grid->addRow($bottomRow);
            }
            //\d($grid);exit;
            $content = $grid->generate();
        }
        $result = $this->generateStart() . $this->generateHeader() . $content . $this->generateFooter() . $this->generateEnd();
        Yii::endProfile(get_called_class() . ':' . __FUNCTION__);

        return $result;
    }

    /**
     * Get widget areas.
     *
     * @return [[@doctodo return_type:getWidgetAreas]] [[@doctodo return_description:getWidgetAreas]]
     */
    public function getWidgetAreas()
    {
        return [
        ];
    }

    /**
     * Get widget.
     *
     * @return unknown
     */
    public function getWidgetId()
    {
        if (!is_null($this->_widgetId)) {
            return $this->_widgetId;
        }

        return $this->_widgetId = 'ic-widget-' . md5(microtime() . mt_rand());
    }

    /**
     * @inheritdoc
     */
    public function setWidgetId($value)
    {
        $this->_widgetId = $value;
    }

    /**
     * Get priority adjust.
     *
     * @return [[@doctodo return_type:getPriorityAdjust]] [[@doctodo return_description:getPriorityAdjust]]
     */
    public function getPriorityAdjust()
    {
        return 0;
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Encryptor.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Encryption;

use EasyWeChat\Core\Exceptions\InvalidConfigException;
use EasyWeChat\Support\XML;
use Exception as BaseException;

/**
 * Class Encryptor.
 */
class Encryptor
{
    /**
     * App id.
     *
     * @var string
     */
    protected $appId;

    /**
     * App token.
     *
     * @var string
     */
    protected $token;

    /**
     * AES key.
     *
     * @var string
     */
    protected $AESKey;

    /**
     * Block size.
     *
     * @var int
     */
    protected $blockSize;

    /**
     * Constructor.
     *
     * @param string $appId
     * @param string $token
     * @param string $AESKey
     */
    public function __construct($appId, $token, $AESKey)
    {
        $this->appId = $appId;
        $this->token = $token;
        $this->AESKey = $AESKey;
        $this->blockSize = 32;
    }

    /**
     * Encrypt the message and return XML.
     *
     * @param string $xml
     * @param string $nonce
     * @param int    $timestamp
     *
     * @return string
     */
    public function encryptMsg($xml, $nonce = null, $timestamp = null)
    {
        $encrypt = $this->encrypt($xml, $this->appId);

        !is_null($nonce) || $nonce = substr($this->appId, 0, 10);
        !is_null($timestamp) || $timestamp = time();

        //生成安全签名
        $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypt);

        $response = [
            'Encrypt' => $encrypt,
            'MsgSignature' => $signature,
            'TimeStamp' => $timestamp,
            'Nonce' => $nonce,
        ];

        //生成响应xml
        return XML::build($response);
    }

    /**
     * Decrypt message.
     *
     * @param string $msgSignature
     * @param string $nonce
     * @param string $timestamp
     * @param string $postXML
     *
     * @return array
     *
     * @throws EncryptionException
     */
    public function decryptMsg($msgSignature, $nonce, $timestamp, $postXML)
    {
        try {
            $array = XML::parse($postXML);
        } catch (BaseException $e) {
            throw new EncryptionException('Invalid xml.', EncryptionException::ERROR_PARSE_XML);
        }

        $encrypted = $array['Encrypt'];

        $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypted);

        if ($signature !== $msgSignature) {
            throw new EncryptionException('Invalid Signature.', EncryptionException::ERROR_INVALID_SIGNATURE);
        }

        return XML::parse($this->decrypt($encrypted, $this->appId));
    }

    /**
     * Get SHA1.
     *
     * @return string
     *
     * @throws EncryptionException
     */
    public function getSHA1()
    {
        try {
            $array = func_get_args();
            sort($array, SORT_STRING);

            return sha1(implode($array));
        } catch (BaseException $e) {
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_CALC_SIGNATURE);
        }
    }

    /**
     * Encode string.
     *
     * @param string $text
     *
     * @return string
     */
    public function encode($text)
    {
        $padAmount = $this->blockSize - (strlen($text) % $this->blockSize);

        $padAmount = $padAmount !== 0 ? $padAmount : $this->blockSize;

        $padChr = chr($padAmount);

        $tmp = '';

        for ($index = 0; $index < $padAmount; ++$index) {
            $tmp .= $padChr;
        }

        return $text.$tmp;
    }

    /**
     * Decode string.
     *
     * @param string $decrypted
     *
     * @return string
     */
    public function decode($decrypted)
    {
        $pad = ord(substr($decrypted, -1));

        if ($pad < 1 || $pad > $this->blockSize) {
            $pad = 0;
        }

        return substr($decrypted, 0, (strlen($decrypted) - $pad));
    }

    /**
     * Return AESKey.
     *
     * @return string
     *
     * @throws InvalidConfigException
     */
    protected function getAESKey()
    {
        if (empty($this->AESKey)) {
            throw new InvalidConfigException("Configuration mission, 'aes_key' is required.");
        }

        if (strlen($this->AESKey) !== 43) {
            throw new InvalidConfigException("The length of 'aes_key' must be 43.");
        }

        return base64_decode($this->AESKey.'=', true);
    }

    /**
     * Encrypt string.
     *
     * @param string $text
     * @param string $appId
     *
     * @return string
     *
     * @throws EncryptionException
     */
    private function encrypt($text, $appId)
    {
        try {
            $key = $this->getAESKey();
            $random = $this->getRandomStr();
            $text = $this->encode($random.pack('N', strlen($text)).$text.$appId);

            $iv = substr($key, 0, 16);

            $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);

            return base64_encode($encrypted);
        } catch (BaseException $e) {
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_ENCRYPT_AES);
        }
    }

    /**
     * Decrypt message.
     *
     * @param string $encrypted
     * @param string $appId
     *
     * @return string
     *
     * @throws EncryptionException
     */
    private function decrypt($encrypted, $appId)
    {
        try {
            $key = $this->getAESKey();
            $ciphertext = base64_decode($encrypted, true);
            $iv = substr($key, 0, 16);

            $decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
        } catch (BaseException $e) {
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_DECRYPT_AES);
        }

        try {
            $result = $this->decode($decrypted);

            if (strlen($result) < 16) {
                return '';
            }

            $content = substr($result, 16, strlen($result));
            $listLen = unpack('N', substr($content, 0, 4));
            $xmlLen = $listLen[1];
            $xml = substr($content, 4, $xmlLen);
            $fromAppId = trim(substr($content, $xmlLen + 4));
        } catch (BaseException $e) {
            throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_INVALID_XML);
        }

        if ($fromAppId !== $appId) {
            throw new EncryptionException('Invalid appId.', EncryptionException::ERROR_INVALID_APPID);
        }

        $dataSet = json_decode($xml, true);
        if ($dataSet && (JSON_ERROR_NONE === json_last_error())) {
            // For mini-program JSON formats.
            // Convert to XML if the given string can be decode into a data array.
            $xml = XML::build($dataSet);
        }

        return $xml;
    }

    /**
     * Generate random string.
     *
     * @return string
     */
    private function getRandomStr()
    {
        return substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'), 0, 16);
    }
}


<?php

namespace Jelle_S\Util\Intersections;

use Jelle_S\Util\BitMask\BitMaskGenerator;

/**
 * Tries to find intersections between a combination of arrays.
 *
 * @author Jelle Sebreghts
 */
class ArrayIntersections {

  /**
   * The array of arrays to find intersections for.
   *
   * @var array
   */
  protected $arrays;

  /**
   * The array keys of the master array.
   *
   * @var array
   */
  protected $arrayKeys;

  /**
   * The size of the master array.
   *
   * @var int
   */
  protected $arraysSize;

  /**
   * The intersections that were found so far.
   *
   * @var array
   */
  protected $intersections;

  /**
   * The masks that resulted in no intersections
   *
   * @var array
   */
  protected $noResultMasks = [];

  /**
   * The threshold. The minimum size of the intersections to search for.
   *
   * @var int
   */
  protected $threshold;

  /**
   * The maximum number of combinations to try for finding intersections.
   *
   * @var int
   */
  protected $maxNumberOfCombinations;

  /**
   * Creates an Intersections object.
   *
   * @param array $arrays
   *   The array of arrays to find intersections for.
   * @param int $threshold
   *   The threshold. The minimum size of the intersections to search for.
   * @param int $maxNumberOfCombinations
   *   The maximum number of combinations to try for finding intersections.
   */
  public function __construct($arrays, $threshold, $maxNumberOfCombinations = 1000000) {
    $this->arrays = $arrays;
    $this->threshold = $threshold;
    if (count($this->arrays) === 1 && count(reset($this->arrays)) > $this->threshold) {
      $this->intersections = $this->arrays;
    }
    // Fitler the arrays. Those smaller than the threshold will not create an
    // intersection bigger than the threshold.
    foreach ($this->arrays as $key => $array) {
      if (count($array) < $this->threshold) {
        unset($this->arrays[$key]);
      }
    }
    $this->arraysSize = count($this->arrays);
    $this->arrayKeys = array_keys($this->arrays);
    $this->maxNumberOfCombinations = $maxNumberOfCombinations;
  }

  /**
   * Get all intersections given the constructor parameters.
   *
   * @return array
   */
  public function getAll() {
    if (is_null($this->intersections)) {
      $this->intersections = [];
      if ($this->arraysSize >= 2) {
        $this->createIntersections();
      }
    }

    return $this->intersections;
  }

  /**
   * Get the largest intersection found given the constructor parameters.
   *
   * @return array
   */
  public function getLargest() {
    $this->getAll();
    return $this->intersections ? reset($this->intersections) : NULL;
  }

  /**
   * Set the maximum number of combinations to try for finding intersections.
   *
   * @param int $max
   *
   * @codeCoverageIgnore
   */
  public function setMaxNumberOfCombinations($max) {
    $this->maxNumberOfCombinations = $max;
  }

  /**
   * Create all intersections given the constructor parameters.
   */
  protected function createIntersections() {
    $totalNumberOfCombinations = min(pow(2, $this->arraysSize), $this->maxNumberOfCombinations);
    $maskGenerator = new BitMaskGenerator($this->arraysSize, 2);
    $i = 0;
    $noresult = 0;
    while ($i < $totalNumberOfCombinations && $noresult < $totalNumberOfCombinations && $mask = $maskGenerator->getNextMask()) {
      if (!$this->isNoResultMask($mask)) {
        $i++;
        $this->generateIntersection($mask);
        continue;
      }
      $noresult++;
    }

    if (!is_null($this->intersections)) {
      uasort($this->intersections, function ($a, $b) {
        return count($b) - count($a);
      });
    }
  }

  /**
   * Try to determine if this mask will result in no intersections based on
   * previously generated masks.
   *
   * @param string $mask
   *   The mask to check.
   *
   * @return boolean
   *   TRUE if this mask would result in an empty intersection, FALSE if not or
   *   if not known.
   */
  protected function isNoResultMask($mask) {
    foreach ($this->noResultMasks as $noresultMask) {
      if ($mask === $noresultMask) {
        return TRUE; // @codeCoverageIgnore
      }
      if (($mask & $noresultMask) === $noresultMask) {
        $this->noResultMasks[] = $mask;
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * Generate intersections based on a combination mask.
   *
   * @param string $combinationMask
   *   The combination mask to try.
   */
  protected function generateIntersection($combinationMask) {
    $combination = [];
    foreach (str_split($combinationMask) as $key => $indicator) {
      if ($indicator) {
        $combination[] = $this->arrays[$this->arrayKeys[$key]];
      }
    }
    $intersection = call_user_func_array('array_intersect_assoc', $combination);
    if (count($intersection) >= $this->threshold) {
      $this->intersections[] = $intersection;
      return;
    }
    $this->noResultMasks[] = $combinationMask;
  }

}


<?php
/**
 * This source file is part of Virtupeer project.
 *
 * @link      https://virtupeer.com
 * @copyright Copyright (c) 2016, Virtupeer. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form;

use Zend\Form\ElementFactory;

/**
 * A {@link Module} class.
 *
 * @package Xloit\Bridge\Zend\Form
 */
class Module
{
    /**
     * Return default zend-validator configuration for zend-mvc applications.
     *
     * @return array
     */
    public function getConfig()
    {
        return [
            'form_elements' => [
                'aliases'   => [
                    'checkbox'       => Element\Checkbox::class,
                    'Checkbox'       => Element\Checkbox::class,
                    'ckeditor'       => Element\CkEditor::class,
                    'ckEditor'       => Element\CkEditor::class,
                    'CkEditor'       => Element\CkEditor::class,
                    'csrf'           => Element\Csrf::class,
                    'Csrf'           => Element\Csrf::class,
                    'date'           => Element\Date::class,
                    'Date'           => Element\Date::class,
                    'datetime'       => Element\DateTime::class,
                    'dateTime'       => Element\DateTime::class,
                    'DateTime'       => Element\DateTime::class,
                    'email'          => Element\Email::class,
                    'Email'          => Element\Email::class,
                    'multipleinput'  => Element\MultipleInput::class,
                    'multipleInput'  => Element\MultipleInput::class,
                    'MultipleInput'  => Element\MultipleInput::class,
                    'password'       => Element\Password::class,
                    'Password'       => Element\Password::class,
                    'rangefilter'    => Element\RangeFilter::class,
                    'rangeFilter'    => Element\RangeFilter::class,
                    'RangeFilter'    => Element\RangeFilter::class,
                    'time'           => Element\Time::class,
                    'Time'           => Element\Time::class,
                    'timezoneselect' => Element\TimeZoneSelect::class,
                    'timezoneSelect' => Element\TimeZoneSelect::class,
                    'TimezoneSelect' => Element\TimeZoneSelect::class,
                    'username'       => Element\Username::class,
                    'Username'       => Element\Username::class,
                    'yesnoselect'    => Element\YesNoSelect::class,
                    'yesNoSelect'    => Element\YesNoSelect::class,
                    'YesNoSelect'    => Element\YesNoSelect::class
                ],
                'factories' => [
                    Element\Checkbox::class       => ElementFactory::class,
                    Element\CkEditor::class       => ElementFactory::class,
                    Element\Csrf::class           => ElementFactory::class,
                    Element\Date::class           => ElementFactory::class,
                    Element\DateTime::class       => ElementFactory::class,
                    Element\Email::class          => ElementFactory::class,
                    Element\MultipleInput::class  => ElementFactory::class,
                    Element\Password::class       => ElementFactory::class,
                    Element\RangeFilter::class    => ElementFactory::class,
                    Element\Time::class           => ElementFactory::class,
                    Element\TimeZoneSelect::class => ElementFactory::class,
                    Element\Username::class       => ElementFactory::class,
                    Element\YesNoSelect::class    => ElementFactory::class
                ]
            ]
        ];
    }
}


<?php

/**
 * Manage Request
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib;

use \Venus\core\Mother as Mother;
use \Venus\lib\Request\Cookies as Cookies;
use \Venus\lib\Request\Files as Files;
use \Venus\lib\Request\Headers as Headers;
use \Venus\lib\Request\Query as Query;
use \Venus\lib\Request\Request as RequestPost;
use \Venus\lib\Request\Server as Server;

/**
 * This class manage the request
 *
 * @property 	\Venus\lib\Request\Cookies cookies
 * @property 	\Venus\lib\Request\Files files
 * @property 	\Venus\lib\Request\Headers headers
 * @property 	\Venus\lib\Request\Query query
 * @property 	\Venus\lib\Request\Request request
 * @property 	\Venus\lib\Request\Server server
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Request extends Mother
{
	/**
	 * Query constructor.
	 */
	public function __construct()
	{
        $this->cookies = function() { return new Cookies(); };
        $this->files = function() { return new Files(); };
        $this->headers = function() { return new Headers(); };
        $this->query = function() { return new Query(); };
        $this->request = function() { return new RequestPost(); };
		$this->server = function() { return new Server(); };
	}

	/**
	 * if the request is ajax
	 *
	 * @access public
	 * @param  string $sName name of the template
	 * @return bool
	 */
	public static function isXmlHttpRequest()
	{
		if (!self::isCliRequest()) {

			if (array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

				return true;
			}
			else {

				return false;
			}
		}
	}

	/**
	 * if the request is http (web site or web service)
	 *
	 * @access public
	 * @return bool
	 */
	public static function isHttpRequest()
	{
		if (isset($_SERVER) && isset($_SERVER['HTTP_HOST'])) { return true; }
		else { return false; }
	}

	/**
	 * if the request is https (web site or web service)
	 *
	 * @access public
	 * @return bool
	 */
	public static function isHttpsRequest()
	{
		if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') { return true; }
		else { return false; }
	}

	/**
	 * if the request is http (web site or web service)
	 *
	 * @access public
	 * @return bool
	 */
	public static function isCliRequest()
	{
		$sSapiType = php_sapi_name();

		if (substr($sSapiType, 0, 3) == 'cgi' || defined('STDIN')) { return true; }
		else { return false; }
	}

	/**
	 * if the request is http (web site or web service)
	 *
	 * @access public
	 * @return bool
     * @deprecated  don't use this method because they return a false result
     *              delete in the version 5
     * @throws \Exception
	 */
	public static function getPreferredLanguage()
	{
        throw new \Exception("Use getLanguages() method now!");
	}

	/**
	 * if the request is http (web site or web service)
	 *
	 * @access public
	 * @return bool
	 */
	public static function getParameters()
	{
		if (isset($_GET)) { return $_GET; }
		else { return array(); }
	}

	/**
	 * if the request is http (web site or web service)
	 *
	 * @access public
	 * @return bool
	 */
	public static function getPostParameters()
	{
		if (isset($_POST)) { return $_POST; }
		else { return array(); }
	}

	/**
	 * if there are POST parameters
	 *
	 * @access public
	 * @return bool
	 */
	public function isPost()
	{
		if (isset($_POST) && count($_POST) > 0) { return true; }
		else { return false; }
	}

	/**
	 * get the POST for $sName
	 *
	 * @access public
	 * @param  string $name
	 * @return mixed
     * @deprecated  please use $this->request->get()
     *              delete in the version 5
	 */
	public function getPost(string $name)
	{
		return $this->request->get($name);
	}

	/**
	 * get the put method
	 *
	 * @access public
	 * @return array
	 */
	public static function getPut()
	{
	    $aPut = array();

	    $rPutResource = fopen("php://input", "r");

	    while ($sData = fread($rPutResource, 1024)) {

	        $aSeparatePut = explode('&', $sData);

	        foreach($aSeparatePut as $sOne) {

	            $aOnePut = explode('=', $sOne);
	            $aPut[$aOnePut[0]] = $aOnePut[1];
	        }
	    }

	    return $aPut;
	}

	/**
	 * Set the HTTP status
	 *
	 * @access public
	 * @param  int $iCode
	 * @return void
	 */
	public static function setStatus($iCode)
	{
		if ($iCode === 200) { header('HTTP/1.1 200 Ok');  }
		else if ($iCode === 201) { header('HTTP/1.1 201 Created');  }
		else if ($iCode === 204) { header("HTTP/1.0 204 No Content");  }
		else if ($iCode === 403) { header('HTTP/1.1 403 Forbidden'); }
		else if ($iCode === 404) { header('HTTP/1.1 404 Not Found'); }
	}

    /**
     * get http method
     * @return string
     */
    public function getMethod() : string
    {
        return $this->server->get('REQUEST_METHOD');
    }

    /**
     * return languages accepted by the customer
     * @return array
     */
    public function getLanguages() : array
    {
        if (!self::isCliRequest()) { return explode(',', preg_replace('/^([^;]);?.*$/', '$1', $_SERVER['HTTP_ACCEPT_LANGUAGE'])); }
        else { return array(); }
    }

	/**
	 * get path info
	 * @return string
     */
	public function getPathInfo() : string
	{
		return $this->server->get('REQUEST_URI');
	}
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\db;

use cascade\components\dataInterface\MissingItemException;
use cascade\components\dataInterface\RecursionException;

/**
 * DataItem data item for db data interface connector.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataItem extends \cascade\components\dataInterface\connectors\generic\DataItem
{
    /**
     * Fill the unfilled child|parent_object_id field in the relation config.
     *
     * @param array      $config      relationship configuration
     * @param Model $otherObject the other object to fill in the relation config data
     */
    protected function fillRelationConfig(&$config, $otherObject)
    {
        if (isset($config['parent_object_id'])) {
            $config['child_object_id'] = $otherObject;
        } elseif (isset($config['child_object_id'])) {
            $config['parent_object_id'] = $otherObject;
        }
    }

    /**
     * @inheritdoc
     */
    protected function handleLocal($baseAttributes = [])
    {
        if ($this->ignoreLocalObject) {
            return false;
        }
        // local to foreign

        // find
        return false;
    }

    /**
     * Retrieve the foreign object.
     *
     * @throws RecursionException   when an object load is attempted when it is already being loaded above the call
     * @throws MissingItemException when the item can't be found in the foreign data source
     */
    protected function loadForeignObject()
    {
        if ($this->_isLoadingForeignObject) {
            throw new RecursionException('Ran into recursion while loading foreign object');
        }
        $this->_isLoadingForeignObject = true;
        if (isset($this->foreignPrimaryKey)) {
            $foreignObject = $this->dataSource->getForeignDataModel($this->foreignPrimaryKey);
            if ($foreignObject) {
                $this->foreignObject = $foreignObject;
            }
        }
        if (empty($this->_foreignObject)) {
            \d($this->foreignPrimaryKey);
            \d($this->dataSource->name);
            throw new MissingItemException('Foreign item could not be found: ' . $this->foreignPrimaryKey);
        }
        $this->_isLoadingForeignObject = false;
    }

    /**
     * Retrieve the local object.
     *
     * @throws RecursionException when an object load is attempted when it is already being loaded above the call
     */
    protected function loadLocalObject()
    {
        if ($this->_isLoadingLocalObject) {
            throw new RecursionException('Ran into recursion while loading local object');
        }
        $this->_isLoadingLocalObject = true;
        if (isset($this->foreignObject) && !isset($this->_localObject)) {
            $keyTranslation = $this->dataSource->getKeyTranslation($this->foreignObject);
            if (!empty($keyTranslation) && ($localObject = $keyTranslation->object)) {
                $this->localObject = $localObject;
            }
        }
        $this->_isLoadingLocalObject = false;
    }
}


<?php

namespace nadir2\core;

/**
 * This is a factory class for generating of View-objects (View, Layout).
 * @author Leonid Selikhov
 */
class ViewFactory
{

    /**
     * @ignore.
     */
    private function __construct()
    {
        // Nothing here ...
    }

    /**
     * The method creates a view object assosiated with the specific controller and
     * action in it. If controller name is empty it means a markup file determined
     * only with action name. It doesn't physically consist into the direcory named
     * as controller, it's in the root of the view directory.
     * @param string $actionName The action name.
     * @param string $ctrlName|null The controller name (as optional)
     * @return \nadir2\core\View|null It returns null if view file isn't readable.
     */
    public static function createView(
        string $actionName,
        ?string $ctrlName = null
    ): ?View {
        $viewsRoot = AppHelper::getInstance()->getComponentRoot('views');
        $addPath   = '';
        if (!empty($ctrlName)) {
            $addPath .= \DIRECTORY_SEPARATOR.strtolower($ctrlName);
        }
        $viewFile = $viewsRoot.$addPath.\DIRECTORY_SEPARATOR
            .strtolower($actionName).'.php';
        if (is_readable($viewFile)) {
            return new View($viewFile);
        }
        return null;
    }

    /**
     * It creates a layout object.
     * @param string $layoutName The layout name.
     * @param \nadir2\core\View $view The object of view.
     * @return \nadir2\core\Layout|null It returns null if layout file isn't
     * readable.
     */
    public static function createLayout(string $layoutName, View $view): ?Layout
    {
        $layoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts');
        $layoutFile  = $layoutsRoot.\DIRECTORY_SEPARATOR
            .strtolower($layoutName).'.php';
        if (is_readable($layoutFile)) {
            return new Layout($layoutFile, $view);
        }
        return null;
    }

    /**
     * The method creates a snippet-object.
     * @param type $snptName The snippet name.
     * @return \nadir2\core\Snippet|null. It returns null if snippet file isn't
     * readable.
     */
    public static function createSnippet(string $snptName): ?Snippet
    {
        $snptRoot = AppHelper::getInstance()->getComponentRoot('snippets');
        $snptFile  = $snptRoot.\DIRECTORY_SEPARATOR
            .strtolower($snptName).'.php';
        if (is_readable($snptFile)) {
            return new Snippet($snptFile);
        }
        return null;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Repository\RedirectionRepositoryInterface;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class RedirectionRepository
 */
class RedirectionRepository extends AbstractAggregateRepository implements RedirectionRepositoryInterface
{
    /**
     * @param string $nodeId
     * @param string $locale
     * @param string $siteId
     *
     * @return array
     */
    public function findByNode($nodeId, $locale, $siteId){
        $qa = $this->createAggregationQuery();

        $qa->match(array(
            'nodeId' => $nodeId,
            'locale' => $locale,
            'siteId' => $siteId,
        ));

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @param string $siteId
     *
     * @return array
     */
    public function findBySiteId($siteId){
        $qa = $this->createAggregationQuery();

        $qa->match(array(
            'siteId' => $siteId,
        ));

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return array
     */
    public function findForPaginate(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregationQuery();

        $this->filterSearch($configuration, $qa);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @return int
     */
    public function count()
    {
        $qa = $this->createAggregationQuery();

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param string $pattern
     * @param string $redirectionId
     *
     * @return int
     */
    public function countByPattern($pattern, $redirectionId)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'routePattern' => $pattern,
            '_id' => array('$ne' => new \MongoId($redirectionId))
        ));

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return int
     */
    public function countWithFilter(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregationQuery();
        $this->filterSearch($configuration, $qa);

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param Stage                       $qa
     *
     * @return array
     */
    protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa)
    {
        $siteName = $configuration->getSearchIndex('site_name');
        if (null !== $siteName && '' !== $siteName) {
            $qa->match(array('siteName' => new \MongoRegex('/.*' . $siteName . '.*/i')));
        }

        $locale = $configuration->getSearchIndex('locale');
        if (null !== $locale && '' !== $locale) {
            $qa->match(array('locale' => new \MongoRegex('/.*' . $locale . '.*/i')));
        }

        $routePattern = $configuration->getSearchIndex('route_pattern');
        if (null !== $routePattern && '' !== $routePattern) {
            $qa->match(array('routePattern' => new \MongoRegex('/.*' . $routePattern . '.*/i')));
        }

        $redirection = $configuration->getSearchIndex('redirection');
        if (null !== $redirection && '' !== $redirection) {
            $qa->match(array('$or' => array(
                array('url'    => new \MongoRegex('/.*' . $redirection . '.*/i')),
                array('nodeId' => new \MongoRegex('/.*' . $redirection . '.*/i'))
            )));
        }

        $permanent = $configuration->getSearchIndex('permanent');
        if (null !== $redirection && '' !== $permanent) {
            if ('true' == $permanent) {
                $qa->match(array('permanent' => true));
            }
            if ('false' == $permanent) {
                $qa->match(array('permanent' => false));
            }
        }

        return $qa;
    }

    /**
     * @param array $redirectionIds
     *
     * @throws \Exception
     */
    public function removeRedirections(array $redirectionIds)
    {
        $redirectionMongoIds = array();
        foreach ($redirectionIds as $redirectionId) {
            $redirectionMongoIds[] = new \MongoId($redirectionId);
        }

        $qb = $this->createQueryBuilder();
        $qb->remove()
            ->field('id')->in($redirectionMongoIds)
            ->getQuery()
            ->execute();
    }
}


<?php namespace Versatile\View;

use Versatile\View\Contracts\CollectionFactory;
use Versatile\Query\Builder;
use Versatile\Introspection\Contracts\TitleIntrospector;
use Versatile\Introspection\Contracts\TypeIntrospector;
use Collection\View\Collection;
use Collection\ColumnList;
use Collection\ValueGetter\DottedObjectAccess;
use Collection\Table\Column;

class QueryBuilderFactory implements CollectionFactory
{

    protected $namer;

    protected $types;

    public function __construct(TitleIntrospector $namer,
                                TypeIntrospector $types)
    {
        $this->namer = $namer;
        $this->types = $types;
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return \Collection\Collection
     **/
    public function create($searchable, array $params=[], $view='html')
    {
        $collection = $this->createCollection($searchable);
        $collection->setSrc($searchable->get());
        $this->assignColumns($searchable, $collection);
        return $collection;
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return \Collection\Collection
     **/
    public function paginate($searchable, array $params=[], $view='html')
    {
        $collection = $this->createCollection($searchable);

        $perPage = (isset($params['per_page']) && is_numeric($params['per_page'])) ? $params['per_page'] : null;

        $collection->setSrc($searchable->paginate([], $perPage));
        $this->assignColumns($searchable, $collection);

        return $collection;
    }

    /**
     * {@inheritdoc}
     *
     * @param mixed $searchable
     * @param array $params
     * @param string $view
     * @return bool
     **/
    public function canCreate($searchable, array $params=[], $view='html')
    {
        if ($searchable instanceof Builder) {
            return true;
        }
        return false;
    }

    protected function createCollection(Builder $builder)
    {
        $collection = new Collection;
        $collection->setItemClass($builder->modelClass());
        return $collection;
    }

    protected function assignColumns(Builder $builder, Collection $collection)
    {
        $columns = $this->findViewColumns($builder, $collection);

        $columnList = new ColumnList;
        $accessor = new DottedObjectAccess;
        $rootModel = $builder->model();

        foreach ($columns as $columnName) {

            $column = Column::create()
                            ->setAccessor($columnName, $accessor)
                            ->setTitle($this->namer->keyTitle($rootModel, $columnName));
            $columnList->push($column);

            if ($type = $this->types->keyType($rootModel, $columnName)) {
                $column->setValueFormatter($type);
            }
        }

        $collection->setColumns($columnList);

    }

    protected function findViewColumns(Builder $builder, Collection $collection)
    {
        if ($columns = $builder->getColumns()) {
            return $columns;
        }

        $src = $collection->getSrc();

        if (!count($src)) {
            return [$builder->model()->getKeyName()];
        }

        $firstResult = $src[0];

        return array_keys($firstResult->getAttributes());

    }

}


<?php

namespace PeterColes\Cluster\Servers\Adapters;

use Exception;
use PeterColes\Cluster\Contracts\Adapter;
use PeterColes\Cluster\Contracts\ServerAdapterInterface;

class DigitalOcean extends Adapter implements ServerAdapterInterface
{
    /**
     * The endpoint for all API calls to Digital Ocean (currently at v2)
     */
    protected $apiEndpoint = 'https://api.digitalocean.com/v2';

    /**
     * A set of default params for creating Digital Ocean droplets
     *
     * @todo add methods to make this more dynamic and controllable by consumers
     */
    protected $defaults = [
        "name" => "example.com",
        "region" => "lon1",
        "size" => "512mb",
        "image" => "ubuntu-14-04-x64",
        "ssh_keys" => null,
        "backups" => false,
        "ipv6" => true,
        "user_data" => null,
        "private_networking" => null
    ];

    /**
     * List details for an indexed server, or all servers if id is null.
     *
     * @param integer $id
     * @return GuzzleResponse object | array of GuzzleResponse objects
     */
    public function read($id = null)
    {
        if ($id === null) {
            $response = $this->client->request->get($this->apiEndpoint."/droplets");
        } else {
            $response = $this->client->request->get($this->apiEndpoint."/droplets/$id");
        }

        return $this->client->getBody($response);
    }

    /**
     * Create a new server based on parameters received.
     *
     * @param array $params
     * @return array
     */
    public function create($params = array())
    {
        $serverConfig = array_merge($this->defaults, $params);

        try {
            $response = $this->client->request->post($this->apiEndpoint."/droplets", ['json' => $serverConfig]);

            if (202 != $this->client->getStatus($response)) {
                throw new Exception('Unable to create server.');
            }
        } catch (Exception $e) {
            echo 'Unable to create server because '.$e->getMessage();
        }

        return $this->client->getBody($response);
    }

    /**
     * Delete the server corresponding to the given id.
     *
     * @param integer $id
     * @return integer | null
     */
    public function delete($id)
    {
        try {
            $response = $this->client->request->delete($this->apiEndpoint."/droplets/$id");

            $status = $this->client->getStatus($response);

            if (204 != $status) {
                throw new Exception('Digital Ocean responded that it could not delete it.');
            }

            return $status;

        } catch (Exception $e) {
            echo 'Unable to delete server because '.$e->getMessage();
        }
    }

    /**
     * List of available snapshots.
     *
     * @param array $params
     * @return array
     */
    public function images($params)
    {
        try {
            $response = $this->client->request->get($this->apiEndpoint.'/images'.$this->paramsToString($params));

            $status = $this->client->getStatus($response);

            if (200 != $status) {
                throw new Exception('Digital Ocean was not able to successfully provide a list of snapshots.');
            }

            return $this->client->getBody($response);

        } catch (Exception $e) {
            echo 'Unable to list snapshots because '.$e->getMessage();
        }
    }

    /**
     * Construct http client request headers.
     *
     * @return void
     */
    protected function setHeaders()
    {
        parent::setHeaders();

        $this->headers['headers']['Authorization'] = 'Bearer '.$this->params['token'];
    }

    /**
     * Construct http client request headers.
     * @todo this isn't the best place for this method - see where it gets used next and find it a better home
     *
     * @param array | null  $in   array of parameters to be converted to string for URL
     * @return string
     */
    private function paramsToString($in)
    {
        $out = http_build_query((array) $in);

        return strlen($out) > 0 ? '?'.$out : '';
    }
}


<?php

namespace PeterColes\Cluster\Queues\Adapters;

use PeterColes\Cluster\Contracts\Adapter;
use PeterColes\Cluster\Contracts\QueueAdapterInterface;

class IronMQ extends Adapter implements QueueAdapterInterface
{
    /**
     * The endpoint for all API calls to Digital Ocean (currently at v2)
     */
    // @todo support for all regions
    protected $apiEndpoint = 'https://mq-aws-us-east-1.iron.io/1';

    /**
     * List details for an indexed server, or all servers if id is null.
     *
     * @param string $queue
     * @return integer
     */
    public function count($queue)
    {
        // @todo remove hard-coded project
        $response = $this->client->request->get(
            $this->apiEndpoint.'/projects/'.$this->params['project'].'/queues/'.$queue
        );

        return $this->client->getBody($response);
    }

    /**
     * Receives the name of a queue and clears it.
     *
     * @param string $queue
     * @return void
     */
    public function clear($queue)
    {
        $this->client->request->post(
            $this->apiEndpoint.'/projects/'.$this->params['project'].'/queues/'.$queue.'/clear'
        );
    }

    /**
     * Construct http client request headers.
     *
     * @return void
     */
    protected function setHeaders()
    {
        parent::setHeaders();

        $this->headers['headers']['Authorization'] = 'OAuth '.$this->params['token'];
    }
}


<?php
namespace Lead\Benchmark\Reporter;

use SimpleBench\Utils;

class Text
{
    /**
     * The benchmark.
     *
     * @object
     */
    protected $_benchmark = null;

    /**
     * Constructor
     *
     * @param object $benchmark The benchmark instance.
     */
    public function __construct($benchmark)
    {
        $this->_benchmark = $benchmark;
    }

    /**
     * Returns the bar chart.
     *
     * @return string The bar chart.
     */
    public function chart()
    {
        $result = '';

        $ranking = $this->_benchmark->matrix()->ranking();

        $maxLength = 0;

        $maxRate = 0;

        foreach($ranking as $task) {
            if ($task->failed()) {
                continue;
            }
            if ($task->rate() > $maxRate){
                $maxRate = $task->rate();
            }
            if (mb_strlen($task->name()) > $maxLength){
                $maxLength = mb_strlen($task->name());
            }
        }

        foreach($ranking as $task) {
            $name = $task->name();
            $result .= $this->mb_str_pad($name, $maxLength, ' ', STR_PAD_RIGHT);

            if ($task->failed()) {
                $ratio = 0;
                $result .= $this->mb_str_pad('x', 10);
            } else {
                $rate = $task->rate();
                $ratio = ($rate / $maxRate);
                $result .= $this->mb_str_pad(round($ratio*100) . '%', 10);
            }
            $result .= ' | ';

            $width = 60;
            $chars = (int) ($width * $ratio);
            $result .= str_repeat('█', $chars);
            $result .= str_repeat(' ', $width - $chars );
            $result .= "  |\n";
        }
        return $result;
    }

    /**
     * Returns the report.
     *
     * @return string The report.
     */
    public function table()
    {
        $ranking = $this->_benchmark->matrix()->ranking();
        $matrix = $this->_benchmark->matrix()->matrix();

        if (!$ranking) {
            return;
        }

        $columnLength = [];
        $maxLength = 0;
        foreach($ranking as $task) {
            $name = $task->name();
            if (preg_match('~^([\w\s]+)~', $name, $matches)) {
                $columnLength[$name] = mb_strlen(trim($matches[1]));
            } else {
                $columnLength[$name] = mb_strlen($name);
            }
            if (mb_strlen($name) > $maxLength){
                $maxLength = mb_strlen($name);
            }
        }

        $result = '';
        $result .= $this->mb_str_pad('', $maxLength);
        $result .= $this->mb_str_pad('Rate', 10);
        $result .= $this->mb_str_pad('Mem', 8);

        foreach($ranking as $task) {
            $name = $task->name();
            if (preg_match('~^([\w\s]+)~', $name, $matches)) {
                $result .= $this->mb_str_pad(trim($matches[1]), $columnLength[$name] + 2);
            } else {
                $result .= $this->mb_str_pad($name, $columnLength[$name] + 2);
            }
        }
        $result .= "\n";

        foreach($ranking as $task1) {
            $name1 = $task1->name();
            $result .= $this->mb_str_pad($name1, $maxLength, ' ', STR_PAD_RIGHT);
            $task1 = $this->_benchmark->task($name1);

            $result .= $this->mb_str_pad($this->readableSize($task1->rate()) . '/s', 10);
            $result .= $this->mb_str_pad($this->readableSize($task1->memory(), 0, 1024) . 'B', 8);

            foreach($ranking as $task2) {
                $name2 = $task2->name();
                if ($task1->failed() || $task2->failed()) {
                    $result .= $this->mb_str_pad('x', $columnLength[$name2] + 2);
                } else {
                    $percent = $matrix[$name1][$name2] !== 100 ? $matrix[$name1][$name2] : '--';
                    $result .= $this->mb_str_pad($percent . '%', $columnLength[$name2] + 2);
                }
            }
            $result .= "\n";
        }
        return $result;
    }

    /**
     * Humanizes values using an appropriate unit.
     *
     * @return integer $value     The value.
     * @return integer $precision The required precision.
     * @return integer $base      The unit base.
     * @return string             The Humanized string value.
     */
    public function readableSize($value, $precision = 0, $base = 1000)
    {
        $i = 0;
        if (!$value) {
            return '0';
        }
        $isNeg = false;
        if ($value < 0) {
            $isNeg = true;
            $value = -$value;
        }
        if ($value >= 1) {
            $units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
            while (($value / $base) >= 1) {
                $value = $value / $base;
                $i++;
            }
            $unit = isset($units[$i]) ? $units[$i] : '?';
        } else {
            $units = ['', 'm', 'µ', 'n', 'p', 'f', 'a', 'z'];
            while (($value * $base) <= $base) {
                $value = $value * $base;
                $i++;
            }
            $unit = isset($units[$i]) ? $units[$i] : '?';

        }
        return round($isNeg ? -$value : $value, $precision) . $unit;
    }

    /**
     * Pad a string to a certain length with another string.
     *
     * @param  string $input  The input string.
     * @param  string $length The padding length.
     * @param  string $string The padding string.
     * @param  string $type   The type of padding.
     * @return string         The padded string.
     */
    public function mb_str_pad($input, $length, $string = ' ', $type = STR_PAD_LEFT)
    {
        return str_pad($input, $length + strlen($input) - mb_strlen($input), $string, $type );
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\file;

use canis\base\exceptions\Exception;
use canis\helpers\Match;
use Yii;

/**
 * SourceFile [[@doctodo class_description:cascade\components\dataInterface\connectors\file\SourceFile]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class SourceFile extends \canis\base\Object
{
    /**
     * @var [[@doctodo var_type:id]] [[@doctodo var_description:id]]
     */
    public $id;
    /**
     * @var [[@doctodo var_type:url]] [[@doctodo var_description:url]]
     */
    public $url;
    /**
     * @var [[@doctodo var_type:local]] [[@doctodo var_description:local]]
     */
    public $local;
    /**
     * @var [[@doctodo var_type:skipLines]] [[@doctodo var_description:skipLines]]
     */
    public $skipLines = 1;
    /**
     * @var [[@doctodo var_type:idColumn]] [[@doctodo var_description:idColumn]]
     */
    public $idColumn = 'id';
    /**
     * @var [[@doctodo var_type:delimeter]] [[@doctodo var_description:delimeter]]
     */
    public $delimeter = ',';
    /**
     * @var [[@doctodo var_type:excelSheetIndex]] [[@doctodo var_description:excelSheetIndex]]
     */
    public $excelSheetIndex = 0;
    /**
     * @var [[@doctodo var_type:ignore]] [[@doctodo var_description:ignore]]
     */
    public $ignore = [];

    /**
     * @var [[@doctodo var_type:_headers]] [[@doctodo var_description:_headers]]
     */
    protected $_headers;
    /**
     * @var [[@doctodo var_type:_filePointer]] [[@doctodo var_description:_filePointer]]
     */
    protected $_filePointer;
    /**
     * @var [[@doctodo var_type:_lines]] [[@doctodo var_description:_lines]]
     */
    protected $_lines;

    /**
     * [[@doctodo method_description:__destruct]].
     */
    public function __destruct()
    {
        if (!empty($this->_filePointer)) {
            fclose($this->_filePointer);
        }
    }

    /**
     * [[@doctodo method_description:clean]].
     */
    public function clean()
    {
        $this->_lines = null;
    }

    /**
     * Get lines.
     *
     * @param boolean $lazy [[@doctodo param_description:lazy]] [optional]
     * @param boolean $raw  [[@doctodo param_description:raw]] [optional]
     *
     * @return [[@doctodo return_type:getLines]] [[@doctodo return_description:getLines]]
     */
    public function getLines($lazy = true, $raw = false)
    {
        if (is_null($this->_lines)) {
            $file = $this->filePointer;
            if (!$file) {
                return false;
            }
            rewind($file);
            $this->_lines = [];
            $currentLineNumber = 0;
            while (($buffer = fgetcsv($this->filePointer, 0, $this->delimeter)) !== false) {
                $currentLineNumber++;
                if ($currentLineNumber <= $this->skipLines) {
                    continue;
                }
                $line = Yii::createObject(['class' => SourceFileLine::className(), 'sourceFile' => $this, 'lineNumber' => $currentLineNumber-1, 'content' => $buffer]);
                if ($this->testIgnore($line)) {
                    continue;
                }
                $lineId = $line->id;
                if (!isset($lineId)) {
                    continue;
                }
                $this->_lines[$lineId] = $line;
                if ($lazy) {
                    $line->clean();
                }
            }
        }

        return $this->_lines;
    }

    /**
     * [[@doctodo method_description:testIgnore]].
     *
     * @param [[@doctodo param_type:line]] $line [[@doctodo param_description:line]]
     *
     * @return [[@doctodo return_type:testIgnore]] [[@doctodo return_description:testIgnore]]
     */
    public function testIgnore($line)
    {
        foreach ($this->ignore as $field => $test) {
            $settings = [];
            if (is_numeric($field)) {
                $settings = $test;
                $field = isset($settings['field']);
                $test = $settings['test'];
            }
            $value = null;
            if (isset($line->attributes[$field])) {
                $value = $line->attributes[$field];
            }
            if ($test instanceof Match && $test->test($value)) {
                return true;
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:readLine]].
     *
     * @param [[@doctodo param_type:line]] $line [[@doctodo param_description:line]]
     *
     * @return [[@doctodo return_type:readLine]] [[@doctodo return_description:readLine]]
     */
    public function readLine($line)
    {
        if (!$this->filePointer) {
            return false;
        }
        rewind($this->filePointer);
        $currentLineNumber = 0;
        while (($buffer = fgetcsv($this->filePointer, 0, $this->delimeter)) !== false) {
            $currentLineNumber++;
            if ($currentLineNumber === $line) {
                return $buffer;
            }
        }

        return false;
    }

    /**
     * Get file pointer.
     *
     * @return [[@doctodo return_type:getFilePointer]] [[@doctodo return_description:getFilePointer]]
     */
    public function getFilePointer()
    {
        if (!isset($this->_filePointer)) {
            ini_set('auto_detect_line_endings', true);
            $this->_filePointer = false;
            $file = null;
            if (isset($this->local) && file_exists($this->local)) {
                $file = $this->local;
                $pathinfo = pathinfo($this->local);
            } elseif (isset($this->url)) {
                $fileCacheKey = md5(__CLASS__ . __FUNCTION__ . $this->url);
                $fileContent = Yii::$app->fileCache->get($fileCacheKey);
                $pathinfo = pathinfo($this->url);
                $file = Yii::$app->fileStorage->getTempFile(false, $pathinfo['extension']);
                if ($fileContent) {
                    file_put_contents($file, $fileContent);
                } else {
                    if (!$this->downloadFile($this->url, $file)) {
                        $file = null;
                    } else {
                        Yii::$app->fileCache->set($fileCacheKey, file_get_contents($file), 86400);
                    }
                }
            }
            if (isset($file)) {
                $file = $this->normalizeFile($file);
            }
            if (file_exists($file)) {
                $this->_filePointer = fopen($file, 'r');
            }
        }

        return $this->_filePointer;
    }

    /**
     * [[@doctodo method_description:normalizeFile]].
     *
     * @param [[@doctodo param_type:filepath]] $filepath [[@doctodo param_description:filepath]]
     *
     * @return [[@doctodo return_type:normalizeFile]] [[@doctodo return_description:normalizeFile]]
     */
    public function normalizeFile($filepath)
    {
        $pathinfo = pathinfo($filepath);
        switch ($pathinfo['extension']) {
            case 'csv':
                return $filepath;
            break;
            case 'xls':
                $tmpfile = Yii::$app->fileStorage->getTempFile();

                return $this->convertExcel($filepath, $tmpfile, 'Excel5');
            break;
            case 'xlsx';
                $tmpfile = Yii::$app->fileStorage->getTempFile();

                return $this->convertExcel($filepath, $tmpfile);
            break;
        }
    }

    /**
     * [[@doctodo method_description:_loadExcel]].
     */
    private function _loadExcel()
    {
        spl_autoload_unregister(['BaseYii', 'autoload']);
        $path = CANIS_APP_VENDOR_PATH . DIRECTORY_SEPARATOR . 'phpoffice' . DIRECTORY_SEPARATOR . 'phpexcel' . DIRECTORY_SEPARATOR . 'Classes' . DIRECTORY_SEPARATOR . 'PHPExcel.php';
        require_once $path;
    }

    /**
     * [[@doctodo method_description:_unloadExcel]].
     */
    private function _unloadExcel()
    {
        spl_autoload_register(['Yii', 'autoload']);
    }

    /**
     * [[@doctodo method_description:convertExcel]].
     *
     * @param [[@doctodo param_type:filepath]] $filepath [[@doctodo param_description:filepath]]
     * @param [[@doctodo param_type:tmpfile]]  $tmpfile  [[@doctodo param_description:tmpfile]]
     * @param string                           $filetype [[@doctodo param_description:filetype]] [optional]
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return [[@doctodo return_type:convertExcel]] [[@doctodo return_description:convertExcel]]
     *
     */
    protected function convertExcel($filepath, $tmpfile, $filetype = 'Excel2007')
    {
        $this->_loadExcel();
        $fileCacheKey = md5(serialize([__CLASS__, __FUNCTION__, $this->id, $this->url, $this->local]));
        $test = Yii::$app->fileCache->get($fileCacheKey);
        if ($test) {
            file_put_contents($tmpfile, $test);

            return $tmpfile;
        }
        echo "Converting {$filepath}...\n";
        if (!class_exists('\PHPExcel_IOFactory')) {
            $this->_unloadExcel();
            throw new Exception("Unable to load PHPExcel library!");
        }
        $objReader = \PHPExcel_IOFactory::createReader($filetype);
        $objPHPExcelReader = $objReader->load($filepath);
        $loadedSheetNames = $objPHPExcelReader->getSheetNames();
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
        foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
            $objWriter->setSheetIndex($sheetIndex);
            $objWriter->save($tmpfile);
            break;
        }
        $this->_unloadExcel();
        Yii::$app->fileCache->set($fileCacheKey, file_get_contents($tmpfile), 86400);

        return $tmpfile;
    }

    /**
     * [[@doctodo method_description:downloadFile]].
     *
     * @param [[@doctodo param_type:url]]      $url      [[@doctodo param_description:url]]
     * @param [[@doctodo param_type:savePath]] $savePath [[@doctodo param_description:savePath]]
     *
     * @return [[@doctodo return_type:downloadFile]] [[@doctodo return_description:downloadFile]]
     */
    protected function downloadFile($url, $savePath)
    {
        echo "Download $url...\n";
        $fp = fopen($savePath, 'w');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        //curl_setopt($ch, CURLOPT_HEADER, 1);
        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        fclose($fp);
        if ($httpCode !== 200) {
            @unlink($savePath);

            return false;
        }

        if (!file_exists($savePath) || !filesize($savePath) === 0) {
            @unlink($savePath);

            return false;
        }

        return $savePath;
    }

    /**
     * Get headers.
     *
     * @return [[@doctodo return_type:getHeaders]] [[@doctodo return_description:getHeaders]]
     */
    public function getHeaders()
    {
        if (!isset($this->_headers)) {
            $this->_headers = $this->readLine(1);
            if (!$this->_headers) {
                $this->_headers = [];
            }
        }

        return $this->_headers;
    }

    /**
     * Set headers.
     *
     * @param [[@doctodo param_type:headers]] $headers [[@doctodo param_description:headers]]
     */
    public function setHeaders($headers)
    {
        $this->_headers = $headers;
    }
}


<?php
/**
 * This file is part of VinceTAdminBundle for Symfony2
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */

namespace VinceT\AdminBundle\Menu;

use Knp\Menu\Silex\RouterAwareFactory;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Sonata\AdminBundle\Admin\AdminInterface;

/**
 * MenuFactory
 *
 * @category VinceT
 * @package  VinceTAdminBundle
 * @author   Vincent Touzet <vincent.touzet@gmail.com>
 * @license  MIT License view the LICENSE file that was distributed with this source code.
 * @link     https://github.com/vincenttouzet/AdminBundle
 */
class MenuFactory extends RouterAwareFactory implements ContainerAwareInterface
{
    protected $container = null;

    /**
     * [__construct description]
     *
     * @param ContainerInterface $container [description]
     */
    public function __construct(ContainerInterface $container)
    {
        $this->setContainer($container);
        parent::__construct($this->container->get('router'));
    }

    /**
     * Sets the Container.
     *
     * @param ContainerInterface $container A ContainerInterface instance
     *
     * @return null
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Create an item
     *
     * @param string $name    Name of the item
     * @param array  $options Options
     *
     * @return VinceT\AdminBundle\Menu\MenuItem
     */
    public function createItem($name, array $options = array())
    {
        if (!empty($options['admin'])) {
            $admin = $options['admin'];
            if ( !$options['admin'] instanceof AdminInterface ) {
                $admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($admin);
            }
            $action = isset($options['admin_action']) ? $options['admin_action'] : 'list';
            $options['uri'] = $admin->generateUrl($action);
            $options['translationDomain'] = $admin->getTranslationDomain();
        }
        /**
         * Knp\Menu\Silex\RouterAwareFactory
         */
        if (!empty($options['route'])) {
            $params = isset($options['routeParameters']) ? $options['routeParameters'] : array();
            $absolute = isset($options['routeAbsolute']) ? $options['routeAbsolute'] : false;
            $options['uri'] = $this->generator->generate($options['route'], $params, $absolute);
        }

        // use VinceT\AdminBundle\Menu\MenuItem
        $item = new MenuItem($name, $this);

        $options = array_merge(
            array(
                'uri' => null,
                'label' => null,
                'attributes' => array(),
                'linkAttributes' => array(),
                'childrenAttributes' => array(),
                'labelAttributes' => array(),
                'extras' => array(),
                'display' => true,
                'displayChildren' => true,
                'translationDomain' => 'messages',
                'displayLink' => true,
                'displayLabel' => true,
            ),
            $options
        );

        $item
            ->setUri($options['uri'])
            ->setLabel($options['label'])
            ->setAttributes($options['attributes'])
            ->setLinkAttributes($options['linkAttributes'])
            ->setChildrenAttributes($options['childrenAttributes'])
            ->setLabelAttributes($options['labelAttributes'])
            ->setExtras($options['extras'])
            ->setDisplay($options['display'])
            ->setDisplayChildren($options['displayChildren'])
            ->setTranslationDomain($options['translationDomain'])
            ->setDisplayLink($options['displayLink'])
            ->setDisplayLabel($options['displayLabel']);

        return $item;

        return parent::createItem($name, $options);
    }
}


<?php
namespace FelixOnline\Base;

/**
 * Paginator object that wraps a Manager
 */
class Paginator
{
    /**
     * Manager
     */
    public $manager;

    /**
     * Number of items per page
     */
    public $pageSize;

    /**
     * Current page
     */
    public $page;

    /**
     * Last page number
     */
    public $lastPage;

    /**
     * Total number of items
     */
    public $count;

    /**
     *
     */
    public function __construct(BaseManager $manager, $page = 1, $pageSize = 20)
    {
        $this->manager = $manager;
        $this->page = $page;
        $this->pageSize = $pageSize;

        $this->calculateTotal();
    }

    protected function calculateTotal()
    {
        $this->count = $this->manager->count();

        $this->lastPage = (int) ceil($this->count / $this->pageSize);
    }

    /**
     * Get models for the specified page
     */
    public function getPage($page = null)
    {
        if (is_null($page)) {
            $page = $this->page;
        }
        list($offset, $size) = $this->getLimts($page);

        $this->manager->limit($offset, $size);

        return $this->manager->values();
    }

    /**
     * Returns array with first argument being the offset and the second the
     * page size
     */
    protected function getLimts($page)
    {
        $offset = ($page - 1) * $this->pageSize;
        return array($offset, $this->pageSize);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application 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://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Action\Seo;

use RedKiteCms\Action\BaseAction;
use RedKiteCms\Content\BlockManager\BlockManagerAdd;
use RedKiteCms\Content\Page\PageManager;
use Silex\Application;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class EditSeoAction defines the object assigned to edit a page for a specific language
 *
 * @package RedKiteCms\Action
 */
class EditSeoAction extends BaseAction
{
    /**
     * {@inheritdoc}
     */
    public function execute(array $options, $username)
    {
        $data = $options["data"];
        $pageName = $data["pageName"];
        $seoData = $data["seoData"];
        $pageManager = $this->app["red_kite_cms.page_manager"];
        $pageManager
            ->contributor($username)
            ->edit($pageName, $seoData)
        ;
    }
}


<?php
namespace eMacros\Runtime\Symbol;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;

class SymbolExists implements Applicable {
	/**
	 * Checks if the given symbol exists on current environment
	 * Usage: (sym-exists "true") (sym-exists "_value")
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("SymbolExists: No parameters found.");
		$ref = $arguments[0]->evaluate($scope);
		if (!is_string($ref) || empty($ref))
			throw new \InvalidArgumentException("SymbolExists: Symbol must be specified as a non-empty string.");
		return array_key_exists($ref, $scope->symbols);
	}
}
?>


<?php

declare(strict_types=1);

namespace Ruwork\Reminder\Manager;

use Psr\Container\ContainerInterface;
use Ruwork\Reminder\Event\ReminderEvent;
use Ruwork\Reminder\Event\ReminderEvents;
use Ruwork\Reminder\Item\ClearableItemInterface;
use Ruwork\Reminder\Item\ItemInterface;
use Ruwork\Reminder\Marker\MarkerInterface;
use Ruwork\Reminder\Provider\ProviderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

final class Reminder implements ReminderInterface
{
    private $dispatcher;
    private $marker;
    private $providers;

    public function __construct(
        EventDispatcherInterface $dispatcher,
        MarkerInterface $marker,
        ContainerInterface $providers
    ) {
        $this->dispatcher = $dispatcher;
        $this->marker = $marker;
        $this->providers = $providers;
    }

    /**
     * {@inheritdoc}
     */
    public function remind(string $providerName, ?\DateTimeImmutable $now = null): void
    {
        $now = $now ?? new \DateTimeImmutable();

        /** @var ProviderInterface $provider */
        $provider = $this->providers->get($providerName);

        /** @var ItemInterface $item */
        foreach ($provider->getItems($now) as $item) {
            $markerId = $providerName.':'.$item->getId();

            if ($this->marker->isMarked($markerId)) {
                continue;
            }

            $event = new ReminderEvent($providerName, $now, $item);
            $this->dispatcher->dispatch(ReminderEvents::remind($providerName), $event);

            $this->marker->mark($markerId);

            if ($item instanceof ClearableItemInterface) {
                $item->clear();
            }
        }
    }
}


<?php

Web2All_Manager_Main::loadClass('Web2All_Table_Collection_IDataProvider');

/**
 * Web2All Table Collection simple DataProvider class
 *
 * This class defines a very basic data provider for
 * a Web2All_Table_Collection.
 *
 * For usage example see Web2All_Table_Collection documentation.
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2008-2011 Web2All BV
 * @since 2008-07-22
 */
class Web2All_Table_Collection_SimpleDataProvider extends Web2All_Manager_Plugin implements Web2All_Table_Collection_IDataProvider {

  /**
   * ADODB database connection
   *
   * @var ADOConnection
   */
  protected $db;

  /**
   * how many records to return (truncate)
   *
   * @var int
   */
  protected $limit;

  /**
   * ignore the first $offset records when building resultset
   *
   * @var int
   */
  protected $offset;

  /**
   * the sql query
   *
   * @var string
   */
  protected $sql;

  /**
   * list of query placeholder values
   *
   * @var array
   */
  protected $params;

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param ADOConnection $db
   */
  public function __construct(Web2All_Manager_Main $web2all,$db) {
    parent::__construct($web2all);

    $this->db=$db;

    $this->limit=-1;

    $this->offset=-1;

    $this->params=array();
  }

  /**
   * Assign a range to fetch from the list.
   * If you do this before calling fetchData() then
   * only results from $offset to $offset+$limit
   * are returned
   *
   * @param int $limit
   * @param int $offset
   */
  public function setRange($limit,$offset)
  {
    $this->limit=$limit;
    $this->offset=$offset;
  }

  /**
   * Set the SQL to use with this query. You NEED to call this
   * method if you want to use this dataprovider.
   *
   * It is your own responsibility to select all fields which are
   * needed for the collection object. You can use placeholders
   * if you also use the setParams method.
   *
   * @param string $sql
   */
  public function setSQL($sql)
  {
  	$this->sql=$sql;
  }

  /**
   * Set the params to use in the SQL query.
   *
   * Params should be provided as an array of values, just
   * like you would do with the adodb Execute method.
   *
   * @param array $params
   */
  public function setParams($params)
  {
  	$this->params=$params;
  }

  /**
   * Execute the query and return the adodb recordset.
   *
   * Make sure you have at least set the sql for the query, will throw exception otherwise.
   *
   * @return ADORecordSet
   */
  public function getADORecordSet()
  {
    if (!$this->sql) {
    	// no sql set
      throw new Exception('Web2All_Table_Collection_SimpleDataProvider::getADORecordSet: no SQL query set');
    }

  	return $this->db->SelectLimit($this->sql,$this->limit,$this->offset,$this->params);
  }

}
?>