<?php

/**
 * Provides the ability to authenticate against credentials stored in a database
 * table.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.auth.adapter.dbtable.html Zend_Auth_Adapter_DbTable
 * @link http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html#zend.auth.introduction.results Zend_Auth_Result
 */
class Benri_Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable
{
    /**
     * The table name to check.
     *
     * @var string
     */
    protected $_tableName = 'user';

    /**
     * The column to use as the identity.
     *
     * @var string
     */
    protected $_identityColumn = 'username';

    /**
     * Columns to be used as the credentials.
     *
     * @var string
     */
    protected $_credentialColumn = 'password';

    /**
     * Sets a flag for usage of identical identities with unique credentials.
     * It accepts ints (0, 1) or bool (true, false) parameters.
     *
     * @internal
     * @param int $flag
     * @return Benri_Auth_Adapter_DbTable
     */
    public function setAmbiguityIdentity($flag)
    {
        $this->_ambiguityIdentity = false;
    }

    /**
     * Called to attempt an authentication.
     *
     * Previous to this call, this adapter would have already been configured
     * with all necessary information to successfully connect to a database
     * table and attempt to find a record matching the provided identity.
     *
     * @return Zend_Auth_Result
     * @see http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html#zend.auth.introduction.results Zend_Auth_Result
     * @throws Zend_Auth_Adapter_Exception if answering the authentication
     *  query is impossible
     */
    public function authenticate()
    {
        $this->_authenticateSetup();

        $dbSelect   = $this->_authenticateCreateSelect();
        $identity   = $this->_authenticateQuerySelect($dbSelect);
        $authResult = $this->_authenticateValidateResultSet($identity);

        if ($authResult instanceof Zend_Auth_Result) {
            return $authResult;
        }

        /// _authenticateValidateResult() attempts to make certain that only
        /// one record was returned in the resultset.
        return $this->_authenticateValidateResult(array_shift($identity));
    }

    /**
     * Creates a Zend_Db_Select object that is completely configured to be
     * queried against the database.
     *
     * @return Zend_Db_Select
     * @see http://framework.zend.com/manual/1.12/en/zend.db.select.html Zend_Db_Select
     */
    protected function _authenticateCreateSelect()
    {
        $dbSelect = clone $this->getDbSelect();
        $dbSelect->from($this->_tableName)
            ->where("{$this->_identityColumn} = ?", $this->_identity)
            ->limit(1);

        return $dbSelect;
    }

    /**
     * Attempts to make certain that only one record was returned in the
     * resultset.
     *
     * @param array $resultIdentities
     * @return Zend_Auth_Result
     * @see http://framework.zend.com/manual/1.12/en/zend.auth.introduction.html#zend.auth.introduction.results Zend_Auth_Result
     */
    protected function _authenticateValidateResult($resultIdentity)
    {
        $code    = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
        $message = 'Supplied credential is invalid.';

        if (Benri_Util_String::verifyPassword($this->_credential, $resultIdentity[$this->_credentialColumn])) {
            $code             = Zend_Auth_Result::SUCCESS;
            $message          = 'Authentication successful.';
            $this->_resultRow = $resultIdentity;
        }

        $this->_authenticateResultInfo['code']       = $code;
        $this->_authenticateResultInfo['messages'][] = $message;

        /// _authenticateCreateAuthResult creates a Zend_Auth_Result object
        /// from the information that has been collected during the
        /// Benri_Auth_Adapter_DbTable::authenticate() attempt.
        return $this->_authenticateCreateAuthResult();
    }
}


<?php
namespace Wambo\Catalog\Mapper;

use Wambo\Catalog\Exception\ProductException;
use Wambo\Catalog\Model\Product;
use Wambo\Catalog\Model\SKU;
use Wambo\Catalog\Model\Slug;

/**
 * Class ProductMapper creates \Wambo\Model\Product models from data bags with product data.
 *
 * @package Wambo\Mapper
 */
class ProductMapper
{
    const FIELD_SKU = "sku";
    const FIELD_SLUG = "slug";

    /**
     * @var array $mandatoryFields A list of all mandatory fields of a Product
     */
    private $mandatoryFields = [self::FIELD_SKU, self::FIELD_SLUG];

    /**
     * @var ContentMapper
     */
    private $contentMapper;

    /**
     * Creates a new ProductMapper instance
     *
     * @param ContentMapper $contentMapper A class for mapping product content
     */
    public function __construct(ContentMapper $contentMapper)
    {
        $this->contentMapper = $contentMapper;
    }

    /**
     * Get a Catalog model from an array of unstructured product data
     *
     * @param array $productData An array containing product attributes
     *
     * @return Product
     *
     * @throws ProductException If a mandatory field is missing
     * @throws ProductException If the no Product could be created from the given product data
     */
    public function getProduct(array $productData)
    {
        // check if all mandatory fields are present
        foreach ($this->mandatoryFields as $mandatoryField) {
            if (!array_key_exists($mandatoryField, $productData)) {
                throw new ProductException("The field '$mandatoryField' is missing in the given product data");
            }
        }

        // try to create a product from the available data
        try {

            // sku
            $sku = new SKU($productData[self::FIELD_SKU]);

            // slug
            $slug = new Slug($productData[self::FIELD_SLUG]);

            // product content
            $content = $this->contentMapper->getContent($productData);

            $product = new Product($sku, $slug, $content);
            return $product;

        } catch (\Exception $productException) {
            throw new ProductException(sprintf("Failed to create a product from the given data: %s",
                $productException->getMessage()), $productException);
        }
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Form;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Form\ResetPassword,
    CmsUser\Options\ModuleOptions;

class ResetPasswordFormFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ResetPassword
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        /* @var $options ModuleOptions */
        $options = $services->get(ModuleOptions::class);

        $creationOptions = $options->toArray();

        // Use submit button by default
        if (!isset($creationOptions['use_submit_element'])) {
            $creationOptions['use_submit_element'] = true;
        }

        // Use reset button by default
        if (!isset($creationOptions['use_reset_element'])) {
            $creationOptions['use_reset_element'] = true;
        }

        return new ResetPassword('reset-password-form', $creationOptions);
    }
}


<?php

/*
 * This File is part of the Thapp\Jmg\Http\Psr7 package
 *
 * (c) iwyg <mail@thomas-appel.com>
 *
 * For full copyright and license information, please refer to the LICENSE file
 * that was distributed with this package.
 */

namespace Thapp\Jmg\Http\Psr7;

use Psr\Http\Message\StreamInterface;
use Thapp\Jmg\Resource\ImageResourceInterface;
use InvalidArgumentException;

/**
 * @class ImageStream
 *
 * @package Thapp\Jmg\Http\Psr7
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class ImageStream implements StreamInterface
{
    private $resource;
    public function __construct(ImageResourceInterface $image)
    {
        $this->setResource($image);
    }

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

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        if (null === $this->resource) {
            return;
        }

        fclose($this->resource);
    }

    /**
     * {@inheritdoc}
     */
    public function detach()
    {
        $resource = $this->resource;
        $this->resource = null;

        return $resource;
    }

    /**
     * {@inheritdoc}
     */
    public function getSize()
    {
        if (null === $this->resource) {
            return null;
        }

        $stat = fstat($this->resource);

        return $stat['size'];
    }

    /**
     * {@inheritdoc}
     */
    public function tell()
    {
        $this->throwOnNull('Resource is null.');

        return ftell($this->resource);
    }

    /**
     * {@inheritdoc}
     */
    public function eof()
    {
        if (null === $this->resource) {
            return true;
        }

        return feof($this->resource);
    }

    /**
     * {@inheritdoc}
     */
    public function isSeekable()
    {
        return null !== $this->resource;
    }

    public function seek($offset, $whence = SEEK_SET)
    {
        $this->throwOnNull();

        fseek($this->resource, $offset, $whence);
    }

    public function rewind()
    {
        return $this->seek(0);
    }

    /**
     * {@inheritdoc}
     */
    public function isWritable()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function write($string)
    {
        throw new \RuntimeException();
    }

    /**
     * {@inheritdoc}
     */
    public function isReadable()
    {
        return $this->resource !== null;
    }

    /**
     * {@inheritdoc}
     */
    public function read($length)
    {
        $this->throwOnNull();

        return fread($this->resource, $length);
    }

    /**
     * {@inheritdoc}
     */
    public function getContents()
    {
        $this->throwOnNull();

        return stream_get_contents($this->resource);
    }

    /**
     * {@inheritdoc}
     */
    public function getMetadata($key = null)
    {
        $this->throwOnNull();

        $meta = stream_get_meta_data($this->resource);

        return null === $key ? $meta : (isset($meta[$key]) ? $neta[$key] : null);
    }

    /**
     * throwOnNull
     *
     * @param string $message
     * @throws \RuntimeException if resource is null.
     *
     * @return void
     */
    private function throwOnNull($message = 'Stream error')
    {
        if (null === $this->resource) {
            throw new \RuntimeException($message);
        }
    }

    /**
     * setResource
     *
     * @param ImageResourceInterface $image
     *
     * @return resource
     */
    private function setResource(ImageResourceInterface $image)
    {
        $error = null;

        if ($image->isLocal()) {
            set_error_handler(function ($e, $msg) use (&$error) {
                $error = $msg;
            }, E_WARNING);

            $resource = fopen($image->getPath(), 'r');
            restore_error_handler();
        } else {
            $resource = fopen('php://temp', 'wb+');
            fwrite($resource, $image->getContents());
            rewind($resource);
        }

        if (null !== $error) {
            throw new InvalidArgumentException($error);
        }

        return $this->resource = $resource;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Command;

use Doctrine\Bundle\MongoDBBundle\Command\LoadDataFixturesDoctrineODMCommand;
use Doctrine\Common\DataFixtures\Executor\MongoDBExecutor;
use Doctrine\Common\DataFixtures\Purger\MongoDBPurger;
use OpenOrchestra\ModelBundle\DataFixtures\Loader\OrchestraContainerAwareLoader;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class OrchestraLoadDataFixturesDoctrineODMCommand
 */
class OrchestraLoadDataFixturesDoctrineODMCommand extends LoadDataFixturesDoctrineODMCommand
{
    /**
     * Configure the command
     */
    protected function configure()
    {
        $this
            ->setName('orchestra:mongodb:fixtures:load')
            ->setDescription('Load data fixtures to your database.')
            ->addOption('fixtures', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The directory or file to load data fixtures from.')
            ->addOption('append', null, InputOption::VALUE_NONE, 'Append the data fixtures instead of flushing the database first.')
            ->addOption('dm', null, InputOption::VALUE_REQUIRED, 'The document manager to use for this command.')
            ->addOption('type', null, InputOption::VALUE_OPTIONAL, 'Set type of loaded fixtures.')
            ->setHelp(<<<EOT
The <info>orchestra:mongodb:fixtures:load</info> command loads data fixtures from your bundles:

  <info>./app/console doctrine:mongodb:fixtures:load</info>

You can also optionally specify the path to fixtures with the <info>--fixtures</info> option:

  <info>./app/console doctrine:mongodb:fixtures:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2</info>

If you want to append the fixtures instead of flushing the database first you can use the <info>--append</info> option:

  <info>./app/console doctrine:mongodb:fixtures:load --append</info>

If you want to set the type of loaded fixtures you can use the <info>--type=[=TYPE]</info> option:

  <info>./app/console doctrine:mongodb:fixtures:load --type=production</info>

If you want to choose with prompt in all possible types of fixtures you can ignore the <info>--type</info> option:

  <info>./app/console doctrine:mongodb:fixtures:load</info>

EOT
            );
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return mixed
     * @throws \InvalidArgumentException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        if (!is_null($input->getOption('type'))) {
            $type = $input->getOption('type');
        } else {
            $type = $this->getHelperSet()->get('dialog')->ask(
                $output,
                'Choose type in ' . implode(', ', $this->getContainer()->getParameter('open_orchestra_model.fixtures.command')) . ' (all) : ',
                'all'
            );
        }

        $dm = $this->getContainer()->get('doctrine_mongodb')->getManager($input->getOption('dm'));
        $dirOrFile = $input->getOption('fixtures');
        if ($dirOrFile) {
            $paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);
        } else {
            $paths = $this->getContainer()->getParameter('doctrine_mongodb.odm.fixtures_dirs');
            $paths = is_array($paths) ? $paths : array($paths);
            foreach ($this->getContainer()->get('kernel')->getBundles() as $bundle) {
                $paths[] = $bundle->getPath().'/DataFixtures/MongoDB';
            }
        }

        $loader = new OrchestraContainerAwareLoader($this->getContainer(), $type);
        foreach ($paths as $path) {
            if (is_dir($path)) {
                $loader->loadFromDirectory($path);
            }
        }

        $fixtures = $loader->getFixtures();
        if (!$fixtures) {
            throw new \InvalidArgumentException(
                sprintf('Could not find any fixtures of %s type to load in: %s', $type, "\n\n- ".implode("\n- ", $paths))
            );
        }

        $purger = new MongoDBPurger($dm);
        $executor = new MongoDBExecutor($dm, $purger);
        $executor->setLogger(function($message) use ($output) {
            $output->writeln(sprintf('  <comment>></comment> <info>%s</info>', $message));
        });
        $executor->execute($fixtures, $input->getOption('append'));
    }
}


<?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 Error503DataGenerator
 */
class Error503DataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
        $htmlContent = <<<EOF

Site en maintenance

Le site est actuellement en maintenance. Vous pourrez à nouveau le consulter très prochainement.

EOF;
        $routePattern = "errorPage503";
        $language = "fr";

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

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

Website under maintenance

The site is currently under maintenance. You will be able to visit it again in the very near future.

EOF;
        $routePattern = "errorPage503";
        $language = "en";

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

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

Webseite unter Wartung

Die Seite befindet sich derzeit im Wartungsmodus. Sie können es wieder in sehr naher Zukunft zu besuchen.

EOF;
        $routePattern = "errorPage503";
        $language = "de";

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

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

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

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

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

        $nodeError503->setNodeType(NodeInterface::TYPE_ERROR);
        $nodeError503->setLanguage($language);
        $nodeError503->setNodeId(NodeInterface::ERROR_503_NODE_ID);
        $nodeError503->setName('503');
        $nodeError503->setVersionName($this->getVersionName($nodeError503));
        $nodeError503->setCreatedBy('fake_admin');
        $nodeError503->setParentId(NodeInterface::ROOT_PARENT_ID);
        $nodeError503->setRoutePattern($routePattern);
        $nodeError503->setInFooter(false);
        $nodeError503->setInMenu(false);
        $nodeError503->setOrder(-1);

        return $nodeError503;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use OpenOrchestra\ModelInterface\Model\WorkflowProfileInterface;
use OpenOrchestra\ModelInterface\Model\WorkflowTransitionInterface;
use OpenOrchestra\ModelInterface\Model\StatusInterface;

/**
 * Class WorkflowProfile
 *
 * @ODM\Document(
 *   collection="workflow_profile",
 *   repositoryClass="OpenOrchestra\ModelBundle\Repository\WorkflowProfileRepository"
 * )
 */
class WorkflowProfile implements WorkflowProfileInterface
{
    /**
     * @var string $id
     *
     * @ODM\Id
     */
    protected $id;

    /**
     * @var array $labels
     *
     * @ODM\Field(type="hash")
     */
    protected $labels;

    /**
     * @var array $descriptions
     *
     * @ODM\Field(type="hash")
     */
    protected $descriptions;

    /**
     * @var ArrayCollection
     *
     * @ODM\EmbedMany(
     *  targetDocument="OpenOrchestra\ModelInterface\Model\WorkflowTransitionInterface"
     * )
     */
    protected $transitions;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->initCollections();
        $this->labels = array();
        $this->descriptions = array();
    }

    /**
     * Clone the element
     */
    public function __clone()
    {
        $this->initCollections();
    }

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

    /**
     * @param string $language
     * @param string $label
     */
    public function addLabel($language, $label)
    {
        if (is_string($language) && is_string($label)) {
            $this->labels[$language] = $label;
        }
    }

    /**
     * @param string $language
     */
    public function removeLabel($language)
    {
        if (is_string($language) && isset($this->labels[$language])) {
            unset($this->labels[$language]);
        }
    }

    /**
     * @param string $language
     *
     * @return string
     */
    public function getLabel($language)
    {
        if (isset($this->labels[$language])) {
            return $this->labels[$language];
        }

        return '';
    }

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

    /**
     * @param array $labels
     */
    public function setLabels(array $labels)
    {
        foreach ($labels as $language => $label) {
            $this->addLabel($language, $label);
        }
    }

    /**
     * @param string $language
     * @param string $description
     */
    public function addDescription($language, $description)
    {
        if (is_string($language) && is_string($description)) {
            $this->descriptions[$language] = $description;
        }
    }

    /**
     * @param string $language
     */
    public function removeDescription($language)
    {
        if (is_string($language) && isset($this->labels[$language])) {
            unset($this->labels[$language]);
        }
    }

    /**
     * @param string $language
     *
     * @return string
     */
    public function getDescription($language)
    {
        if (isset($this->descriptions[$language])) {
            return $this->descriptions[$language];
        }

        return '';
    }

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

    /**
     * @param array $descriptions
     */
    public function setDescriptions(array $descriptions)
    {
        foreach ($descriptions as $language => $description) {
            $this->addDescription($language, $description);
        }
    }

    /**
     * @param WorkflowTransitionInterface $transition
     */
    public function addTransition(WorkflowTransitionInterface $transition)
    {
        $this->transitions->add($transition);
    }

    public function setTransitions(array $transitions) {
        $this->transitions = $transitions;
    }

    /**
     * @param StatusInterface $fromStatus
     * @param StatusInterface $toStatus
     *
     * @return boolean
     */
    public function hasTransition(StatusInterface $fromStatus, StatusInterface $toStatus)
    {
        foreach ($this->transitions as $transition) {
            if ($transition->getStatusFrom()->getId() === $fromStatus->getId()
                && $transition->getStatusTo()->getId() === $toStatus->getId()
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function getTransitions()
    {
        return $this->transitions;
    }

    /**
     * Initialize collections
     */
    protected function initCollections() {
        $this->transitions = new ArrayCollection();
    }
}


<?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\Core;

use ItePHP\Provider\Session;
use Pactum\ConfigContainer;

/**
 * Provider for request.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class EmptyRequest implements Request{

	/**
	 *
	 * @var string[]
	 */
	private $data=[];

	/**
	 *
     * @var string[]
	 */
	private $query=[];

	/**
	 *
	 * @var Session
	 */
	private $session;

	/**
	 *
	 * @var mixed[]
	 */
	private $arguments=[];

	/**
	 *
	 * @var string
	 */
	private $url;

	/**
	 *
	 * @var string[]
	 */
	private $headers=[];

	/**
	 *
	 * @var string
	 */
	private $clientIp;

	/**
	 *
	 * @var mixed[]
	 */
	private $files=[];

	/**
	 *
	 * @var ConfigContainer
	 */
	private $config;

    /**
     * {@inheritdoc}
     */
	public function getFile($name){
		if(!isset($this->files[$name])){
			throw new FileNotUploadedException($name);
		}

		return $this->files[$name];
	}

    /**
     * {@inheritdoc}
     */
	public function getUrl(){
		return $this->url;
	}

    /**
     * {@inheritdoc}
     */
	public function getType(){
		return $_SERVER['REQUEST_METHOD'];
	}

    /**
     * {@inheritdoc}
     */
	public function getHeader($name){
		if(!isset($this->headers[strtolower($name)])){
			throw new HeaderNotFoundException($name);
		}

		return $this->headers[strtolower($name)];
	}

    /**
     * {@inheritdoc}
     */
	public function getBody(){
		return file_get_contents('php://input');
	}

    /**
     * {@inheritdoc}
     */
	public function setArgument($name,$value){
		$this->arguments[$name]=$value;
	}

    /**
     * {@inheritdoc}
     */
	public function getArguments(){
		return $this->arguments;
	}

    /**
     * {@inheritdoc}
     */
	public function removeArgument($name){
		unset($this->arguments[$name]);
	}

    /**
     * {@inheritdoc}
     */
	public function getSession(){
		return $this->session;
	}

    /**
     * {@inheritdoc}
     */
	public function getConfig(){
		return $this->config;
	}

    /**
     * {@inheritdoc}
     */
	public function setConfig(ConfigContainer $config){
		$this->config=$config;
	}

    /**
     * {@inheritdoc}
     */
	public function getData(){
		return $this->data;
	}

    /**
     * {@inheritdoc}
     */
	public function getQuery(){
		return $this->query;
	}

    /**
     * {@inheritdoc}
     */
	public function getHost(){
		return $_SERVER['HTTP_HOST'];
	}

    /**
     * {@inheritdoc}
     */
	public function getProtocol(){
		return $_SERVER['SERVER_PROTOCOL'];
	}

    /**
     * {@inheritdoc}
     */
	public function isSSL(){
		return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
			&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL'])
			&& $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') || (isset($_SERVER['HTTP_X_SSL_CIPHER'])));
	}

    /**
     * {@inheritdoc}
     */
	public function isAjax(){
		try{
			return strtolower($this->getHeader('x-requested-with'))=='xmlhttprequest';
		}
		catch(HeaderNotFoundException $e){
			return false;
		}

	}

    /**
     * {@inheritdoc}
     */
	public function getClientIp(){
		return $this->clientIp;
	}

    /**
     * {@inheritdoc}
     */
	public function isFullUploadedData(){
	    return true;
	}

}


<?php

/**
 * {@inheritdoc}
 */
class Benri_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    /**
     * Initialize rest routes.
     */
    protected function _initRestRoute()
    {
        $front = Zend_Controller_Front::getInstance();
        $front->setResponse(new Benri_Controller_Response_Http());
        $front->setRequest(new Benri_Controller_Request_Http());

        $front->getRouter()->addRoute('benri-app', new Zend_Rest_Route($front));
    }

    /**
     * Initialize the database resource.
     */
    protected function _initDbResource()
    {
        $registry = $this->getPluginResource('db');
        if (!$registry) {
            return;
        }

        //
        // options in configs/application
        $options = $registry->getOptions();

        if (array_key_exists('dsn', $options) && '' !== $options['dsn']) {
            $options['params'] = array_replace(
                $options['params'],
                $this->_parseDsn($options['dsn'])
            );
        }

        $registry->setOptions($options);
    }

    /**
     * Initialize multidb resources.
     */
    protected function _initMultiDbResources()
    {
        $registry = $this->getPluginResource('multidb');
        if (!$registry) {
            return;
        }

        //
        // options in configs/application
        $options = $registry->getOptions();

        foreach ($options as &$connection) {
            if ('db://' === substr($connection['dbname'], 0, 5)) {
                $connection = array_replace(
                    $connection,
                    $this->_parseDsn($connection['dbname'])
                );
            }
        }

        Zend_Registry::set('multidb', $registry->setOptions($options));
    }

    /**
     * Parse a DSN string and return return its components.
     *
     * If you want to use DSN, you **must** provide a valid AND complete DSN.
     *
     * Also, you are responsible to set both adapter and charset options, so
     * a valid DSN would looks something like this (DSNs MUST begin with `db://`):
     *      db://root:root@127.0.0.1/my_db or
     *      db://root:root@localhost/db_name
     *
     * @param string $dsn
     * @return array
     */
    private function _parseDsn($dsn)
    {
        $dsn = parse_url($dsn);
        $cfg = [];

        //
        // Some drivers (a.k.a. PDO_PGSQL) complains if the port is set
        // without a value, even NULL
        if (isset($dsn['port'])) {
            $cfg['port'] = $dsn['port'];
        }

        return $cfg + [
            'dbname'    => isset($dsn['path']) ? trim($dsn['path'], '/') : null,
            'host'      => isset($dsn['host']) ? $dsn['host']            : null,
            'password'  => isset($dsn['pass']) ? $dsn['pass']            : null,
            'username'  => isset($dsn['user']) ? $dsn['user']            : null,
        ];
    }
}


<?php

namespace ebussola\common\datatype\datetime;

/**
 * Author: Leonardo Shinagawa
 * Date: 12/04/12
 * Time: 17:32
 */
class OrderedList implements \Iterator, \Countable, \ArrayAccess
{

    /**
     * @var Array
     * [Date, Mixed][]
     */
    private $storage = array();

    /**
     * @var int
     */
    private $pointer = 0;

    /**
     * @var bool
     */
    private $isOrdered = false;

    /**
     * @param Date $date
     * @param mixed $data
     */
    public function add(Date $date, $data)
    {
        $this->offsetSet($date, $data);
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     */
    public function current()
    {
        if (!$this->isOrdered) {
            usort($this->storage, array($this, 'compare'));
            $this->isOrdered = true;
        }

        $data = $this->storage[$this->pointer][1];

        return $data;
    }

    private function compare($value1, $value2)
    {
        $date1 = $value1[0];
        $date2 = $value2[0];

        if ($date1 == $date2) {
            return 0;
        }

        return ($date1 > $date2) ? 1 : -1;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     */
    public function next()
    {
        $this->pointer++;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return String scalar on success, integer
     * 0 on failure.
     */
    public function key()
    {
        /** @var \ebussola\common\datatype\datetime\Date $date */
        $date = $this->storage[$this->pointer][0];
        return $date->format('Y-m-d');
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     */
    public function valid()
    {
        return isset($this->storage[$this->pointer]);
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     */
    public function rewind()
    {
        $this->pointer = 0;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Count elements of an object
     * @link http://php.net/manual/en/countable.count.php
     * @return int The custom count as an integer.
     *

     *

     * The return value is cast to an integer.
     */
    public function count()
    {
        return count($this->storage);
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Whether a offset exists
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset

     * An offset to check for.
     *

     * @return boolean Returns true on success or false on failure.
     *

     *

     * The return value will be casted to boolean if non-boolean was returned.
     */
    public function offsetExists($offset)
    {
        if (!$offset instanceof Date) {
            $offset = new Date($offset);
        }

        $item = $this->searchOffset($offset);
        return is_null($item) ? false : true;
    }

    private function searchOffset($offset)
    {
        foreach ($this->storage as $index => $item) {
            $date = array_values($item)[0];
            if ($date == $offset) {
                return $index;
            }
        }

        return null;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Offset to retrieve
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset

     * The offset to retrieve.
     *

     * @return mixed Can return all value types.
     */
    public function offsetGet($offset)
    {
        if (!$offset instanceof Date) {
            $offset = new Date($offset);
        }
        $value = $this->storage[$this->searchOffset($offset)][1];

        return $value;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Offset to set
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset

     * The offset to assign the value to.
     *

     * @param mixed $value

     * The value to set.
     *

     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (!$offset instanceof Date) {
            $offset = new Date($offset);
        }

        $index = $this->searchOffset($offset);
        if (is_null($index)) {
            $this->storage[] = array($offset, $value);
        } else {
            $this->storage[$index] = array($offset, $value);
        }

        $this->isOrdered = false;
    }

    /**
     * (PHP 5 >= 5.1.0)

     * Offset to unset
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset

     * The offset to unset.
     *

     * @return void
     */
    public function offsetUnset($offset)
    {
        if (!$offset instanceof Date) {
            $offset = new Date($offset);
        }

        $index = $this->searchOffset($offset);
        unset($this->storage[$index]);
    }

}


<?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\exceptions\Exception;
use Yii;

/**
 * Module [[@doctodo class_description:cascade\components\web\widgets\Module]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Module extends \cascade\components\base\CollectorModule
{
    /**
     * @var [[@doctodo var_type:title]] [[@doctodo var_description:title]]
     */
    public $title;
    /**
     * @var [[@doctodo var_type:icon]] [[@doctodo var_description:icon]]
     */
    public $icon = 'ic-icon-info';
    /**
     * @var [[@doctodo var_type:priority]] [[@doctodo var_description:priority]]
     */
    public $priority = 1000; //lower is better

    /**
     * @var [[@doctodo var_type:locations]] [[@doctodo var_description:locations]]
     */
    public $locations = []; //lower is better

    /**
     * @var [[@doctodo var_type:widgetNamespace]] [[@doctodo var_description:widgetNamespace]]
     */
    public $widgetNamespace;

    /**
     * @inheritdoc
     */
    public function getCollectorName()
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function getModuleType()
    {
        return 'Widget';
    }

    /**
     * [[@doctodo method_description:onAfterInit]].
     *
     * @param [[@doctodo param_type:event]] $event [[@doctodo param_description:event]]
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return [[@doctodo return_type:onAfterInit]] [[@doctodo return_description:onAfterInit]]
     *
     */
    public function onAfterInit($event)
    {
        if (isset(Yii::$app->collectors['widgets']) and !Yii::$app->collectors['widgets']->registerMultiple($this, $this->widgets())) {
            throw new Exception('Could not register widgets for ' . $this->systemId . '!');
        }

        return parent::onAfterInit($event);
    }

    /**
     * [[@doctodo method_description:widgets]].
     *
     * @return [[@doctodo return_type:widgets]] [[@doctodo return_description:widgets]]
     */
    public function widgets()
    {
        $widgets = [];
        $className = $this->widgetNamespace . '\\' . 'Content';
        @class_exists($className);
        if (class_exists($className, false)) {
            $summaryWidget = [];
            $id = $this->systemId . 'Content';
            $summaryWidget['widget'] = [
                'class' => $className,
                'icon' => $this->icon,
                'owner' => $this,
            ];
            $summaryWidget['locations'] = $this->locations;
            $summaryWidget['priority'] = $this->priority;
            $widgets[$id] = $summaryWidget;
        }
        //\d($widgets);exit;
        return $widgets;
    }

    /**
     * Get short name.
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return [[@doctodo return_type:getShortName]] [[@doctodo return_description:getShortName]]
     *
     */
    public function getShortName()
    {
        preg_match('/Widget([A-Za-z]+)\\\Module/', get_class($this), $matches);
        if (!isset($matches[1])) {
            throw new Exception(get_class($this) . " is not set up correctly!");
        }

        return $matches[1];
    }
}


<?php namespace ForeverPHP\Http;

use ForeverPHP\Session\SessionManager;

/**
 * Devuelve una respuesta de tipo de redireccion.
 *
 * @since 0.3.0
 */
class RedirectResponse implements ResponseInterface {
    /**
     * Ruta a la cual redireccionar.
     *
     * @var string
     */
    private $path;

    /**
     * Codigo de estado.
     *
     * @var integer
     */
    private $status;

    /**
     * Encabezados a incluir en la redireccion.
     *
     * @var array
     */
    private $headers;

    /**
     * Almacena la instancia unica del administrador de sesiones.
     *
     * @var \ForeverPHP\Session\SessionManager
     */
    private $session;

    public function __construct($path, $status, $headers) {
        $this->path = $path;
        $this->status = $status;
        $this->headers = $headers;

        // Obtiene la instancia del administrador de sesiones
        $this->session = SessionManager::getInstance();
    }

    public function with($key, $value = null) {
        if (is_array($key)) {
            foreach ($key as $k => $value) {
                $this->with($k, $value);
            }
        } elseif ($key instanceof \ForeverPHP\View\Context) {
            $this->with($key->all());
        } else {
            $this->session->set($key, $value, 'redirect');
        }

        return $this;
    }

    /**
     * Construye la redireccion
     *
     * @return void
     */
    public function make() {
        /*
         * Se guardan los headers si es que hay en la configuracion
         * para luego utilizarlos al construir la redireccion
         */
        if (count($this->headers) > 0) {
            if (!$this->session->exists('headersInRedirect', 'redirect') || !$this->session->get('headersInRedirect', 'redirect')) {
                $this->session->set('redirectPath', $this->path, 'redirect');
                $this->session->set('headersInRedirect', $this->headers, 'redirect');
            }
        }

        header("Location: $this->path");
        exit();
    }
}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular\Validation\Adapter;
use bigwhoop\Formular\Validation\ValidatorInterface;
use Zend\Validator\ValidatorInterface as Validator;
use Zend\Validator\ValidatorChain;
use Zend\Validator\NotEmpty;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
class ZendFrameworkAdapter implements ValidatorInterface
{
    /** @var string */
    private $label;

    /** @var Validator */
    private $validator;

    /** @var string */
    private $errorMessage = '';

    /** @var bool */
    private $allowEmpty = true;

    /**
     * @param string $label
     * @param Validator $validator   1st ...
     * @param Validator $validator   2nd ...
     * @param Validator $validator   3rd ...
     */
    public function __construct($label, Validator $validator)
    {
        $this->label = $label;

        $validatorChain = new ValidatorChain();
        foreach (array_slice(func_get_args(), 1) as $validator) {
            if ($validator instanceof NotEmpty) {
                $this->allowEmpty = false;
            }
            $validatorChain->attach($validator, true);
        }
        $this->validator = $validatorChain;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        if (($this->allowEmpty && empty($value)) || $this->validator->isValid($value)) {
            $this->errorMessage = '';
            return true;
        }
        $this->errorMessage = (empty($this->label) ? '' : "{$this->label}: ") . join(' / ', $this->validator->getMessages());
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }
}


<?php

namespace Jormin\DDoc\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;

class DDocController
{

    /**
     * 读取数据库信息
     */
    private function initTablesData()
    {
        //获取数据库表名称列表
        $tables = DB::select('SHOW TABLE STATUS ');
        foreach ($tables as $key => $table) {
            //获取改表的所有字段信息
            $columns = DB::select("SHOW FULL FIELDS FROM `".$table->Name."`");
            $table->columns = $columns;
            $tables[$key] = $table;
        }
        return $tables;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $tables = $this->initTablesData();
        return view('ddoc::index',compact('tables'));
    }

    /**
     * 导出文档
     *
     * @param $type
     */
    public function export($type)
    {
        if(!in_array($type,array('html','md'))){
            return null;
        }
        $tables = $this->initTablesData();
        $filename = config('app.name').'数据字典';
        switch($type){
            case 'html':
                $zippath = storage_path($filename.'.zip');
                $zip = new \ZipArchive;
                $res = $zip->open($zippath, \ZipArchive::CREATE);
                if ($res === TRUE) {
                    // 添加静态资源文件
                    $this->addFileToZip('vendor/laravel-ddoc',$zip);
                    // 生成Html文件
                    require_once (__DIR__.'/../Lib/simple_html_dom.php');
                    $obj = View::make('ddoc::index', compact('tables'),array())->render();
                    $protocol = 'http://';
                    if(Request::secure()){
                        $protocol = 'https://';
                    }
                    $obj = str_replace($protocol.$_SERVER['HTTP_HOST'].'/vendor/laravel-ddoc','.',$obj);
                    $html = new \simple_html_dom();
                    $html->load($obj);
                    $html->find('div[class=export-wrap]',0)->outertext = '';
                    $zip->addFromString($filename.'.html', $html);
                    $zip->close();
                } else {
                    return null;
                }

                $response =  new Response(file_get_contents($zippath), 200, array(
                    'Content-Type' => 'application/zip',
                    'Content-Disposition' =>  'attachment; filename="'.$filename.'.zip"'
                ));
                unlink($zippath);
                return $response;
                break;
            case 'pdf':
                $filename .= '.pdf';
                $pdf = SnappyPdf::loadView('ddoc::index', compact('tables'));
                return $pdf->download($filename);
                break;
            case 'md':
                $filename .= '.md';
                $content = $this->getMdContent();
                $response =  new Response($content, 200, array(
                    'Content-Type' => 'application/octet-stream',
                    'Accept-Length' => strlen($content),
                    'Content-Disposition' =>  'attachment; filename="'.$filename
                ));

                return $response;
        }
    }

    /**
     * 添加文件夹
     *
     * @param $path
     * @param $zip
     */
    private function addFileToZip($path, $zip) {
        $handler = opendir(public_path($path));
        while (($filename = readdir($handler)) !== false) {
            if (!in_array($filename,array('.','..','.DS_Store'))) {
                if (is_dir($path . "/" . $filename)) {
                    $this->addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $fullname = public_path($path) . "/" . $filename;
                    $localname = str_replace('vendor/laravel-ddoc/','','/'.$path.'/'.$filename);
                    $zip->addFile($fullname,$localname);
                }
            }
        }
        @closedir($path);
    }

    /**
     * md 内容
     *
     * @param $table
     */
    private function getMdContent()
    {
        $tables = $this->initTablesData();
        $content = "## 数据字典\n";
        foreach ($tables as $table){
            $content .= $this->tableName($table);
        }
        $content .= "\n";
        foreach ($tables as $key => $table){
            $content .= $this->tableDetail($key, $table);
        }
        return $content;
    }

    /**
     * 数据库 表名字
     *
     * @param $table
     */
    private function tableName($table)
    {
        $content = "* [".$table->Name."](#".$table->Name.")\n";
        return $content;
    }

    /**
     *数据库 详情
     *
     * @param $key
     * @param $table
     */
    private function tableDetail($key, $table)
    {
        $content = "\n\n-------------------\n\n";
        $content .= "<h3 id='".$table->Name."'>".($key+1).". ".$table->Name."<h3>\n";
		$table->Comment && $content .= '> '.$table->Comment."\n";
        $content .= "|字段|类型|为空|键|默认值|特性|备注|\n|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n";
        foreach ($table->columns as $column){
            $content .= "|".$column->Field."|".$column->Type."|".$column->Null."|".$column->Key."|".$column->Default."|".$column->Extra."|".$column->Comment."|\n";
        }
        return $content;
    }
}


<?php
/**
 * This file contains the JavaXmlPropertiesUtils class.
 */

namespace Mbcraft\Piol\Utils;

use Mbcraft\Piol\PiolObject;
use Mbcraft\Piol\File;

/**
 * This class has static methods for handling java xml properties.
 */
class JavaXmlPropertiesUtils extends PiolObject {

    const XML_PRELUDE = <<<'END_XML_PRELUDE'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties
  SYSTEM "http://java.sun.com/dtd/properties.dtd">
END_XML_PRELUDE;

    const XML_ROOT_OPEN = <<<'TAG'
<properties>
TAG;

    const XML_ROOT_CLOSE = <<<'TAG'
</properties>
TAG;

    /**
     * Adds entries to a java xml properties file.
     *
     * @param mixed $file a path or a File
     * @param array $entries
     *
     * @api
     */
    public static function addEntriesToFile($file, $entries) {
        $properties = self::readFromFile($file);
        foreach ($entries as $key => $value) {
            $properties[$key] = $value;
        }

        self::saveToFile($file, $properties);
    }

    /**
     * Removes entries to a java xml properties file.
     *
     * @param mixed $file a path or a File
     * @param array $entries The entries to remove.
     *
     * @api
     */
    public static function removeEntriesFromFile($file, $entries) {
        $properties = self::readFromFile($file);
        if (is_string($entries)) {
            unset($properties[$entries]);
        } else {
            foreach ($entries as $i => $key) {
                unset($properties[$key]);
            }
        }
        self::saveToFile($file, $properties);
    }

    /**
     * Reads the properties from a string.
     *
     * @param string $string The string, in xml java properties format.
     *
     * @return array The properties array
     *
     * @api
     */
    public static function readFromString($string) {

        $xml = new \DOMDocument();
        $xml->loadXML($string);

        $result = [];

        $props = $xml->childNodes->item($xml->childNodes->length-1)->childNodes;

        for ($i=0; $i<$props->length;$i++) {
            $entry = $props->item($i);
            if ($entry->nodeName=="entry")
                $result[$entry->attributes->getNamedItem("key")->nodeValue] = $entry->textContent;
        }

        return $result;
    }

    /**
     * Reads the properties from a file, in xml java properties format.
     *
     * @param mixed $file a path or a File
     *
     * @return array The properties array
     *
     * @api
     */
    public static function readFromFile($file) {
        $real_file = File::asFile($file);

        if ($real_file->exists())
            return self::readFromString($file->getContent());
        else
            return array();
    }

    /**
     * Saves the properties to a string.
     *
     * @param array $properties The properties, as an array.
     *
     * @return string the string containing the properties in xml java properties format.
     *
     * @api
     */
    public static function saveToString($properties) {
        $xn = new \SimpleXMLElement(self::XML_ROOT_OPEN.self::XML_ROOT_CLOSE,LIBXML_NOXMLDECL);

        foreach ($properties as $key => $value) {
            $xn->addChild("entry", htmlspecialchars($value,ENT_XML1))->addAttribute("key",htmlspecialchars($key,ENT_XML1));
        }
        //LIBXML_NOXMLDECL is not supported, so replace the xml declaration to include also the dtd
        return preg_replace('/\<\?.*\?\>/', self::XML_PRELUDE, $xn->asXML());

    }

    /**
     * Saves the properties to file.
     *
     * @param mixed  $file a path or a File
     * @param array $properties The properties, as an array.
     *
     * @api
     */
    public static function saveToFile($file, $properties) {
        $prop_string = self::saveToString($properties);

        $real_file = File::asFile($file);

        if (!$real_file->exists()) {
            $real_file->touch();
        }
        $real_file->setContent($prop_string);
    }

}


<?php
/**
 * This file is part of Formular.
 *
 * (c) Philippe Gerber
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace bigwhoop\Formular;
use bigwhoop\Formular\Element\ElementCollection;
use bigwhoop\Formular\Element\ElementInterface;
use bigwhoop\Formular\Element\Element;
use bigwhoop\Formular\Element\ElementQueue;
use bigwhoop\Formular\Filtering\CallbackFilter;
use bigwhoop\Formular\Filtering\FilterInterface;
use bigwhoop\Formular\TemplateFactory\TemplateFactoryInterface;
use bigwhoop\Formular\Validation\CallbackValidator;
use bigwhoop\Formular\Validation\ValidatorInterface;

/**
 * @author Philippe Gerber <philippe@bigwhoop.ch>
 */
class Form
{
    /** @var array */
    static protected $defaultOptions = [];

    /** @var array */
    protected $options = [];

    /** @var ElementCollection */
    private $elements = null;

    /** @var ElementQueue|null */
    private $renderQueue = null;

    /** @var TemplateFactoryInterface|null */
    private $templateFactory = null;

    /** @var FilterInterface[] */
    private $filters = [];

    /** @var ValidatorInterface[] */
    private $validators = [];

    /** @var array */
    private $errorMessages = [];

    /**
     * @param array $options
     */
    static public function setDefaultOptions(array $options)
    {
        static::$defaultOptions = $options;
    }

    /**
     * Constructor
     */
    public function __construct(array $options = [])
    {
        $this->options = $options + static::$defaultOptions;
        $this->elements = new ElementCollection();
        $this->init();
    }

    /**
     * Can be implemented by subclasses.
     */
    public function init()
    {
        // ...
    }

    /**
     * @param TemplateFactoryInterface $locator
     * @return $this
     */
    public function setTemplateFactory(TemplateFactoryInterface $locator)
    {
        $this->templateFactory = $locator;
        return $this;
    }

    /**
     * @return TemplateFactoryInterface|null
     */
    public function getTemplateFactory()
    {
        return $this->templateFactory;
    }

    /**
     * @return $this
     */
    public function clearElements()
    {
        $this->elements->reset();
        $this->resetRenderQueue();
        return $this;
    }

    /**
     * @param ElementInterface|string $template
     * @param array $attributes
     * @return $this
     */
    public function addElement($template, array $attributes = [])
    {
        if (!$template instanceof ElementInterface) {
            $template = new Element($template, $attributes);
        }
        $this->elements->addElement($template);
        return $this;
    }

    /**
     * @param string $id
     * @param mixed $default
     * @return mixed
     * @throws \OutOfBoundsException        If the element does not exist.
     */
    public function getElementValueByID($id, $default = null)
    {
        try {
            return $this->elements->getElementByID($id)->getValue($default);
        } catch (\OutOfBoundsException $e) {
            throw $e;
        }
    }

    /**
     * @param array $filters
     * @return $this
     */
    public function setFilters(array $filters)
    {
        $this->filters = [];
        foreach ($filters as $scope => $filter) {
            $this->setFilter($scope, $filter);
        }
        return $this;
    }

    /**
     * @param string $scope
     * @param callable|FilterInterface $filter
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setFilter($scope, $filter)
    {
        if (!is_string($scope)) {
            throw new \InvalidArgumentException("Scope must be string.");
        }
        if (!is_callable($filter) && !$filter instanceof FilterInterface) {
            throw new \InvalidArgumentException("Filter must be a callable or an instance of FilterInterface.");
        }
        if (!$filter instanceof FilterInterface) {
            $filter = new CallbackFilter($filter);
        }
        $this->filters[$scope] = $filter;
        return $this;
    }

    /**
     * @param array $validators
     * @return $this
     */
    public function setValidators(array $validators)
    {
        $this->validators = [];
        foreach ($validators as $scope => $validator) {
            $this->setValidator($scope, $validator);
        }
        return $this;
    }

    /**
     * @param string $scope
     * @param callable|ValidatorInterface $validator
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setValidator($scope, $validator)
    {
        if (!is_string($scope)) {
            throw new \InvalidArgumentException("Scope must be string.");
        }
        if (!is_callable($validator) && !$validator instanceof ValidatorInterface) {
            throw new \InvalidArgumentException("Validator must be a callable or an instance of ValidatorInterface.");
        }
        if (!$validator instanceof ValidatorInterface) {
            $validator = new CallbackValidator($validator, 'Value %VALUE% is not valid.');
        }
        $this->validators[$scope] = $validator;
        return $this;
    }

    /**
     * @param mixed|callable $value
     * @return callable
     */
    public function bindValue($value)
    {
        // Bind callable
        if (is_callable($value)) {
            return $value;
        }

        // Bind object property
        if (is_array($value) && count($value) == 2 && is_object($value[0]) && is_string($value[1]) && property_exists($value[0], $value[1])) {
            return function() use ($value) {
                return $value[0]->$value[1];
            };
        }

        // Bind everything else
        return function() use ($value) {
            return $value;
        };
    }

    /**
     * @param mixed $var
     * @return callable
     */
    public function bindVariable(&$var)
    {
        return function() use (&$var) {
            return $var;
        };
    }

    /**
     * Just call render() again to continue rendering of the form. All the elements
     * are in a queue and we can just continue to dequeue the next element.
     *
     * @return callable
     */
    public function bindContinue()
    {
        return $this->bindValue(function() {
            return $this->render();
        });
    }

    /**
     * @return callable
     */
    public function bindErrorMessages()
    {
        return $this->bindValue(function() {
            return $this->getErrorMessages();
        });
    }

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

    /**
     * @return string
     */
    public function render()
    {
        if ($this->renderQueue === null) {
            $this->renderQueue = ElementQueue::createFromCollection($this->elements);
        }

        $out = '';
        while (count($this->renderQueue) > 0) {
            $element = $this->renderQueue->dequeue();
            $out .= $this->renderElement($element);
        }
        return $out;
    }

    /**
     * @param ElementInterface $element
     * @return string
     * @throws \LogicException
     */
    private function renderElement(ElementInterface $element)
    {
        $factory = $this->getTemplateFactory();
        if (!$factory) {
            throw new \LogicException("A template factory must be set to render elements.");
        }
        $template = $factory->createTemplate($element->getTemplateName());
        return $template->render($element->getAttributes());
    }

    /**
     * Validates all the elements against the defined validators.
     *
     * During validation the given values will be set as the new values of the elements.
     *
     * @param array $values
     * @return bool
     */
    public function isValid(array $values)
    {
        $this->errorMessages = [];

        foreach ($this->elements->getElements() as $element) {
            $elementId = $element->getID();
            if (empty($elementId)) {
                continue;
            }

            $value = null;
            if (array_key_exists($elementId, $values)) {
                $value = $values[$elementId];
            }
            $element->setValue($value);

            $this->filterElement($element);
            $this->validateElement($element);
        }

        return count($this->errorMessages) === 0;
    }

    /**
     * Applies all defined filters to an element's value
     *
     * @param ElementInterface $element
     */
    private function filterElement(ElementInterface $element)
    {
        $value = $element->getValue();
        foreach ($this->filters as $scope => $filter) {
            $elementIds = array_map('trim', explode(',', $scope));
            if ($scope === '*' || in_array($element->getID(), $elementIds)) {
                $value = $filter->filter($value);
            }
        }
        $element->setValue($value);
    }

    /**
     * @param ElementInterface $element
     */
    private function validateElement(ElementInterface $element)
    {
        foreach ($this->validators as $scope => $validator) {
            $elementIds = array_map('trim', explode(',', $scope));
            if ($scope === '*' || in_array($element->getID(), $elementIds)) {
                if (!$validator->isValid($element->getValue())) {
                    $this->errorMessages[] = $validator->getErrorMessage();
                }
            }
        }
    }

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


<?php

namespace Versatile\Search;

use Versatile\Search\Contracts\Criteria as CriteriaContract;
use Versatile\Search\Contracts\Queryable;
use Versatile\Search\Contracts\Sortable;
use Versatile\Search\Contracts\Filter as FilterContract;
use Versatile\Query\Builder;

trait ProvidesKeyInterface
{

    protected $keys = [];

    /**
     * Adds a key or many keys (columns) to the result.
     * Pass an array of keys or just one key or multiple (string) arguments
     *
     * @param array|string $key
     * @return self
     **/
    public function withKey($key)
    {
        $keys = func_num_args() > 1 ? func_get_args() : (array)$key;

        foreach ($keys as $key) {
            $this->keys[] = $key;
        }

        return $this;
    }

    /**
     * Returns all assigned keys (columns)
     *
     * @return array
     **/
    public function keys()
    {
        return $this->keys;
    }

    /**
     * Clears a key or many keys (columns). Pass a single key, an array of keys
     * or multiple (string) arguments
     *
     * @param array|string $key
     * @return self
     **/
    public function clearKey($key)
    {
        $keys = func_num_args() > 1 ? func_get_args() : (array)$key;

        foreach ($keys as $key) {
            $idx = array_search($key, $this->keys);
            if ($idx !== false) {
                unset($this->keys[$idx]);
            }
        }

        $this->keys = array_values($this->keys);
        return $this;

    }

    /**
     * Clears all keys and replaces em
     *
     * @return self
     **/
    public function replaceKeys($keys)
    {
        $this->keys = [];
        call_user_func_array([$this, 'withKey'], func_get_args());
        return $this;
    }

}


<?php
namespace eMacros\Runtime\Regex;

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

class RegexReplaceCallback implements Applicable {
	/**
	 * Replaces all matches specified by a pattern on a given subject
	 * Usage: see RegexPackageTest class
	 * Returns: array | string
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$nargs = count($arguments);
		if ($nargs < 3) throw new \BadFunctionCallException("RegexReplaceCallback: Function expects at least 3 parameters.");
		$args = [];

		for ($i = 0; $i < $nargs; $i++) {
			if ($i == 4) break;
			$args[] = $arguments[$i]->evaluate($scope);
		}

		if (!is_callable($args[1])) throw new \InvalidArgumentException("RegexReplaceCallback: Second parameter is not a valid callback.");
		if ($nargs < 4) return call_user_func_array('preg_replace_callback', $args);
		else {
			$target = $arguments[4];
			if (!($target instanceof Symbol))
				throw new \InvalidArgumentException(sprintf("RegexReplaceCallback: Expected symbol as fourth parameter but %s was found instead.", substr(strtolower(strstr(get_class($arguments[4]), '\\')), 1)));
			$ref = $target->symbol;
			$result = preg_replace_callback($args[0], $args[1], $args[2], $args[3], $count);
			$scope->symbols[$ref] = $count;
			return $result;
		}
	}
}
?>


<?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\Page;

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

/**
 * Class RemovePageAction defines the object assigned to remove a page from the website
 *
 * @package RedKiteCms\Action
 */
class RemovePageAction extends BaseAction
{
    /**
     * {@inheritdoc}
     */
    public function execute(array $options, $username)
    {
        $values = $options["data"];
        $pageManager = $this->app["red_kite_cms.page_collection_manager"];
        $pageManager
            ->contributor($username)
            ->remove($values["name"])
        ;
    }
}


<?php

/**
 * Manage Asset
 *
 * @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;

/**
 * This class manage the Asset
 *
 * @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
 *
 * @tutorial	$oAsset = new \Venus\lib\Asset;
 * 				$oAsset->stylesheets(array('css/style.css'));
 */
class Asset
{
	/**
	 * get URL of your javascripts
	 *
	 * @access public
	 * @return array
	 * @internal param array $aJavascript [many can be passed]
	 */
	public function javascripts() : array {

	    $sDefaultPath = 'http://'.$_SERVER['HTTP_HOST'].'/getJs?';
	    $aJavascript = func_get_args();
	    $aReturns = array();

	    foreach($aJavascript as $aJsCombination) {

	        $sJsPath = $sDefaultPath;

	        foreach ($aJsCombination as $sJsToAdd) {

	            $sJsPath = $sJsToAdd.'&';
	        }

    	    if (defined('ASSET_VERSION') && ASSET_VERSION) {

    	        $sJsPath = ASSET_VERSION;
    	    }

	        $aReturns[] = $sJsPath;
	    }

	    return $aReturns;
	}

	/**
	 * get URL of your javascripts
	 *
	 * @access public
	 * @return array
	 * @internal param array $aCss [many can be passed]
	 *
	 * @tutoriel
	 */
	public function stylesheets() : array {

	    $sDefaultPath = 'http://'.$_SERVER['HTTP_HOST'].'/getCss?';
	    $aCss = func_get_args();
	    $aReturns = array();

	    foreach($aCss as $aCssCombination) {

	        $sCssPath = $sDefaultPath;

	        foreach ($aCssCombination as $sCssToAdd) {

	            $sCssPath = $sCssToAdd.'&';
	        }

    	    if (defined('ASSET_VERSION') && ASSET_VERSION) {

                $sCssPath = ASSET_VERSION;
    	    }

	        $aReturns[] = $sCssPath;
	    }

	    return $aReturns;
	}
}


<?php
namespace Poirot\Queue\Queue;

use Predis;

use Poirot\Queue\Exception\exIOError;
use Poirot\Queue\Exception\exReadError;
use Poirot\Queue\Exception\exWriteError;
use Poirot\Queue\Exception\NotImplementedException;
use Poirot\Queue\Interfaces\iPayload;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Queue\Payload\QueuedPayload;
use Poirot\Storage\Interchange\SerializeInterchange;

class RedisQueue implements iQueueDriver
{

    const QUEUE_PREFIX = "queue.";
    const DEFAULT_QUEUE_NAME = "general";
    const WIP_QUEUE_PREFIX = "wip_queue.";

    /** @var  Predis\Client */
    protected $client;

    /** @var SerializeInterchange */
    protected $_c_interchangable;

    /**
     * MongoQueue constructor.
     *
     * @param Predis\Client $client
     */
    function __construct(Predis\Client $client)
    {
        $this->client = $client;
    }

    /**
     * Push To Queue
     *
     * @param iPayload $payload Serializable payload
     * @param string $queue
     *
     * @return iPayloadQueued
     * @throws exIOError
     */
    function push($payload, $queue = null)
    {
        $payload  = $payload->getData();

        $uid = ($payload instanceof iPayloadQueued)
            ? $payload->getUID()
            : \Poirot\Std\generateUniqueIdentifier(24);

        if ($queue === null && $payload instanceof iPayloadQueued)
            $queue = $payload->getQueue();

        $qName = $this->_normalizeQueueName($queue);

        $time = ($payload instanceof iPayloadQueued)
            ? $time = $payload->getCreatedTimestamp()
            : time();

        $value = $this->_interchangeable()
            ->makeForward([
                'id'                => $uid,
                'payload'           => $payload,
                'created_timestamp' => $time,
        ]);

        try
        {
            $this->client->lpush($qName, $value);
        } catch (\Exception $e)
        {
            throw new exWriteError('Error While Writing To Redis Client.', $e->getCode(), $e);
        }

        $queued = new QueuedPayload($payload);
        $queued = $queued
            ->withUID($uid)
            ->withQueue($qName);

        return $queued;
    }

    /**
     * Pop From Queue
     *
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function pop($queue = null)
    {
        $queueName = $this->_normalizeQueueName($queue);

        $rpop = null;
        try
        {
            $rpop = $this->client->rpop($queueName);
        } catch(\Exception $e) {
            throw new exReadError('Error While Reading From Redis Client.', $e->getCode(), $e);
        }

        if (empty($rpop))
        {
            return null;
        }

        $rpopArray = (array) $this->_interchangeable()->retrieveBackward($rpop);

        try
        {
            $this->client->hset($this->_getWIPQueueName($queue), $rpopArray['id'], $rpop);
        } catch (\Exception $e)
        {
            throw new exWriteError('Error While Writing To Redis Client.', $e->getCode(), $e);
        }

        $payload = $rpopArray['payload'];
        $payload = new QueuedPayload($payload);
        $payload = $payload->withQueue($queue)
            ->withUID( (string) $rpopArray['id'] );

        return $payload;
    }

    /**
     * Release an Specific From Queue By Removing It
     *
     * @param iPayloadQueued|string $id
     * @param null|string $queue
     *
     * @return void
     * @throws exIOError
     */
    function release($id, $queue = null)
    {
        if ( $id instanceof iPayloadQueued )
        {
            $arg   = $id;
            $id    = $arg->getUID();
            $queue = $arg->getQueue();
        }

        try
        {
            $this->client->hdel($this->_getWIPQueueName($queue), $id);
        } catch (\Exception $e) {
            throw new exWriteError('Error While Writing To Redis Client.', $e->getCode(), $e);
        }
    }

    /**
     * Find Queued Payload By Given ID
     *
     * @param string $id
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function findByID($id, $queue = null)
    {
        throw new NotImplementedException("For God's sake, Cannot Implement this feature in Redis!");
    }

    /**
     * Get Queue Size
     *
     * @param string $queue
     *
     * @return int
     * @throws exIOError
     */
    function size($queue = null)
    {
        $count = 0;

        try {
            $count = $this->client->llen($this->_normalizeQueueName($queue));
        } catch (\Exception $e) {
            throw new exReadError('Error While Reading From Redis Client.', $e->getCode(), $e);
        }

        return $count;
    }

    /**
     * Get Queues List
     *
     * @return string[]
     * @throws exIOError
     */
    function listQueues()
    {
        try {
            return $this->client->keys(self::QUEUE_PREFIX . "*");
        } catch (\Exception $e) {
            throw new exReadError('Error While Reading From Redis Client.', $e->getCode(), $e);
        }
    }

    /**
     * @param string $queue
     * @return string
     */
    protected function _normalizeQueueName($queue)
    {
        if ($queue === null)
        {

            return self::QUEUE_PREFIX.self::DEFAULT_QUEUE_NAME;
        }

        return \strtolower( self::QUEUE_PREFIX . (string) $queue );
    }

    /**
     * @param string $queue
     * @return string
     */
    protected function _getWIPQueueName($queue)
    {
        if ($queue === null)
        {
            $queue = self::DEFAULT_QUEUE_NAME;
        }
        return \strtolower( self::WIP_QUEUE_PREFIX . (string) $queue );
    }

    /**
     * @return SerializeInterchange
     */
    protected function _interchangeable()
    {
        if (! $this->_c_interchangable)
            $this->_c_interchangable = new SerializeInterchange;

        return $this->_c_interchangable;
    }

}


<?php

namespace Ken\View\TwigEngine;

use Ken\Base\Buildable;
use Ken\Helper\Url;

/**
 * This class is used to add simple function to Twig Template Engine.
 * Extends this class to add custom function.
 */
class FunctionGenerator implements Buildable
{
    protected $functionList = [];

    private function __construct()
    {
        $this->addDefaultFunction();
        $this->addCustomFunction();
    }

    /**
     * {@inheritdoc}
     */
    public static function build(array $config = array())
    {
        return new static();
    }

    /**
     * Adds function to twig engine.
     *
     * @param string   $functionName Function name to be called from template file
     * @param callable $callback     Callback function to be called
     */
    public function addFunction($functionName, $callback)
    {
        if (is_string($functionName) && is_callable($callback)) {
            $functions = [
                'name' => $functionName,
                'callable' => $callback,
            ];

            array_push($this->functionList, $functions);
        }
    }

    /**
     * Retrieves function list.
     *
     * @return array
     */
    public function getFunctionList()
    {
        return $this->functionList;
    }

    /**
     * Adds default function for twig template.
     */
    private function addDefaultFunction()
    {
        $this->addFunction('app', function () {
            return app();
        });

        $this->addFunction('url', function ($url, $absolute = false, array $params = array()) {
            if ($absolute) {
                return Url::createAbsolute($url, $params);
            } else {
                return Url::create($url, $params);
            }
        });

        $this->addFunction('assets', function ($path) {
            return Url::createAbsolute($path);
        });
    }

    /**
     * Adds custom function for Twig Template Engine.
     * You must extends this method to add your custom function.
     */
    protected function addCustomFunction()
    {
        // ADD YOUR CUSTOM FUNCTION HERE
    }
}


<?php

namespace Bavix\SDK;

use Bavix\Exceptions\NotFound;
use Bavix\Exceptions;
use Bavix\Helpers\Arr;
use Bavix\Helpers\File;
use Bavix\Helpers\PregMatch;

class FileLoader
{

    /**
     * @var array
     */
    protected static $extensions = [
        'php'  => FileLoader\PHPLoader::class,
        'yml'  => FileLoader\YamlLoader::class,
        'yaml' => FileLoader\YamlLoader::class,
        'json' => FileLoader\JSONLoader::class,
        'xml'  => FileLoader\XmlLoader::class,
        'ini'  => FileLoader\IniLoader::class,
    ];

    /**
     * @return array
     * @codeCoverageIgnore
     */
    public static function extensions()
    {
        return Arr::getKeys(static::$extensions);
    }

    /**
     * @param string $file
     *
     * @return FileLoader\DataInterface
     *
     * @throws NotFound\Path
     * @throws Exceptions\PermissionDenied
     */
    public static function load($file)
    {
        if (!File::isFile($file))
        {
            throw new NotFound\Path($file);
        }

        if (!File::isReadable($file))
        {
            throw new Exceptions\PermissionDenied($file);
        }

        $preg = PregMatch::first('~\.(?<ext>\w+)$~', $file);

        $class = Arr::get(
            static::$extensions,
            Arr::get($preg->matches, 'ext', 'php'),
            static::$extensions['php']
        );

        return new $class($file);
    }

}


<?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\Bridge\Routing;

use RedKiteCms\Bridge\Routing\RoutingGenerator;
use RedKiteCms\Configuration\ConfigurationHandler;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Router;

/**
 * This object instantiates a new routing for the frontend environment
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Routing
 */
class RoutingFrontend extends RoutingBase
{
    /**
     * {@inheritdoc}
     */
    protected $routesFile = 'routes-frontend.yml';

    /**
     * {@inheritdoc}
     */
    public function generateWebsiteRoutes(RoutingGenerator $routingGenerator, $user = null)
    {
        $routingGenerator
            ->pattern('/')
            ->frontController('Controller\Cms\FrontendController::showAction')
            ->explicitHomepageRoute(true)
            ->generate($this->router)
        ;
    }
}


<?php
/**
 * Jaeger
 *
 * @copyright	Copyright (c) 2015-2016, mithra62
 * @link		http://jaeger-app.com
 * @version		1.0
 * @filesource 	./Remote/Sftp.php
 */
namespace JaegerApp\Remote;

use League\Flysystem\Sftp\SftpAdapter as Adapter;
use RuntimeException;
use JaegerApp\Remote\Sftp as m62Sftp;

/**
 * Jaeger - SFTP Transfer Abstraction
 *
 * Simple intermediary between Flysystem and JaegerApp
 *
 * @package Remote
 * @author Eric Lamb <eric@mithra62.com>
 */
class Sftp extends Adapter
{

    /**
     * (non-PHPdoc)
     *
     * @see \League\Flysystem\Adapter\Ftp::connect()
     */
    public function connect()
    {
        @parent::connect();
    }

    /**
     * (non-PHPdoc)
     *
     * @see \League\Flysystem\Adapter\Ftp::getMetadata()
     */

    /**
     *
     * @ignore (non-PHPdoc)
     * @see \League\Flysystem\Adapter\Ftp::getMetadata()
     */
    public function getMetadata($path)
    {
        return @parent::getMetadata($path);
    }

    /**
     * Returns the remote transport client
     *
     * @param array $params
     *            An array of the connection details
     * @return \JaegerApp\Remote\Sftp
     */
    public static function getRemoteClient(array $params)
    {
        return new m62Sftp([
            'host' => $params['sftp_host'],
            'username' => $params['sftp_username'],
            'password' => $params['sftp_password'],
            'port' => $params['sftp_port'],
            'privateKey' => (isset($params['sftp_private_key']) ? $params['sftp_private_key'] : ''),
            'timeout' => (! empty($params['sftp_timeout']) ? $params['sftp_timeout'] : '30'),
            'root' => $params['sftp_root']
        ]);
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory\Authentication;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Authentication\Storage\DefaultStorage,
    CmsUser\Options\AuthenticationOptionsInterface,
    CmsUser\Options\ModuleOptions;

class StorageFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return DefaultStorage
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $options AuthenticationOptionsInterface */
        $options = $serviceLocator->get(ModuleOptions::class);

        return new DefaultStorage($serviceLocator->get('MapperManager')->get($options->getUserEntityClass()));
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis;

use Predis\Command\CommandInterface;
use Predis\Command\RawCommand;
use Predis\Command\ScriptCommand;
use Predis\Configuration\Options;
use Predis\Configuration\OptionsInterface;
use Predis\Connection\ConnectionInterface;
use Predis\Connection\ParametersInterface;
use Predis\Connection\Replication\SentinelReplication;
use Predis\Monitor\Consumer as MonitorConsumer;
use Predis\Pipeline\Pipeline;
use Predis\PubSub\Consumer as PubSubConsumer;
use Predis\Response\ErrorInterface as ErrorResponseInterface;
use Predis\Response\ResponseInterface;
use Predis\Response\ServerException;
use Predis\Transaction\MultiExec as MultiExecTransaction;

/**
 * Client class used for connecting and executing commands on Redis.
 *
 * This is the main high-level abstraction of Predis upon which various other
 * abstractions are built. Internally it aggregates various other classes each
 * one with its own responsibility and scope.
 *
 * {@inheritdoc}
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Client implements ClientInterface, \IteratorAggregate
{
    const VERSION = '2.0.0-dev';

    /**
     * @var Predis\Configuration\OptionsInterface
     */
    private $options;

    /**
     * @var Predis\Connection\ConnectionInterface
     */
    private $connection;

    /**
     * @var Predis\Command\FactoryInterface
     */
    private $commands;

    /**
     * @param mixed $parameters Connection parameters for one or more servers.
     * @param mixed $options    Options to configure some behaviours of the client.
     */
    public function __construct($parameters = null, $options = null)
    {
        $this->options = $this->createOptions($options ?: array());
        $this->connection = $this->createConnection($parameters ?: array());
        $this->commands = $this->options->commands;
    }

    /**
     * Creates a new instance of Predis\Configuration\Options from different
     * types of arguments or simply returns the passed argument if it is an
     * instance of Predis\Configuration\OptionsInterface.
     *
     * @param mixed $options Client options.
     *
     * @throws \InvalidArgumentException
     *
     * @return OptionsInterface
     */
    protected function createOptions($options)
    {
        if (is_array($options)) {
            return new Options($options);
        }

        if ($options instanceof OptionsInterface) {
            return $options;
        }

        throw new \InvalidArgumentException('Invalid type for client options');
    }

    /**
     * Creates single or aggregate connections from different types of arguments
     * (string, array) or returns the passed argument if it is an instance of a
     * class implementing Predis\Connection\ConnectionInterface.
     *
     * Accepted types for connection parameters are:
     *
     *  - Instance of Predis\Connection\ConnectionInterface.
     *  - Instance of Predis\Connection\ParametersInterface.
     *  - Array
     *  - String
     *  - Callable
     *
     * @param mixed $parameters Connection parameters or connection instance.
     *
     * @throws \InvalidArgumentException
     *
     * @return ConnectionInterface
     */
    protected function createConnection($parameters)
    {
        $options = $this->getOptions();

        if ($parameters instanceof ConnectionInterface) {
            return $parameters;
        }

        if ($parameters instanceof ParametersInterface || is_string($parameters)) {
            return $options->connections->create($parameters);
        }

        if (is_array($parameters)) {
            if (!isset($parameters[0])) {
                return $options->connections->create($parameters);
            }

            if ($options->defined('cluster')) {
                return $this->createAggregateConnection($parameters, 'cluster');
            } elseif ($options->defined('replication')) {
                return $this->createAggregateConnection($parameters, 'replication');
            } elseif ($options->defined('aggregate')) {
                return $this->createAggregateConnection($parameters, 'aggregate');
            } else {
                throw new \InvalidArgumentException(
                    'Array of connection parameters requires `cluster`, `replication` or `aggregate` client option'
                );
            }
        }

        if (is_callable($parameters)) {
            $connection = call_user_func($parameters, $options);

            if (!$connection instanceof ConnectionInterface) {
                throw new \InvalidArgumentException('Callable parameters must return a valid connection');
            }

            return $connection;
        }

        throw new \InvalidArgumentException('Invalid type for connection parameters');
    }

    /**
     * Creates an aggregate connection.
     *
     * @param mixed  $parameters Connection parameters.
     * @param string $option     Option for aggregate connections (`aggregate`, `cluster`, `replication`).
     *
     * @return \Closure
     */
    protected function createAggregateConnection($parameters, $option)
    {
        $options = $this->getOptions();

        $initializer = $options->$option;
        $connection = $initializer($parameters);

        // TODO: this is dirty but we must skip the redis-sentinel backend for now.
        if ($option !== 'aggregate' && !$connection instanceof SentinelReplication) {
            $options->connections->aggregate($connection, $parameters);
        }

        return $connection;
    }

    /**
     * {@inheritdoc}
     */
    public function getCommandFactory()
    {
        return $this->commands;
    }

    /**
     * {@inheritdoc}
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Creates a new client from the specified .
     *
     * The new client instances inherites the same options of the original one.
     * When no callable object is supplied, this method returns the new client.
     * When a callable object is supplied, the new client is passed as its sole
     * argument and its return value is returned by this method to the caller.
     *
     * NOTE: This method works against any kind of underlying connection object
     * as it uses a duck-typing approach and looks for a suitable method that
     * matches the selector type to extract the correct connection.
     *
     * @param string        $selector Type of selector (`id`, `key`, `slot`, `command`)
     * @param string        $value    Values of selector.
     * @param callable|null $callable Optional callable object.
     *
     * @return ClientInterface|mixed
     */
    public function getClientBy($selector, $value, $callable = null)
    {
        $selector = strtolower($selector);

        if (!in_array($selector, array('id', 'key', 'slot', 'role', 'alias', 'command'))) {
            throw new \InvalidArgumentException("Invalid selector type: `$selector`");
        }

        if (!method_exists($this->connection, $method = "getConnectionBy$selector")) {
            $class = get_class($this->connection);
            throw new \InvalidArgumentException("Selecting connection by $selector is not supported by $class");
        }

        if (!$connection = $this->connection->$method($value)) {
            throw new \InvalidArgumentException("Cannot find a connection by $selector matching `$value`");
        }

        $client = new static($connection, $this->getOptions());

        if ($callable) {
            return call_user_func($callable, $client);
        } else {
            return $client;
        }
    }

    /**
     * Opens the underlying connection and connects to the server.
     */
    public function connect()
    {
        $this->connection->connect();
    }

    /**
     * Closes the underlying connection and disconnects from the server.
     */
    public function disconnect()
    {
        $this->connection->disconnect();
    }

    /**
     * Closes the underlying connection and disconnects from the server.
     *
     * This is the same as `Client::disconnect()` as it does not actually send
     * the `QUIT` command to Redis, but simply closes the connection.
     */
    public function quit()
    {
        $this->disconnect();
    }

    /**
     * Returns the current state of the underlying connection.
     *
     * @return bool
     */
    public function isConnected()
    {
        return $this->connection->isConnected();
    }

    /**
     * {@inheritdoc}
     */
    public function getConnection()
    {
        return $this->connection;
    }

    /**
     * Executes a command without filtering its arguments, parsing the response,
     * applying any prefix to keys or throwing exceptions on Redis errors even
     * regardless of client options.
     *
     * It is possible to identify Redis error responses from normal responses
     * using the second optional argument which is populated by reference.
     *
     * @param array $arguments Command arguments as defined by the command signature.
     * @param bool  $error     Set to TRUE when Redis returned an error response.
     *
     * @return mixed
     */
    public function executeRaw(array $arguments, &$error = null)
    {
        $error = false;
        $commandID = array_shift($arguments);

        $response = $this->connection->executeCommand(
            new RawCommand($commandID, $arguments)
        );

        if ($response instanceof ResponseInterface) {
            if ($response instanceof ErrorResponseInterface) {
                $error = true;
            }

            return (string) $response;
        }

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function __call($commandID, $arguments)
    {
        return $this->executeCommand(
            $this->createCommand($commandID, $arguments)
        );
    }

    /**
     * {@inheritdoc}
     */
    public function createCommand($commandID, $arguments = array())
    {
        return $this->commands->createCommand($commandID, $arguments);
    }

    /**
     * {@inheritdoc}
     */
    public function executeCommand(CommandInterface $command)
    {
        $response = $this->connection->executeCommand($command);

        if ($response instanceof ResponseInterface) {
            if ($response instanceof ErrorResponseInterface) {
                $response = $this->onErrorResponse($command, $response);
            }

            return $response;
        }

        return $command->parseResponse($response);
    }

    /**
     * Handles -ERR responses returned by Redis.
     *
     * @param CommandInterface       $command  Redis command that generated the error.
     * @param ErrorResponseInterface $response Instance of the error response.
     *
     * @throws ServerException
     *
     * @return mixed
     */
    protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response)
    {
        if ($command instanceof ScriptCommand && $response->getErrorType() === 'NOSCRIPT') {
            $response = $this->executeCommand($command->getEvalCommand());

            if (!$response instanceof ResponseInterface) {
                $response = $command->parseResponse($response);
            }

            return $response;
        }

        if ($this->options->exceptions) {
            throw new ServerException($response->getMessage());
        }

        return $response;
    }

    /**
     * Executes the specified initializer method on `$this` by adjusting the
     * actual invokation depending on the arity (0, 1 or 2 arguments). This is
     * simply an utility method to create Redis contexts instances since they
     * follow a common initialization path.
     *
     * @param string $initializer Method name.
     * @param array  $argv        Arguments for the method.
     *
     * @return mixed
     */
    private function sharedContextFactory($initializer, $argv = null)
    {
        switch (count($argv)) {
            case 0:
                return $this->$initializer();

            case 1:
                return is_array($argv[0])
                    ? $this->$initializer($argv[0])
                    : $this->$initializer(null, $argv[0]);

            case 2:
                list($arg0, $arg1) = $argv;

                return $this->$initializer($arg0, $arg1);

        // @codeCoverageIgnoreStart
            default:
                return $this->$initializer($this, $argv);
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * Creates a new pipeline context and returns it, or returns the results of
     * a pipeline executed inside the optionally provided callable object.
     *
     * @param mixed ... Array of options, a callable for execution, or both.
     *
     * @return Pipeline|array
     */
    public function pipeline(/* arguments */)
    {
        return $this->sharedContextFactory('createPipeline', func_get_args());
    }

    /**
     * Actual pipeline context initializer method.
     *
     * @param array $options  Options for the context.
     * @param mixed $callable Optional callable used to execute the context.
     *
     * @return Pipeline|array
     */
    protected function createPipeline(array $options = null, $callable = null)
    {
        if (isset($options['atomic']) && $options['atomic']) {
            $class = 'Predis\Pipeline\Atomic';
        } elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
            $class = 'Predis\Pipeline\FireAndForget';
        } else {
            $class = 'Predis\Pipeline\Pipeline';
        }

        /*
         * @var ClientContextInterface
         */
        $pipeline = new $class($this);

        if (isset($callable)) {
            return $pipeline->execute($callable);
        }

        return $pipeline;
    }

    /**
     * Creates a new transaction context and returns it, or returns the results
     * of a transaction executed inside the optionally provided callable object.
     *
     * @param mixed ... Array of options, a callable for execution, or both.
     *
     * @return MultiExecTransaction|array
     */
    public function transaction(/* arguments */)
    {
        return $this->sharedContextFactory('createTransaction', func_get_args());
    }

    /**
     * Actual transaction context initializer method.
     *
     * @param array $options  Options for the context.
     * @param mixed $callable Optional callable used to execute the context.
     *
     * @return MultiExecTransaction|array
     */
    protected function createTransaction(array $options = null, $callable = null)
    {
        $transaction = new MultiExecTransaction($this, $options);

        if (isset($callable)) {
            return $transaction->execute($callable);
        }

        return $transaction;
    }

    /**
     * Creates a new publish/subscribe context and returns it, or starts its loop
     * inside the optionally provided callable object.
     *
     * @param mixed ... Array of options, a callable for execution, or both.
     *
     * @return PubSubConsumer|null
     */
    public function pubSubLoop(/* arguments */)
    {
        return $this->sharedContextFactory('createPubSub', func_get_args());
    }

    /**
     * Actual publish/subscribe context initializer method.
     *
     * @param array $options  Options for the context.
     * @param mixed $callable Optional callable used to execute the context.
     *
     * @return PubSubConsumer|null
     */
    protected function createPubSub(array $options = null, $callable = null)
    {
        $pubsub = new PubSubConsumer($this, $options);

        if (!isset($callable)) {
            return $pubsub;
        }

        foreach ($pubsub as $message) {
            if (call_user_func($callable, $pubsub, $message) === false) {
                $pubsub->stop();
            }
        }
    }

    /**
     * Creates a new monitor consumer and returns it.
     *
     * @return MonitorConsumer
     */
    public function monitor()
    {
        return new MonitorConsumer($this);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        $clients = array();
        $connection = $this->getConnection();

        if (!$connection instanceof \Traversable) {
            throw new ClientException('The underlying connection is not traversable');
        }

        foreach ($connection as $node) {
            $clients[(string) $node] = new static($node, $this->getOptions());
        }

        return new \ArrayIterator($clients);
    }
}