<?php

namespace Chill\CustomFieldsBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;

class CustomFieldsGroupToIdTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    private $om;

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

    /**
     * Transforms an custom_field_group to a string (id)
     *
     * @param  CustomFieldsGroup|null $customFieldsGroup
     * @return string
     */
    public function transform($customFieldsGroup)
    {
        if (null === $customFieldsGroup) {
            return "";
        }

        if (!$customFieldsGroup instanceof CustomFieldsGroup) {
            throw new TransformationFailedException(sprintf('Transformation failed: '
                  . 'the expected type of the transforme function is an '
                  . 'object of type Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, '
                  . '%s given (value : %s)', gettype($customFieldsGroup),
                  $customFieldsGroup));
        }

        return $customFieldsGroup->getId();
    }

    /**
     * Transforms a string (id) to an object (CustomFieldsGroup).
     *
     * @param  string $id
     * @return CustomFieldsGroup|null
     * @throws TransformationFailedException if object (report) is not found.
     */
    public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }

        if ($id instanceof CustomFieldsGroup) {
            throw new TransformationFailedException(sprintf(
                  'The transformation failed: the expected argument on '
                  . 'reverseTransform is an object of type int,'
                  . 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, '
                  . 'given', gettype($id)));
        }

        $customFieldsGroup = $this->om
            ->getRepository('ChillCustomFieldsBundle:customFieldsGroup')->find($id)
        ;

        if (null === $customFieldsGroup) {
            throw new TransformationFailedException(sprintf(
                'Le group avec le numéro "%s" ne peut pas être trouvé!',
                $id
            ));
        }

        return $customFieldsGroup;
    }
}


<?php

/**
 * @file
 * Contains Pipeware\Processor
 */

namespace Pipeware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SyberIsle\Pipeline;

/**
 * PSR-15 pipeline processor
 *
 * @package Pipeware
 */
class Processor
	implements Pipeline\Processor, RequestHandlerInterface
{
	/**
	 * @var \Generator
	 */
	protected $stages;

	/**
	 * @var ResponseFactoryInterface
	 */
	protected $responseFactory;

	public function __construct(ResponseFactoryInterface $responseFactory)
	{
		$this->responseFactory = $responseFactory;
	}

	/**
	 * Handle the request
	 *
	 * @param ServerRequestInterface $request
	 * @return ResponseInterface
	 */
	public function handle(ServerRequestInterface $request): ResponseInterface
	{
		if ($this->stages->valid()) {
			$stage = $this->stages->current();
			$this->stages->next();

			return $stage->process($request, $this);
		}

		return $this->responseFactory->createResponse(404);
	}

	/**
	 * Process the payload
	 *
	 * Returns this with the stages set
	 *
	 * @param Pipeline\Pipeline $pipeline
	 * @param                   $payload
	 * @return mixed|ResponseInterface
	 */
	public function process(Pipeline\Pipeline $pipeline, $payload)
	{
		$runner         = clone($this);
		$runner->stages = $pipeline->getIterator();

		return $runner->handle($payload);
	}
}


<?php
namespace Poirot\Queue;

use Poirot\Events\Interfaces\iEventHeap;
use Poirot\Events\Interfaces\Respec\iEventProvider;
use Poirot\Queue\Exception\Worker\exPayloadMaxTriesExceed;
use Poirot\Queue\Exception\Worker\exPayloadPerformFailed;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Queue\Payload\FailedPayload;
use Poirot\Queue\Queue\AggregateQueue;
use Poirot\Queue\Queue\InMemoryQueue;
use Poirot\Queue\Worker\EventHeapOfWorker;
use Poirot\Queue\Worker\Events\PayloadReceived\ListenerExecutePayload;
use Poirot\Std\ConfigurableSetter;
use Poirot\Std\Exceptions\exImmutable;

class Worker
    extends ConfigurableSetter
    implements iEventProvider
{
    const EVENT_PRIO_EXECUTE_PAYLOAD = 100;

    protected $_worker_id;
    /** @var string Worker name */
    protected $workerName;
    /** @var AggregateQueue */
    protected $queue;

    /** @var iEventHeap */
    protected $events;
    /** @var iQueueDriver */
    protected $builtinQueue;

    protected $maxTries = 5;
    /** @var int Second(s) */
    protected $blockingInterval = 3000;
    /** @var int Second(s) */
    protected $sleep = 0.5 * 1000000;

    /**
     * Worker constructor.
     *
     * @param string         $workerName
     * @param AggregateQueue $queue
     * @param array          $settings
     */
    function __construct($workerName, AggregateQueue $queue, $settings = null)
    {
        $this->workerName  = (string) $workerName;

        $this->queue = $queue;

        if ($settings !== null)
            parent::__construct($settings);
    }

    protected function __init()
    {
        $this->_attachDefaultEvents();

        $self = $this;
        register_shutdown_function(function () use ($self) {
            $self->__destruct();
        });
    }

    /**
     * Get Worker Name
     *
     * @return string
     */
    function getWorkerName()
    {
        return $this->workerName;
    }

    /**
     * Get Worker ID
     *
     * @return string
     */
    function getWorkerID()
    {
        if (! $this->_worker_id )
            $this->_worker_id  = uniqid();

        return $this->_worker_id;
    }

    /**
     *
     * @return int Executed job
     */
    function goUntilEmpty()
    {
        # Achieve Max Execution Time
        #
        ini_set('max_execution_time', 0);
        set_time_limit(0);

        # Add Default Queues To Control Follow
        #
        $failedQueue  = $this->_getBuiltInQueue();
        if (! in_array('failed', $this->queue->listQueues()) )
            // Check whether queue with name failed exists or not
            $this->queue->addQueue('failed', $failedQueue, 9);

        # Go For Jobs
        #
        $jobExecuted = 0;
        while ( 1 )
        {
            $e = null;
            $flagOriginReleased = null;

            ## Pop a Payload from Queue
            #
            if (null === $originPayload = \Poirot\Std\reTry(
                function () {
                    // Pop Payload form Queue
                    return $this->queue->pop();
                }
                , $this->getMaxTries()
                , $this->getBlockingInterval()
            ))
                // Queue is empty
                break;

            try {

                ## Push To Process Payload and Release Queue So Child Processes can continue
                #
                $processPayload = \Poirot\Std\reTry(
                    function() use ($originPayload) {
                        return $this->_getBuiltInQueue()->push($originPayload, 'processing');
                    }
                    , $this->getMaxTries()
                    , $this->getBlockingInterval()
                );

                ## Release Queue So Child Processes can continue
                #
                $flagOriginReleased = \Poirot\Std\reTry(
                    function() use ($originPayload) {
                        $this->queue->release($originPayload);
                        return true;
                    }
                    , $this->getMaxTries()
                    , $this->getBlockingInterval()
                );

                ## Perform Payload Execution
                #
                $this->performPayload($processPayload);

            }
            catch (exPayloadPerformFailed $e)
            {
                ## Push Back Payload as Failed Message To Queue Again For Next Process
                #
                \Poirot\Std\reTry(
                    function() use ($e) {
                        // Build Message For Performer
                        // @see self::performPayload
                        $failedPayload = $e->getPayload();
                        $failedPayload->incCountRetries();

                        return $this->queue->push($failedPayload, 'failed' );
                    }
                    , $this->getMaxTries()
                    , $this->getBlockingInterval()
                );

                // Log Failed Messages
                $this->event()->trigger(
                    EventHeapOfWorker::EVENT_PAYLOAD_ERROR
                    , [
                        'workerName' => $this->workerName,
                        'payload'    => $e->getPayload(),
                        'exception'  => $e->getReason(),
                    ]
                );

            }

            catch (exPayloadMaxTriesExceed $e) {

                // Log Failed Messages
                $this->event()->trigger(
                    EventHeapOfWorker::EVENT_PAYLOAD_FAILURE
                    , [
                        'workerName' => $this->workerName,
                        'payload' => $e->getPayload(),
                        'exception' => $e
                    ]
                );
            }

            catch (\Exception $e)
            {
exc:
                // Logical Exceptions are OK and not considered as critical errors.

                if (! $e instanceof \LogicException )
                {
                    // Origin Released from queue and process failed
                    // So It Must Back To List Again
                    if (! isset($flagOriginReleased) )
                        $flagOriginReleased = \Poirot\Std\reTry(
                            function() use ($originPayload) {
                                $this->queue->release($originPayload);
                                return true;
                            }
                            , $this->getMaxTries()
                            , $this->getBlockingInterval()
                        );

                    if ( isset($flagOriginReleased) ) {

                        \Poirot\Std\reTry(
                            function () use ($originPayload) {
                                // Push Payload Back To Queue
                                return $this->queue->push($originPayload, 'failed');
                            }
                            , $this->getMaxTries()
                            , $this->getBlockingInterval()
                        );
                    }
                }

                // Log Failed Messages
                $this->event()->trigger(
                    EventHeapOfWorker::EVENT_PAYLOAD_FAILURE
                    , [
                        'workerName' => $this->workerName,
                        'payload'    => $originPayload,
                        'exception'  => $e
                    ]
                );
            }

            catch (\Throwable $e)
            {
                goto exc;
            }

            ## Release Process From Queue
            #
            if ( isset($processPayload) )
                $this->_getBuiltInQueue()->release($processPayload);

            if (! isset($e) ) {
                // Log Failed Messages
                $this->event()->trigger(
                    EventHeapOfWorker::EVENT_PAYLOAD_SUCCEED
                    , [
                        'worker'  => $this,
                        'payload' => (isset($originPayload)) ? $originPayload : null,
                    ]
                );
            }
        }

        return $jobExecuted;
    }

    /**
     * Go Running The Worker Processes
     *
     * @param int $maxExecution
     */
    function goWait($maxExecution = null)
    {
        # Go For Jobs
        #
        $jobExecution = 0; $sleep = 0;
        while ( 1 )
        {
            if ( 0 == $executed = $this->goUntilEmpty() ) {
                // List is Empty; Smart Sleep
                $sleep += 100000;
                usleep($sleep);
                if ($sleep > 2 * 1000000)
                    // Sleep more than 2 second not allowed!!
                    $sleep = 100000;

                continue;
            }

            $jobExecution += $executed;
            if ($jobExecution >= $maxExecution)
                // Maximum Execution Task Exceed!!
                break;

            if ( $sleep = $this->getSleep() )
                // Take a breath between hooks
                usleep($sleep);

            $sleep = 0;
        }
    }

    /**
     * Perform Payload Execution
     *
     * @param iPayloadQueued $processPayload
     *
     * @return void
     */
    function performPayload(iPayloadQueued $processPayload)
    {
        $triesCount = 0;

        if ($processPayload instanceof FailedPayload) {
            if ( $processPayload->getCountRetries() > $this->getMaxTries() )
                throw new exPayloadMaxTriesExceed(
                    $processPayload
                    , sprintf('Max Tries Exceeds After %s Tries.', $processPayload->getCountRetries())
                    , null
                );
        }

        $payLoadData = $processPayload->getData();

        try {

            if ( ob_get_level() )
                ## clean output buffer, display just error page
                ob_end_clean();
            ob_start();

            $this->event()->trigger(
                EventHeapOfWorker::EVENT_PAYLOAD_RECEIVED
                , [ 'payload' => $processPayload, 'data' => $payLoadData, 'worker' => $this ]
            );

            ob_end_flush(); // Strange behaviour, will not work
            flush();        // Unless both are called !

        } catch (\LogicException $e) {
            // Exception is logical and its ok to throw
            throw $e;

        } catch (\Exception $e) {
            // Process Failed
            // Notify Main Stream
            if (! $processPayload instanceof FailedPayload)
                $failedPayload = new FailedPayload($processPayload, $triesCount);
            else
                $failedPayload = $processPayload;

            throw new exPayloadPerformFailed($failedPayload, $e);
        }
    }

    // Options:

    /**
     * @return int
     */
    function getBlockingInterval()
    {
        return $this->blockingInterval;
    }

    /**
     * Blocking Interval In Second
     *
     * @param int $blockingInterval
     *
     * @return $this
     */
    function setBlockingInterval($blockingInterval)
    {
        $this->blockingInterval = (int) $blockingInterval;
        return $this;
    }

    /**
     * Get Sleep Time Between Payload Retrievals
     *
     * @return int Microsecond
     */
    function getSleep()
    {
        return $this->sleep;
    }

    /**
     * Set Sleep Time Between Payload Retrievals
     *
     * @param int $sleep Microsecond
     *
     * @return $this
     */
    function setSleep($sleep)
    {
        $this->sleep = $sleep;
        return $this;
    }

    /**
     * Get Max Tries On Failed Job
     *
     * @return int
     */
    function getMaxTries()
    {
        return $this->maxTries;
    }

    /**
     * Set Max Tries On Failed Job
     *
     * @param int $maxTries
     *
     * @return $this
     */
    function setMaxTries($maxTries)
    {
        $this->maxTries = (int) $maxTries;
        return $this;
    }

    /**
     * Give Built In Queue Driver
     *
     * @param iQueueDriver $queueDriver
     *
     * @return $this
     */
    function giveBuiltInQueue(iQueueDriver $queueDriver)
    {
        if ($this->builtinQueue)
            throw new exImmutable(sprintf(
                'Built-in Queue (%s) is given.'
                , \Poirot\Std\flatten($this->builtinQueue)
            ));

        $this->builtinQueue = $queueDriver;
        return $this;
    }

    /**
     * Get Built In Queue Driver
     *
     * @return iQueueDriver
     */
    protected function _getBuiltInQueue()
    {
        if (! $this->builtinQueue )
            $this->giveBuiltInQueue( new InMemoryQueue );

        return $this->builtinQueue;
    }

    // Implement Event Aware

    /**
     * Get Events
     *
     * @return iEventHeap
     */
    function event()
    {
        if (! $this->events)
            $this->events = new EventHeapOfWorker;

        return $this->events;
    }

    // ..

    private function _attachDefaultEvents()
    {
        # Throw Exception if exception not handle on Error Event
        $this->event()->on(
            EventHeapOfWorker::EVENT_PAYLOAD_RECEIVED
            , new ListenerExecutePayload
            , self::EVENT_PRIO_EXECUTE_PAYLOAD
        );
    }

    function __destruct()
    {

    }
}


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

namespace cascade\components\web\widgets\form;

use cascade\components\web\widgets\Widget;
use cascade\models\StorageEngine;
use canis\base\exceptions\Exception;
use canis\helpers\Html;

/**
 * FileStorage [[@doctodo class_description:cascade\components\web\widgets\form\FileStorage]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class FileStorage extends Widget
{
    /**
     * @var [[@doctodo var_type:item]] [[@doctodo var_description:item]]
     */
    public $item;

    /**
     * @inheritdoc
     */
    public function generateContent()
    {
        $renderedStorageEngines = [];
        $storageEngines = StorageEngine::find()->setAction('read')->all();
        foreach ($storageEngines as $key => $storageEngine) {
            $storageHandler = $storageEngine->storageHandler;
            if (!$storageHandler
                || !($renderedStorageEngines[$storageEngine->primaryKey] = $this->renderItem($storageEngine))
                ) {
                unset($storageEngines[$key]);
            }
        }
        $storageEngines = array_values($storageEngines);

        if (empty($storageEngines)) {
            throw new Exception("No storage engines are available to you.");
        }
        if (count($storageEngines) === 1) {
            $storageEngine = $storageEngines[0];
            $storageHandler = $storageEngine->storageHandler;

            return $renderedStorageEngines[$storageEngine->primaryKey];
        } else {
            return "@todo implement multiple storage engines widget";
        }
    }

    /**
     * [[@doctodo method_description:prepareItem]].
     *
     * @param [[@doctodo param_type:engine]] $engine [[@doctodo param_description:engine]]
     *
     * @return [[@doctodo return_type:prepareItem]] [[@doctodo return_description:prepareItem]]
     */
    public function prepareItem($engine)
    {
        $item = clone $this->item;
        $item->inputOptions['data-engine'] = $engine->primaryKey;
        Html::addCssClass($item->inputOptions, 'storage-field');

        return $item;
    }

    /**
     * [[@doctodo method_description:renderItem]].
     *
     * @param [[@doctodo param_type:storageEngine]] $storageEngine [[@doctodo param_description:storageEngine]]
     *
     * @return [[@doctodo return_type:renderItem]] [[@doctodo return_description:renderItem]]
     */
    public function renderItem($storageEngine)
    {
        $item = $this->prepareItem($storageEngine);
        $rendered = $storageEngine->storageHandler->object->generate($item);
        if (!$rendered) {
            return false;
        }
        $hiddenItem = clone $item;
        $hiddenItem->attribute = Html::changeAttribute($hiddenItem->attribute, 'storageEngine');
        $item->model->storageEngine = $storageEngine->primaryKey;
        $rendered .= Html::activeHiddenInput($item->model, $hiddenItem->attribute, $item->inputOptions);

        return $rendered;
    }

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


<?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\EventSystem\Listener\PageCollection;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\EventSystem\Event\Page\PageSavedEvent;
use RedKiteCms\Rendering\PageRenderer\PageRendererProduction;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Class PageSavedListener listens to PageSavedEvent to copy page assets from the backend to production
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Listener\Page
 */
class PageSavedListener
{
    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    private $configurationHandler;
    /**
     * @type \RedKiteCms\Rendering\PageRenderer\PageRendererProduction
     */
    private $pageProductionRenderer;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     * @param \RedKiteCms\Rendering\PageRenderer\PageRendererProduction $pageProductionRenderer
     */
    public function __construct(
        ConfigurationHandler $configurationHandler,
        PageRendererProduction $pageProductionRenderer
    ) {
        $this->configurationHandler = $configurationHandler;
        $this->pageProductionRenderer = $pageProductionRenderer;
    }

    /**
     * Copies the assets from the backend to production
     *
     * @param \RedKiteCms\EventSystem\Event\Page\PageSavedEvent $event
     */
    public function onPageSaved(PageSavedEvent $event)
    {
        $blocks = $event->getApprovedBlocks();
        foreach ($blocks as $blockk) {
            foreach ($blockk as $block) {
                $this->pageProductionRenderer->renderBlock(json_encode($block));
            }
        }
        $mediaFiles = array_unique($this->pageProductionRenderer->getMediaFiles());

        $webDir = $this->configurationHandler->webDir();
        $fs = new Filesystem();
        foreach ($mediaFiles as $mediaFile) {
            $targetMediaFile = str_replace('/backend/', '/production/', $mediaFile);
            $fs->copy($webDir . $mediaFile, $webDir . $targetMediaFile);
        }
    }
}


<?php
namespace Boekkooi\Bundle\AMQP\DependencyInjection;

use Boekkooi\Bundle\AMQP\CommandConfiguration;
use Boekkooi\Bundle\AMQP\Consumer\Consumer;
use Boekkooi\Bundle\AMQP\Exception\InvalidConfigurationException;
use Boekkooi\Bundle\AMQP\LazyChannel;
use Boekkooi\Bundle\AMQP\LazyConnection;
use Boekkooi\Bundle\AMQP\LazyQueue;
use Boekkooi\Bundle\AMQP\LazyExchange;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 */
class BoekkooiAMQPExtension extends Extension
{
    const SERVICE_VHOST_CONNECTION_ID = 'boekkooi.amqp.vhost.%s.connection';
    const SERVICE_VHOST_CHANNEL_ID = 'boekkooi.amqp.vhost.%s.channel';
    const SERVICE_VHOST_CONSUMER_ID = 'boekkooi.amqp.vhost.%s.consumer';
    const SERVICE_VHOST_EXCHANGE_ID = 'boekkooi.amqp.vhost.%s.exchange.%s';
    const SERVICE_VHOST_QUEUE_ID = 'boekkooi.amqp.vhost.%s.queue.%s';

    const PARAMETER_VHOST_LIST = 'boekkooi.amqp.vhosts';
    const PARAMETER_VHOST_EXCHANGE_LIST = 'boekkooi.amqp.vhost.%s.exchanges';
    const PARAMETER_VHOST_QUEUE_LIST = 'boekkooi.amqp.vhost.%s.queues';

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config        = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/services'));

        $loader->load('amqp.yml');
        $this->loadVhosts($container, $config);

        $loader->load('tactician.yml');
        $this->configureCommands($container, $config);
        $this->configureTransformers($container, $config);
        $this->configureMiddleware($container, $config);

        $this->configureConsoleCommands($container, $config);
    }

    private function loadVhosts(ContainerBuilder $container, array $config)
    {
        $vhosts = [];
        foreach ($config['vhosts'] as $name => $info) {
            if (!isset($config['connections'][$info['connection']])) {
                throw InvalidConfigurationException::noConnectionForVHost($info['connection'], $name);
            }

            // Create connection
            $connectionId = sprintf(self::SERVICE_VHOST_CONNECTION_ID, $name);
            $connInfo = $config['connections'][$info['connection']];
            $container->setDefinition(
                $connectionId,
                new Definition(LazyConnection::class, [
                    $connInfo['host'],
                    $connInfo['port'],
                    $info['path'],
                    $connInfo['login'],
                    $connInfo['password'],
                    $connInfo['timeout']['read'],
                    $connInfo['timeout']['write'],
                    $connInfo['timeout']['connect'],
                ])
            );

            // Create channel
            $channelId = sprintf(self::SERVICE_VHOST_CHANNEL_ID, $name);
            $container->setDefinition(
                $channelId,
                new Definition(LazyChannel::class)
            );

            // Create exchanges
            $this->loadVHostExchanges($container, $name, $info);

            // Create queues
            $this->loadVHostQueues($container, $name, $info);

            // Create queue locator
            $queueLocatorId = sprintf('boekkooi.amqp.vhost.%s.queue_locator', $name);
            $def = new DefinitionDecorator('boekkooi.amqp.abstract.consumer.queue_locator');
            $def->addArgument($name);
            $container->setDefinition($queueLocatorId, $def);

            // Create consumer
            $container->setDefinition(
                sprintf(self::SERVICE_VHOST_CONSUMER_ID, $name),
                new Definition(Consumer::class, [
                    new Reference($connectionId),
                    new Reference($channelId),
                    new Reference($queueLocatorId)
                ])
            );

            $vhosts[] = $name;
        }

        $container->setParameter(self::PARAMETER_VHOST_LIST, $vhosts);
    }

    private function loadVHostExchanges(ContainerBuilder $container, $vhost, array $config)
    {
        $typeMap = [
            'direct' => AMQP_EX_TYPE_DIRECT,
            'fanout' => AMQP_EX_TYPE_FANOUT,
            'headers' => AMQP_EX_TYPE_HEADERS,
            'topic' => AMQP_EX_TYPE_TOPIC
        ];

        $exchanges = [];
        foreach ($config['exchanges'] as $name => $info) {
            $container->setDefinition(
                sprintf(self::SERVICE_VHOST_EXCHANGE_ID, $vhost, $name),
                new Definition(LazyExchange::class, [
                    $name,
                    $typeMap[$info['type']],
                    $info['passive'],
                    $info['durable'],
                    $info['arguments']
                ])
            );

            $exchanges[] = $name;
        }

        $container->setParameter(sprintf(self::PARAMETER_VHOST_EXCHANGE_LIST, $vhost), $exchanges);
    }

    private function loadVHostQueues(ContainerBuilder $container, $vhost, array $config)
    {
        $queues = [];
        foreach ($config['queues'] as $name => $info) {
            $serviceId = sprintf(self::SERVICE_VHOST_QUEUE_ID, $vhost, $name);

            $container->setDefinition(
                $serviceId,
                new Definition(LazyQueue::class, [
                    $name,
                    $info['passive'],
                    $info['durable'],
                    $info['exclusive'],
                    $info['auto_delete'],
                    $info['arguments'],
                    $info['binds']
                ])
            );

            $queues[] = $name;
        }

        $container->setParameter(sprintf(self::PARAMETER_VHOST_QUEUE_LIST, $vhost), $queues);
    }

    private function configureCommands(ContainerBuilder $container, array $config)
    {
        $transformerDef = $container->getDefinition('boekkooi.amqp.tactician.command_transformer');
        $middlewareDef = $container->getDefinition('boekkooi.amqp.middleware.command_transformer');

        $basicCommands = [];
        $rpcCommands = [];
        foreach ($config['commands'] as $class => $info) {
            $commandReference = $this->configureCommand($container, $class, $info);

            $transformerDef->addMethodCall('registerCommand', [ $commandReference ]);
            $middlewareDef->addMethodCall('addSupportedCommand', [ $class ]);

            if ($info['rpc'] === true) {
                $rpcCommands[] = $class;
            } else {
                $basicCommands[] = $class;
            }
        }

        $publisherLocator = $container->getDefinition('boekkooi.amqp.tactician.publisher_locator');
        $publisherLocator->addMethodCall(
            'registerPublisher',
            [
                new Reference('boekkooi.amqp.tactician.publisher.basic'),
                $basicCommands
            ]
        );
        $publisherLocator->addMethodCall(
            'registerPublisher',
            [
                new Reference('boekkooi.amqp.tactician.publisher.rpc'),
                $rpcCommands
            ]
        );
    }

    private function configureCommand(ContainerBuilder $container, $class, array $info)
    {
        $commandConfig = new CommandConfiguration(
            $class,
            $info['vhost'],
            $info['exchange'],
            (isset($info['routing_key']) ? $info['routing_key'] : null),
            (
                (isset($info['mandatory']) && $info['mandatory'] ? AMQP_MANDATORY : AMQP_NOPARAM) |
                (isset($info['immediate']) && $info['immediate'] ? AMQP_IMMEDIATE : AMQP_NOPARAM)
            ),
            (isset($info['attributes']) ? $info['attributes'] : [])
        );

        if (!$container->hasDefinition(sprintf(self::SERVICE_VHOST_CONNECTION_ID, $commandConfig->getVhost()))) {
            throw InvalidConfigurationException::unknownVHostForCommand(
                $commandConfig->getClass(),
                $commandConfig->getVhost()
            );
        }
        if (!$container->hasDefinition(sprintf(self::SERVICE_VHOST_EXCHANGE_ID, $commandConfig->getVhost(), $commandConfig->getExchange()))) {
            throw InvalidConfigurationException::unknownExchangeForCommand(
                $commandConfig->getClass(),
                $commandConfig->getVhost(),
                $commandConfig->getExchange()
            );
        }

        $commandId = sprintf(
            'boekkooi.amqp.vhost.%s.command.config.%s',
            $commandConfig->getVhost(),
            sha1(implode('|', [
                $commandConfig->getClass(),
                $commandConfig->getVhost(),
                $commandConfig->getExchange(),
                $commandConfig->getRoutingKey(),
                $commandConfig->getFlags(),
                count($commandConfig->getAttributes())
            ]))
        );
        $commandDef = new Definition(
            CommandConfiguration::class,
            [
                $commandConfig->getClass(),
                $commandConfig->getVhost(),
                $commandConfig->getExchange(),
                $commandConfig->getRoutingKey(),
                $commandConfig->getFlags(),
                $commandConfig->getAttributes()
            ]
        );
        $commandDef->setPublic(false);
        $container->setDefinition($commandId, $commandDef);

        return new Reference($commandId);
    }

    private function configureTransformers(ContainerBuilder $container, array $config)
    {
        $container
            ->setParameter(
                'boekkooi.amqp.tactician.serializer.format',
                $config['serializer_format']
            );
        $container
            ->setParameter(
                'boekkooi.amqp.tactician.serializer.service',
                $config['serializer']
            );

        $commandSerializer = new Reference($config['serializer']);
        foreach (['command_transformer', 'envelope_transformer', 'response_transformer'] as $transformer) {
            $container
                ->getDefinition('boekkooi.amqp.tactician.' . $transformer)
                ->replaceArgument(0, $commandSerializer);
        }
    }

    private function configureMiddleware(ContainerBuilder $container, array $config)
    {
        $envelopeTransformer = new Reference($config['envelope_transformer']);
        $container
            ->getDefinition('boekkooi.amqp.middleware.envelope_transformer')
            ->replaceArgument(0, $envelopeTransformer);

        $commandTransformer = new Reference($config['command_transformer']);
        $container
            ->getDefinition('boekkooi.amqp.middleware.command_transformer')
            ->replaceArgument(0, $commandTransformer);

        $responseTransformer = new Reference($config['response_transformer']);
        $container
            ->getDefinition('boekkooi.amqp.middleware.remote_response')
            ->replaceArgument(0, $responseTransformer);

        foreach ($config['publisher']['transaction'] as $name) {
            $capturerId = sprintf('boekkooi.amqp.middleware.transaction.%s_capturer', $name);
            $container->setDefinition(
                $capturerId,
                clone $container->getDefinition('boekkooi.amqp.tactician.publisher.capturer')
            );

            $transaction = clone $container->getDefinition('boekkooi.amqp.middleware.transaction_transaction');
            $transaction->replaceArgument(0, new Reference($capturerId));
            $container->setDefinition(
                sprintf('boekkooi.amqp.middleware.transaction.%s_transaction', $name),
                $transaction
            );

            $publish = clone $container->getDefinition('boekkooi.amqp.middleware.transaction_publish');
            $publish->replaceArgument(0, new Reference($capturerId));
            $container->setDefinition(
                sprintf('boekkooi.amqp.middleware.transaction.%s_publish', $name),
                $publish
            );
        }
    }

    private function configureConsoleCommands(ContainerBuilder $container, array $config)
    {
        $container
            ->setAlias('boekkooi.amqp.consume_command_bus', $config['command_bus']);
    }
}


<?php declare(strict_types=1);
/**
 * The router class
 *
 * This router defines routes based on nikic's FastRoute project
 *
 * PHP version 7.0
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 * @copyright  Copyright (c) 2015 Pieter Hordijk <https://github.com/PeeHaa>
 * @license    See the LICENSE file
 * @version    1.0.0
 */
namespace CodeCollab\Router;

use FastRoute\RouteCollector;
use FastRoute\Dispatcher;

/**
 * The router class
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 */
class Router
{
    /**
     * @var \FastRoute\RouteCollector Collector for routes defined in the system
     */
    private $routeCollector;

    /**
     * @var callable Factory for the dispatcher
     */
    private $dispatcherFactory;

    /**
     * @var string Filename of the cache file
     */
    private $cacheFile;

    /**
     * @var bool Whether to invalidate and reload the cache
     */
    private $forceReload;

    /**
     * Creates instance
     *
     * @param \FastRoute\RouteCollector $routeCollector    Collector for routes defined in the system
     * @param callable                  $dispatcherFactory Factory for the dispatcher
     * @param string                    $cacheFile         Filename of the cache file
     * @param bool                      $forceReload       Whether to invalidate and reload the cache
     */
    public function __construct(
        RouteCollector $routeCollector,
        callable $dispatcherFactory,
        string $cacheFile,
        bool $forceReload = false
    )
    {
        $this->routeCollector    = $routeCollector;
        $this->dispatcherFactory = $dispatcherFactory;
        $this->cacheFile         = $cacheFile;
        $this->forceReload       = $forceReload;
    }

    /**
     * Adds a route for a GET request
     *
     * @param string $path     The pattern of the path of the route
     * @param array  $callback The callback of the route
     *
     * @return \CodeCollab\Router\Router Return instance of itself to create a fluent interface
     */
    public function get(string $path, array $callback): Router
    {
        return $this->addRoute('GET', $path, $callback);
    }

    /**
     * Adds a route for a POST request
     *
     * @param string $path     The pattern of the path of the route
     * @param array  $callback The callback of the route
     *
     * @return \CodeCollab\Router\Router Return instance of itself to create a fluent interface
     */
    public function post(string $path, array $callback): Router
    {
        return $this->addRoute('POST', $path, $callback);
    }

    /**
     * Adds a route
     *
     * @param string $verb     The HTTP verb of the route
     * @param string $path     The pattern of the path of the route
     * @param array  $callback The callback of the route
     *
     * @return \CodeCollab\Router\Router Return instance of itself to create a fluent interface
     */
    public function addRoute(string $verb, string $path, array $callback): Router
    {
        $this->routeCollector->addRoute($verb, $path, $callback);

        return $this;
    }

    /**
     * Gets the dispatcher
     *
     * @return \FastRoute\Dispatcher The dispatcher
     */
    public function getDispatcher(): Dispatcher
    {
        if ($this->forceReload || !file_exists($this->cacheFile)) {
            $dispatchData = $this->buildCache();
        } else {
            /** @noinspection PhpIncludeInspection */
            $dispatchData = require $this->cacheFile;
        }

        return call_user_func($this->dispatcherFactory, $dispatchData);
    }

    /**
     * Builds the routes cache file
     *
     * @return array The dispatch data
     */
    private function buildCache(): array
    {
        $dispatchData = $this->routeCollector->getData();

        file_put_contents($this->cacheFile, '<?php return ' . var_export($dispatchData, true) . ';');

        return $dispatchData;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Twig\Extension;

use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use Dothiv\Bundle\ContentfulBundle\Output\Content;
use PhpOption\LazyOption;
use PhpOption\None;
use PhpOption\Option;
use Symfony\Component\HttpFoundation\Request;

class ContentfulTwigExtension extends \Twig_Extension
{

    /**
     * @var Content
     */
    private $content;

    /**
     * @param Content $content
     * @param string  $contentFuncName
     */
    public function __construct(
        Content $content,
        $contentFuncName = null
    )
    {
        $this->content         = $content;
        $this->contentFuncName = Option::fromValue($contentFuncName)->getOrElse('content');
    }

    /**
     * {@inheritdoc}
     */
    public function getTags()
    {

    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction($this->contentFuncName, array($this, 'buildItem'), array('needs_context' => true))
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('behaviour', array($this, 'parseBehaviour'))
        );
    }

    public function buildItem(array $ctx, $type, $name = null, $locale = null)
    {
        $ctxLocale     = new LazyOption(function () use ($ctx) {
            return isset($ctx['locale']) ? Option::fromValue($ctx['locale']) : None::create();
        });
        $requestLocale = new LazyOption(function () use ($ctx) {
            return isset($ctx['app']) ? Option::fromValue($ctx['app']->getRequest())->map(function (Request $request) {
                return $request->getLocale();
            }) : None::create();
        });
        $locale        = Option::fromValue($locale)->orElse($ctxLocale)->orElse($requestLocale)->get();
        if ($name === null) {
            return $this->content->buildEntries($type, $locale);
        }
        try {
            return $this->content->buildEntry($type, $name, $locale);
        } catch (InvalidArgumentException $e) {
            return null;
        }
    }

    /**
     * This filter parses a blocks behaviour configuration string.
     *
     * @param \stdClass $block
     * @param string    $search
     *
     * @return string|boolean
     */
    public function parseBehaviour(\stdClass $block, $search)
    {
        if (!isset($block->behaviour)) {
            return false;
        }
        $behaviours = array();
        foreach (explode(' ', trim($block->behaviour)) as $b) {
            if (strstr($b, ':')) {
                list($name, $prop) = explode(':', $b, 2);
                $behaviours[$name] = $prop;
            } else {
                $behaviours[$b] = true;
            }
        }
        return isset($behaviours[$search]) ? $behaviours[$search] : false;
    }

    public function getName()
    {
        return 'dothiv_contentful_' . $this->contentFuncName;
    }
}


<?php

namespace Biigle\CachedOpenStack;

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use OpenStack\Common\Transport\Utils;
use OpenStack\Common\Service\Builder;
use OpenStack\OpenStack as BaseOpenStack;
use Illuminate\Cache\CacheManager as Cache;
use GuzzleHttp\Middleware as GuzzleMiddleware;

class OpenStack extends BaseOpenStack
{
   /**
    * Create a new instance.
    *
    * @param Cache $cache Cache instance to use.
    * @param array $options OpenStack options.
    * @param Builder|null $builder OpenStack service builder.
    */
   public function __construct(Cache $cache, array $options = [], Builder $builder = null)
   {
      $options['identityService'] = $this->getCachedIdentityService($cache, $options);
      parent::__construct($options, $builder);
   }

   /**
    * Create the cached identity serivce.
    *
    * @param Cache $cache
    * @param array $options
    *
    * @return CachedIdentityService
    */
   protected function getCachedIdentityService(Cache $cache, array $options): CachedIdentityService
   {
      if (!isset($options['authUrl'])) {
        throw new \InvalidArgumentException("'authUrl' is a required option");
      }

      $stack = HandlerStack::create();

      if (!empty($options['debugLog'])
            && !empty($options['logger'])
            && !empty($options['messageFormatter'])
      ) {
         $stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
      }

      $clientOptions = [
         'base_uri' => Utils::normalizeUrl($options['authUrl']),
         'handler'  => $stack,
      ];

      if (isset($options['requestOptions'])) {
         $clientOptions = array_merge($options['requestOptions'], $clientOptions);
      }

      $service = CachedIdentityService::factory(new Client($clientOptions));
      $service->setCache($cache);

      return $service;
    }
}


<?php
namespace app\manage\logic;

use cms\Login;
use think\Url;
use think\Config;
use lookfeel\common\Format;
use core\manage\logic\MemberLogic;

class LoginLogic
{

    /**
     * 登录存储Key
     *
     * @var unknown
     */
    const LOGIN_KEY = 'manage_user';

    /**
     * 登录操作
     *
     * @param string $user_name
     * @param string $user_pass
     * @return array
     */
    public static function doLogin($user_name, $user_pass)
    {
        $res = MemberLogic::instance()->checkLogin($user_name, $user_pass);
        if ($res['code'] != MemberLogic::TYPE_USER_LOGIN) {
            return Format::formatResult(0, $res['msg']);
        }
        $user = $res['data']['user'];
        $group = $res['data']['group'];

        $login_driver = self::getLoginDriver();
        $data = [
            'user_id' => $user['id'],
            'manage_url' => Url::build($group['home_page'])
        ];
        $login_driver->storageLogin(self::LOGIN_KEY, $data);

        return Format::formatResult(1, '登录成功', $data['manage_url']);
    }

    /**
     * 注销登录
     */
    public static function loginOut()
    {
        $login_driver = self::getLoginDriver();
        $login_driver->clearLogin(self::LOGIN_KEY);
    }

    /**
     * 登录用户
     *
     * @return array
     */
    public static function getLoginUser()
    {
        $login_driver = self::getLoginDriver();
        return $login_driver->readLogin(self::LOGIN_KEY);
    }

    /**
     * 登录用户信息
     *
     * @return array
     */
    public static function gteLoginUserInfo()
    {
        $user = self::getLoginUser();
        if (empty($user)) {
            return null;
        }

        return MemberLogic::instance()->getUser($user['user_id']);
    }

    /**
     * 登录存储驱动
     *
     * @return \cms\Login
     */
    public static function getLoginDriver()
    {
        return Login::create(Config::get('manage_driver_login'));
    }
}


<?php

/**
 * Remove the same origin restriction from API calls.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.controller.plugins.html Zend_Controller_Plugin_Abstract
 */
class Benri_Controller_Plugin_CORS extends Zend_Controller_Plugin_Abstract
{
    /**
     * Indicates whether a resource can be shared based by returning the value
     * of the Origin request header, "*", or "null" in the response.
     *
     * @var string
     */
    private $_origin = '*';

    /**
     * Indicates whether the response to request can be exposed when the omit
     * credentials flag is unset. When part of the response to a preflight
     * request it indicates that the actual request can include user
     * credentials.
     *
     * @var bool
     */
    private $_credentials = true;

    /**
     * Indicates, as part of the response to a preflight request, which methods
     * can be used during the actual request.
     *
     * @var array
     */
    private $_methods = [
        'DELETE',
        'GET',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT',
    ];

    /**
     * Indicates, as part of the response to a preflight request, which header
     * field names can be used during the actual request.
     *
     * @var array
     */
    private $_headers = [
        'Authorization',
        'Content-Type',
    ];

    /**
     * Indicates how long the results of a preflight request can be cached in
     * a preflight result cache.
     *
     * @var int
     */
    private $_maxAge = 86400;

    /**
     * Called after an action is dispatched by Zend_Controller_Dispatcher.
     *
     * @internal
     * @param Zend_Controller_Request_Abstract $request
     * @see http://framework.zend.com/manual/1.12/en/zend.controller.request.html Zend_Controller_Request_Abstract
     */
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $methods  = implode(', ', array_unique($this->_methods));
        $headers  = implode(', ', array_unique($this->_headers));

        if ($this->_credentials) {
            header('Access-Control-Allow-Credentials: true', true);
        }

        header("Access-Control-Allow-Origin: {$this->_origin}", true);
        header("Access-Control-Allow-Methods: {$methods}", true);
        header("Access-Control-Allow-Headers: {$headers}", true);
        header("Access-Control-Max-Age: {$this->_maxAge}", true);
        header('X-XSS-Protection: 1; mode=block', true);
        header('X-Frame-Options: SAMEORIGIN', true);
    }

    /**
     * @param bool $credentials
     * @return Benri_Controller_Plugin_CORS
     */
    public function setCredentials($credentials = true)
    {
        $this->_credentials = (bool) $credentials;

        return $this;
    }

    /**
     * @param string $origin
     * @return Benri_Controller_Plugin_CORS
     */
    public function setOrigin($origin = '*')
    {
        $this->_origin = $origin;

        return $this;
    }

    /**
     * @param int $deltaSeconds
     * @return Benri_Controller_Plugin_CORS
     */
    public function setMaxAge($deltaSeconds = 86400)
    {
        $this->_maxAge = $deltaSeconds;

        return $this;
    }

    /**
     * Set a header to use within 'Access-Control-Allow-Headers' header.
     *
     * @param string $name
     * @return Benri_Controller_Plugin_CORS
     */
    public function setHeader($name)
    {
        $this->_headers[] = $name;

        return $this;
    }

    /**
     * Clear the specified header from 'Access-Control-Allow-Headers' index.
     *
     * @param string $name The header to clear
     * @return Benri_Controller_Plugin_CORS
     */
    public function clearHeader($name)
    {
        return $this->unsetFromArray($name, $this->_headers);
    }

    /**
     * Set a method to use within 'Access-Control-Allow-Methods' header.
     *
     * @param string $name
     * @return Benri_Controller_Plugin_CORS
     */
    public function setMethod($name)
    {
        $this->_methods[] = $name;

        return $this;
    }

    /**
     * Clear the specified method from 'Access-Control-Allow-Methods' index.
     *
     * @param string $name
     * @return Benri_Controller_Plugin_CORS
     */
    public function clearMethod($name)
    {
        return $this->unsetFromArray($name, $this->_methods);
    }

    /**
     * @internal
     */
    private function unsetFromArray($name, array &$array)
    {
        if (!count($array)) {
            return $this;
        }

        foreach ($array as $index => $header) {
            if ($name === $header) {
                unset($array[$index]);
            }
        }

        return $this;
    }
}


<?php

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

/**
 * Fundamental API.
 *
 * @author    mingyoung <mingyoungcheung@gmail.com>
 * @copyright 2017
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Fundamental;

use EasyWeChat\Core\AbstractAPI;

class API extends AbstractAPI
{
    const API_CLEAR_QUOTA = 'https://api.weixin.qq.com/cgi-bin/clear_quota';
    const API_CALLBACK_IP = 'https://api.weixin.qq.com/cgi-bin/getcallbackip';

    /**
     * Clear quota.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function clearQuota()
    {
        $appid = $this->getAccessToken()->getAppId();

        return $this->parseJSON('json', [self::API_CLEAR_QUOTA, compact('appid')]);
    }

    /**
     * Get wechat callback ip.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getCallbackIp()
    {
        return $this->parseJSON('get', [self::API_CALLBACK_IP]);
    }
}


<?php

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

/**
 * PaymentServiceProvider.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015
 *
 * @see      https://github.com/overtrue/wechat
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\Payment\CashCoupon\CashCoupon;
use EasyWeChat\Payment\LuckyMoney\LuckyMoney;
use EasyWeChat\Payment\Merchant;
use EasyWeChat\Payment\MerchantPay\MerchantPay;
use EasyWeChat\Payment\Payment;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class PaymentServiceProvider.
 */
class PaymentServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['merchant'] = function ($pimple) {
            $config = array_merge(
                ['app_id' => $pimple['config']['app_id']],
                $pimple['config']->get('payment', [])
            );

            return new Merchant($config);
        };

        $pimple['payment'] = function ($pimple) {
            $payment = new Payment($pimple['merchant']);
            $payment->sandboxMode(
                (bool) $pimple['config']->get('payment.sandbox_mode')
            );

            return $payment;
        };

        $pimple['lucky_money'] = function ($pimple) {
            return new LuckyMoney($pimple['merchant']);
        };

        $pimple['merchant_pay'] = function ($pimple) {
            return new MerchantPay($pimple['merchant']);
        };

        $pimple['cash_coupon'] = function ($pimple) {
            return new CashCoupon($pimple['merchant']);
        };
    }
}


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('contactable');
            $table->string('firstname')->nullable();
            $table->string('middlename')->nullable();
            $table->string('lastname')->nullable();
            $table->string('address')->nullable();
            $table->string('postalcode')->nullable();
            $table->string('city')->nullable();
            $table->smallInteger('phonenumber')->nullable();
            $table->smallInteger('mobile')->nullable();
            $table->string('email', 254)->nullable();
            $table->timestamp('dateofbirth')->nullable();
            $table->tinyInteger('gender')->nullable();
            $table->tinyInteger('maritalstatus')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}


<?php

/*
 * This file is part of the P13/DateTime package.
 *
 * (c) Wagner Sicca <wssicca@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace p13\datetime;

use \DateInterval as OriginalDateInterval;

/**
 * Extensão da classe nativa \DateInterval
 *
 * @author Wagner Sicca <wssicca@gmail.com>
 * @namespace p13\datetime
 * @package p13\datetime
 */
class DateInterval extends OriginalDateInterval implements ExtensionInterface
{

    /**
     * Retorna o número de segundos do intervalo
     * @return int
     */
    public function getSeconds()
    {
        $sec = $this->s;
        $sec += ($this->i * 60);
        $sec += ($this->h * 3600);
        $sec += empty($this->days) ? ($this->d * 86400) : ($this->days * 86400);
        return $sec;
    }

    /**
     * Faz o "cast" de \DateTime para p13\util\datetime\DateTime
     * @param \DateInterval $interval
     * @return DateInterval
     */
    public static function cast($interval)
    {
        if ($interval instanceof self) {
            return $interval;
        } else {
            $myDateInterval = new DateInterval(
                    $interval->format('P%yY%mM%dDT%hH%iM%sS')
            );
            $myDateInterval->invert = $interval->invert;
            return $myDateInterval;
        }
    }

}


<?php

namespace Nether\Cache;
use \Nether;

Nether\Option::Define([
	'cache-diskcache-path' => null
]);

class Diskcache extends DriverInterface {

	protected $Path;
	/*//
	@type string
	the directory path to the file cache.
	//*/

	public function __construct() {
		$this->SetPath(Nether\Option::Get('cache-diskcache-path'));
		return;
	}

	public function SetPath($path) {
	/*//
	define the path to store files in. automatically trims off any trailing
	slashes that are left on.
	//*/

		$this->Path = rtrim($path,'\\/');
		return;
	}

	////////////////
	////////////////

	public function GetFileName($key) {
	/*//
	@return string
	get the full path filename to the file that will be generated by this key
	request, adds a .cache extension to the key as well.
	//*/

		return sprintf(
			'%s%s%s.cache',
			$this->Path,
			DIRECTORY_SEPARATOR,
			$key
		);
	}

	public function IsPathValid() {
	/*//
	@return boolean
	determine if the configured path for file storage is a valid and accessable
	place to put things.
	//*/

		if(!$this->Path) {
			/*//todo/
			log this error.
			//*/
			echo "Option cache-diskcache-path not set.", PHP_EOL;
			return false;
		}

		if(!is_dir($this->Path)) {
			/*//todo/
			log this error.
			//*/

			if(!@mkdir($this->Path,0777,true)) {
				/*//todo/
				log this error.
				//*/
				echo "Unable to create {$this->Path}", PHP_EOL;
				return false;
			} else {
				return true;
			}
		}

		if(!is_writable($this->Path)) {
			/*//todo/
			log this error.
			//*/
			echo "Cache path {$this->Path} is not writable.", PHP_EOL;
			return false;
		}

		return true;
	}

	////////////////
	////////////////

	public function Drop($key) {
		if(!$this->IsPathValid()) return;

		$file = $this->GetFileName($key);
		if(file_exists($file)) {
			if(!is_writable($file)) {
				/*//todo/
				log this error.
				//*/
				echo "Unable to remove cache {$file}", PHP_EOL;
			} else {
				unlink($file);
			}
		}

		return;
	}

	public function Flush() {
		if(!$this->IsPathValid()) return;

		$list = glob($this->GetFileName('*'));
		foreach($list as $file) {
			if(!is_writable($file)) {
				/*//todo/
				log this error.
				//*/
				echo "Unable to remove cache file {$file}", PHP_EOL;
			} else {
				unlink($file);
			}
		}

		return;
	}

	public function Get($key) {
		if(!$this->IsPathValid()) return;

		$file = $this->GetFileName($key);
		if(file_exists($file)) {
			if(!is_readable($file)) {
				/*//todo/
				log this error.
				//*/
				echo "Unable to read cache file {$file}", PHP_EOL;
			} else {
				++$this->Hit;
				return unserialize(file_get_contents($file));
			}
		}

		++$this->Miss;
		return null;
	}

	public function Set($key,$value) {
		if(!$this->IsPathValid()) return;

		$file = $this->GetFileName($key);
		if(!is_writable(dirname($file))) {
			/*//todo/
			log this error.
			//*/
			echo "Unable to write cache file {$file}", PHP_EOL;
		} else {
			file_put_contents($file,serialize($value));
		}

		return;
	}

}


<?php

namespace NajiDev\Common\Helper;

class ArrayHelper
{
	/**
	 * Iterates over each value in the input array passing them to the callback function (recursively). If the callback
	 * function returns true, the current value from input is returned into the result array. Array keys are preserved.
	 *
	 * @param array $input
	 * @param callable $callback
	 * @return array
	 */
	public static function array_filter_recursive(array $input, $callback = null)
	{
		$result = array();

		foreach ($input as $key => $value)
		{
			if (is_array($value))
				$value = self::array_filter_recursive($value, $callback);

			if (call_user_func($callback, $value))
				$result[$key] = $value;
		}

		return $result;
	}
}


<?php
/**
* Tiny library for WordPress plug-ins.
*
* @author Ondrej Donek, <ondrejd@gmail.com>
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
*/

namespace odwp;

/**
 * Parent class for WordPress plug-ins.
 *
 * Usage:
 *

 * class MySimplePlugin extends \odwp\SimplePlugin {
 *     protected $classname = __CLASS__;
 *     protected $id = 'my-plugin';
 *     protected $version = '0.1';
 *     protected $texdomain = 'my-plugin';
 *
 *     public function get_title($suffix = '', $sep = ' - ') {
 *         if (empty($suffix)) {
 *             return __('My Plugin', $this->get_textdomain());
 *         }
 *
 *         return sprintf(
 *             __('My Plugin%s%s', $this->get_textdomain()),
 *             $sep,
 *             $suffix
 *         );
 *     }
 * }
 *

 *
 * @author Ondřej Doněk, <ondrej.donek@ebrana.cz>
 * @version 0.2
 */
abstract class SimplePlugin {

    /**
     * Name of main plug-in's class.
     * @var string $className
     */
    protected $class_name;

    /**
     * Identifier of the plug-in.
     * @var string $id
     */
    protected $id;

    /**
     * Default options of the plug-in.
     * @var \odwp\Options $options
     */
    protected $options;

    /**
     * Textdomain of the plug-in.
     * @var string $textdomain
     */
    protected $texdomain;

    /**
     * The plug-in's title.
     * @var string $title
     */
    protected $title;

    /**
     * Version of the plug-in.
     * @var string $version
     */
    protected $version;

    /**
     * Widgets provided by the plug-in. Array should contains class names of the widgets.
     * @var array $widgets
     */
    protected $widgets;

    /**
     * Position in WP administration menu.
     * @var integer $admin_menu_position
     */
    protected $admin_menu_position;

    /**
     * If `TRUE` than default options page in WP administration will be used.
     * @var boolean $enable_default_options_page
     */
    protected $enable_default_options_page = true;

    /**
     * Holds Twig templating engine.
     * @var \Twig_Environment $tplEngine
     */
    protected $twig;

    /**
     * Holds `TRUE` if textdomain is already initialized.
     * @var boolean $locales_initialized
     */
    private $locales_initialized;

    /**
     * Constructor.
     *
     * @since 0.1.1
     * @return void
     */
    public function __construct() {
        // Check if exists `cache` directory and try to create it if not.
        $cache_path = $this->get_path('cache');
        if (!file_exists($this->get_path('cache'))) {
            @mkdir($cache_path, 0777);
        }

        if (!is_dir($cache_path) || !is_writable($cache_path)) {
            throw new \Exception('You need to create cache directory for templats.');
        }

		// Initialize Twig
		// @link http://twig.sensiolabs.org/doc
		$loader = new \Twig_Loader_Filesystem(array(
			$this->get_path('templates'),
			$this->get_core_path('templates')
		));
		$this->twig = new \Twig_Environment($loader, array(
			'cache' => $cache_path
		));

        // Initialize options
        $this->init_options();

        // Initialize the localization
        $this->init_locales();

        // Plug-in's activation/deactivation
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));

        // Plug-in's uninstall
		register_uninstall_hook(__FILE__, array($this, 'uninstall'));

        // Initialize plugin's widgets
        add_action('widgets_init', array($this, 'init_widgets'));

        // Below are things required only in WP administration...
        if(!is_admin()) {
            return;
        }

        // Register admin menu
        add_action('admin_menu', array($this, 'register_admin_menu'));

        // Register TinyMCE buttons
        if (method_exists($this, 'register_tinymce_buttons')) {
            add_action('init', array($this, 'register_tinymce_buttons'));
        }

        // Use default options page
        if ($this->enable_default_options_page === true) {
            add_action('admin_menu', array($this, 'register_admin_menu'));
            add_action('admin_menu', array($this, 'register_admin_options_page'));
        }
    }

    /**
     * Activates the plug-in.
     *
     * @since 0.5
     * @global wpdb $wpdb
     * @return void
     */
    public function activate() {
        // ...
    }

    /**
     * Deactivates the plug-in.
     *
     * @since 0.5
     * @return void
     */
    public function deactivate() {
        // ...
    }

    /**
     * @since 0.1.9
     * @param string $suffix (Optional.)
     * @return string Returns plug-in's class name (with optional suffix).
     */
    public function get_classname($suffix = '') {
        $ret = $this->classname;

        if (!empty($suffix)) {
            $ret .= $suffix;
        }

        return $ret;
    }

    /**
     * Returns plug-in's ID (with optional suffix).
     *
     * @since 0.1.3
     * @param string $suffix (Optional).
     * @return string
     */
    function get_id($suffix = '') {
        $ret = $this->id;
        if (!empty($suffix)) {
            $ret .= $suffix;
        }

        return $ret;
    }

    /**
     * Returns URL to the plug-in's icon.
     *
     * @since 0.1.3
     * @param string $size (Optional.)
     * @return string
     */
    public function get_icon($size = '32') {
        if (!defined('WP_PLUGIN_URL')) {
            wp_plugin_directory_constants();
        }

        return WP_PLUGIN_URL . '/' . $this->get_id('/icon' . $size . '.png');
    }

    /**
     * Returns path to the plugin's directory. If `$file` is provided
     * than is appended to the end of the path.
     *
     * @since 0.1.3
     * @param string $file (Optional).
     * @return string
     */
    public function get_path($file = '') {
        if (!defined('WP_PLUGIN_DIR')) {
            wp_plugin_directory_constants();
        }

        // TODO There is probably better constant than WP_CONTENT_DIR!
        $path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $this->id;
        if (!empty($file)) {
            $path .= DIRECTORY_SEPARATOR . $file;
        }

        return $path;
    }

    /**
     * Returns array with options of the plug-in.
     *
     * @since 0.1
     * @return array
     */
    public function get_options() {
        return get_option($this->id . '-options');
    }

    /**
     * Returns title of the plug-in.
     *
     * @since 0.1.3
     * @param string $suffix (Optional.)
     * @param string $sep (Optional.)
     * @return string
     */
    abstract public function get_title($suffix = '', $sep = ' - ');

    /**
     * @internal
     * @since 0.1.5
     * @param string $tpl Name of template file.
     * @param array $params
     * @return string
     */
    public function get_core_path($file = '') {
        $ret = dirname(__DIR__);

        if (!empty($file)) {
            $ret .= DIRECTORY_SEPARATOR . $file;
        }

        return $ret;
    }

    /**
     * Returns textdomain for localizing the plug-in.
     *
     * @since 0.1.4
     * @return string
     */
    public function get_textdomain() {
        return $this->textdomain;
    }

    /**
     * Initialize the localization.
     *
     * @return void
     */
    public function init_locales() {
        if (!empty($this->textdomain) && $this->locales_initialized !== true) {
            load_plugin_textdomain($this->textdomain, true, $this->get_id());
            $this->locales_initialized = true;
        }
    }

    /**
     * Initialize plugin's options
     *
     * @since 0.1.1
     * @return array
     */
    public function init_options() {
        if (!is_array($this->options)) {
            $this->options = array();
        }

        $options_id = $this->get_id('-options');
        $options = get_option($options_id);
        $need_update = false;

        if($options === false) {
            $need_update = true;
            $options = array();
        }

        foreach($this->options as $key => $value) {
            if(!array_key_exists($key, $options)) {
                $options[$key] = $value;
            }
        }

        if(!array_key_exists('latest_used_version', $options)) {
            $options['latest_used_version'] = $this->version;
            $need_update = true;
        }

        if($need_update === true) {
            update_option($options_id, $options);
        }

        return $options;
    }

    /**
     * Initializes widgets (if are any defined).
     *
     * @since 0.1.2
     * @return void
     */
    public function init_widgets() {
        if (!is_array($this->widgets)) {
            $this->widgets = array();
        }

        if (count($this->widgets) > 0) {
            return;
        }

        foreach ($this->widgets as $widget) {
            if (class_exists($widget)) {
                register_widget($widget);
            }
        }
    }

    /**
     * Registers administration menu for the plugin.
     *
     * @since 0.1.3
     * @return void
     */
    public function register_admin_menu() {
        add_menu_page(
            $this->get_title(),
            $this->get_title(),
            'edit_posts',
            $this->get_id(),
            array($this, 'render_admin_page'),
            $this->get_icon('16'),
            empty($this->admin_menu_position) ? null : $this->admin_menu_position
        );
    }

    /**
     * Registers administration menu for the plugin.
     *
     * @since 0.1.3
     * @return void
     */
    public function register_admin_options_page() {
        add_submenu_page(
            $this->get_id(),
            $this->get_title(),
            $this->get_title(__('Settings', $this->get_textdomain())),
            'manage_options',
            $this->get_id('-settings'),
            array($this, 'render_admin_options_page')
        );
    }

    /**
     * Renders default main page (in WP administration).
     *
     * @since 0.1.5
     * @return void
     */
    public function render_admin_page() {
        // Render simple commmon main plug-in's admin page
        echo $this->twig->render('admin_page.html.twig', array(
            'icon' => $this->get_icon(),
            'title' => $this->get_title()
        ));
    }

    /**
     * Renders default options page (in WP administration).
     *
     * @since 0.1.3
     * @return void
     *
     * @todo Add `Reset To Defaults` button!
     */
    public function render_admin_options_page() {
        $default = $this->options;
        $current = $this->get_options();
        $params = array(
            'icon' => $this->get_icon(),
            'title' => $this->get_title(__('Settings', $this->get_textdomain())),
            'form_url' => get_bloginfo('url') . '/wp-admin/admin.php?page=' . $this->get_id('-settings')
        );

        // Update options if necessarry
        if (filter_input(INPUT_POST, 'submit')) {
            $res = $this->save_options($default);

            $params['message'] = true;
            $params['message_id'] = 'message_'.rand(0, 99);

            if ($res === true) {
                $params['message_type'] = 'updated';
                $params['message_text'] = __(
                    'Options were successfully updated!',
                    $this->get_textdomain()
                );
                $current = $this->get_options();
            }
            else {
                $params['message_type'] = 'error';
                $params['message_text'] = __(
                    'Options were NOT successfully updated!',
                    $this->get_textdomain()
                );
            }
        }

        // Prepare options for rendering
        $params['options'] = $this->prepare_options_for_render($default, $current);

        // Render template
        echo $this->twig->render('options_page.html.twig', $params);
    }

    /**
     * @internal
     * @since 0.1.7
     * @param array $default Default options.
     * @param array $current Currently set options.
     * @return array Returns prepared options for rendering.
     */
    private function prepare_options_for_render($default, $current) {
        $params = array();

        foreach ($default as $option) {
            $param = array();
            $param['key'] = $option->key;
            $param['label'] = $option->label;

            $key = $option->key;
            $value = array_key_exists($key, $current) ? $current[$key] : $option->value;

            switch ($option->type) {
                case \odwp\PluginOption::TYPE_BOOL:
                    $param['is_bool'] = true;
                    $param['value'] = boolval($value);
                    break;

                case \odwp\PluginOption::TYPE_NUMBER:
                    $param['is_number'] = true;
                    $param['value'] = intval($value);
                    break;

                default:
                case \odwp\PluginOption::TYPE_STRING:
                    $param['is_string'] = true;
                    $param['value'] = strval($value);
                    break;
            }

            if (!empty($option->description)) {
                $param['description'] = $option->description;
            }

            $params[] = $param;
        }

        return $params;
    }

    /**
     * @internal
     * @since 0.1.7
     * @param array $default Default options.
     * @return boolean `TRUE` if saving was successfull otherwise `FALSE`.
     */
    private function save_options($default) {
        $updated = array();
        $updated['latest_used_version'] = $this->version;

        foreach ($default as $option) {
            $new_val = filter_input(INPUT_POST, 'option-' . $option->key);

            if ($option->type == \odwp\PluginOption::TYPE_BOOL) {
                $new_val = !is_null($new_val);
            }
            else if (is_null($new_val)) {
                $new_val = $option->value;
            }

            $updated[$option->key] = $new_val;
        }

        return update_option($this->get_id('-options'), $updated);
    }

    /**
     * Uninstall.
     *
     * @since 0.1.7
     * @return void
     */
    public function uninstall() {
        if (!defined('WP_UNINSTALL_PLUGIN')) {
            return;
        }

        // Delete options
        delete_option($this->get_id('-options'));
        // For site options in multisite
        delete_site_option($this->get_id('-options'));
    }
}


<?php
/**
 * This file is part of the MimeMailer package.
 *
 * Copyright (c) 2013-2016 Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The source code of this package is available online at
 * <http://github.com/atelierspierrot/mime-mailer>.
 */

namespace MimeMailer\Transport;

use \MimeMailer\Mailer;
use \MimeMailer\TransportInterface;

/*
PHP Mail function :
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
*/

/**
 * @author  piwi <me@e-piwi.fr>
 */
class MailTransport
    implements TransportInterface
{

    /**
     * Define the `sendmail` path if so
     */
    public function __construct()
    {
        $sendmail_path = Mailer::getInstance()->getOption('sendmail_path');
        if (!empty($sendmail_path)) {
            @ini_set('sendmail_path', $sendmail_path);
        }
    }

    /**
     * Validate this transport way
     *
     * @return bool Must return a boolean after testing the transport way in current envionement
     */
    public function validate()
    {
        return true;
    }

    /**
     * Messages sender : prepare the whole content and send the e-mail
     *
     * @param   string $to
     * @param   string $subject
     * @param   string $message
     * @param   string $additional_headers
     * @param   string $additional_parameters
     * @return  mixed
     * @see     mail()
     */
    public function transport($to, $subject, $message, $additional_headers = '', $additional_parameters = '')
    {
        return mail($to, $subject, $message, $additional_headers, $additional_parameters);
    }
}

// Endfile


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\models;

use dektrium\user\Finder;
use dektrium\user\Mailer;
use yii\base\Model;

/**
 * Model for collecting data on password recovery.
 *
 * @property \dektrium\user\Module $module
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class RecoveryForm extends Model
{
    /** @var string */
    public $email;

    /** @var string */
    public $password;

    /** @var User */
    protected $user;

    /** @var \dektrium\user\Module */
    protected $module;

    /** @var Mailer */
    protected $mailer;

    /** @var Finder */
    protected $finder;

    /**
     * @param Mailer $mailer
     * @param Finder $finder
     * @param array  $config
     */
    public function __construct(Mailer $mailer, Finder $finder, $config = [])
    {
        $this->module = \Yii::$app->getModule('user');
        $this->mailer = $mailer;
        $this->finder = $finder;
        parent::__construct($config);
    }

    /** @inheritdoc */
    public function attributeLabels()
    {
        return [
            'email'    => \Yii::t('user', 'Email'),
            'password' => \Yii::t('user', 'Password'),
        ];
    }

    /** @inheritdoc */
    public function scenarios()
    {
        return [
            'request' => ['email'],
            'reset'   => ['password']
        ];
    }

    /** @inheritdoc */
    public function rules()
    {
        return [
            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'exist',
                'targetClass' => $this->module->modelMap['User'],
                'message' => \Yii::t('user', 'There is no user with this email address')
            ],
            ['email', function ($attribute) {
                $this->user = $this->finder->findUserByEmail($this->email);
                if ($this->user !== null && $this->module->enableConfirmation && !$this->user->getIsConfirmed()) {
                    $this->addError($attribute, \Yii::t('user', 'You need to confirm your email address'));
                }
            }],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Sends recovery message.
     *
     * @return bool
     */
    public function sendRecoveryMessage()
    {
        if ($this->validate()) {
            /** @var Token $token */
            $token = \Yii::createObject([
                'class'   => Token::className(),
                'user_id' => $this->user->id,
                'type'    => Token::TYPE_RECOVERY
            ]);
            $token->save(false);
            $this->mailer->sendRecoveryMessage($this->user, $token);
            \Yii::$app->session->setFlash('info', \Yii::t('user', 'An email has been sent with instructions for resetting your password'));
            return true;
        }

        return false;
    }

    /**
     * Resets user's password.
     *
     * @param  Token $token
     * @return bool
     */
    public function resetPassword(Token $token)
    {
        if (!$this->validate() || $token->user === null) {
            return false;
        }

        if ($token->user->resetPassword($this->password)) {
            \Yii::$app->session->setFlash('success', \Yii::t('user', 'Your password has been changed successfully.'));
            $token->delete();
        } else {
            \Yii::$app->session->setFlash('danger', \Yii::t('user', 'An error occurred and your password has not been changed. Please try again later.'));
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function formName()
    {
        return 'recovery-form';
    }
}


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

namespace cascade\models;

use canis\data\ActiveDataProvider;
use Yii;

/**
 * ObjectFamiliarity is the model class for table "object_familiarity".
 *
 * @property string $object_id
 * @property string $user_id
 * @property string $model
 * @property boolean $watching
 * @property boolean $created
 * @property integer $modified
 * @property integer $accessed
 * @property integer $familiarity
 * @property string $session
 * @property string $last_modified
 * @property string $last_accessed
 * @property string $first_accessed
 * @property User $user
 * @property Registry $object
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class ObjectFamiliarity extends \cascade\components\db\ActiveRecord
{
    const ACCESSED_FAMILIARITY = 1;
    const MODIFIED_FAMILIARITY = 2;
    const CREATED_FAMILIARITY = 3;

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

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'object_familiarity';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['object_id', 'user_id', 'familiarity'], 'required'],
            [['watching', 'created'], 'boolean'],
            [['modified', 'accessed', 'familiarity'], 'integer'],
            [['last_modified', 'last_accessed', 'first_accessed'], 'safe'],
            [['object_id', 'user_id'], 'string', 'max' => 36],
            [['model'], 'string', 'max' => 255],
            [['session'], 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'object_id' => 'Object ID',
            'user_id' => 'User ID',
            'model' => 'Model',
            'watching' => 'Watching',
            'created' => 'Created',
            'modified' => 'Modified',
            'accessed' => 'Accessed',
            'familiarity' => 'Familiarity',
            'session' => 'Session',
            'last_modified' => 'Last Modified',
            'last_accessed' => 'Last Accessed',
            'first_accessed' => 'First Accessed',
        ];
    }

    /**
     * Get user.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
     * Get object.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getObject()
    {
        return $this->hasOne(Registry::className(), ['id' => 'object_id']);
    }

    /**
     * [[@doctodo method_description:created]].
     *
     * @param unknown $object
     * @param unknown $user   (optional)
     *
     * @return unknown
     */
    public static function created($object, $user = null)
    {
        $objectId = $object->id;
        $objectModel = addslashes($object->modelAlias);
        if (is_null($user) and isset(Yii::$app->user)) {
            $user = Yii::$app->user->id;
        }
        if (is_object($user)) {
            $user = $user->primaryKey;
        }
        if (empty($user) or empty(Yii::$app->session)) {
            return false;
        }
        $session = Yii::$app->session->id;

        $tableName = self::tableName();
        $familiarityUp = self::CREATED_FAMILIARITY;
        $query = "INSERT INTO `{$tableName}` SET `created`=1, `familiarity`={$familiarityUp}, `last_modified`=NOW(), `last_accessed`=NOW(), `first_accessed`=NOW(), `object_id`='{$objectId}', `model`='{$objectModel}', `user_id`='{$user}' ON DUPLICATE KEY UPDATE `modified`=`modified`+1, `familiarity`=`familiarity`+{$familiarityUp}, `session`='{$session}',  last_modified=NOW();";
        $command = Yii::$app->db->createCommand($query);

        return $command->execute();
    }

    /**
     * [[@doctodo method_description:modified]].
     *
     * @param unknown $object
     * @param unknown $user   (optional)
     *
     * @return unknown
     */
    public static function modified($object, $user = null)
    {
        $objectId = $object->id;
        $objectModel = addslashes($object->modelAlias);
        if (is_null($user) and isset(Yii::$app->user)) {
            $user = Yii::$app->user->id;
        }
        if (is_object($user)) {
            $user = $user->primaryKey;
        }
        if (empty($user) or empty(Yii::$app->session)) {
            return false;
        }
        $session = Yii::$app->session->id;

        $tableName = self::tableName();
        $familiarityUp = self::MODIFIED_FAMILIARITY;
        $query = "INSERT INTO `{$tableName}` SET `modified`=1, `familiarity`={$familiarityUp}, `last_modified`=NOW(), `last_accessed`=NOW(), `first_accessed`=NOW(), `object_id`='{$objectId}', `model`='{$objectModel}', `user_id`='{$user}', `session`='{$session}' ON DUPLICATE KEY UPDATE `modified`=`modified`+1, `familiarity`=`familiarity`+{$familiarityUp}, `session`='{$session}',  last_modified=NOW(), last_accessed=NOW();";
        $command = Yii::$app->db->createCommand($query);

        return $command->execute();
    }

    /**
     * [[@doctodo method_description:accessed]].
     *
     * @param unknown $object
     * @param unknown $user   (optional)
     *
     * @return unknown
     */
    public static function accessed($object, $user = null)
    {
        $objectId = $object->id;
        $objectModel = addslashes($object->modelAlias);
        if (is_null($user) and isset(Yii::$app->user)) {
            $user = Yii::$app->user->id;
        }
        if (is_object($user)) {
            $user = $user->primaryKey;
        }
        if (empty($user) or empty(Yii::$app->session)) {
            return false;
        }
        $session = Yii::$app->session->id;

        $tableName = self::tableName();
        $familiarityUp = self::ACCESSED_FAMILIARITY;
        $query = "INSERT INTO `{$tableName}` SET `accessed`=1, `familiarity`={$familiarityUp}, `last_accessed`=NOW(), `first_accessed`=NOW(), `object_id`='{$objectId}', `model`='{$objectModel}', `user_id`='{$user}', `session`='{$session}' ON DUPLICATE KEY UPDATE `accessed`=IF((`session` IS NULL OR `session` != '{$session}'), `accessed`+1, `accessed`), `familiarity`=IF((`session` IS NULL OR `session` != '{$session}'), `familiarity`+{$familiarityUp}, `familiarity`), `session`='{$session}', last_accessed=NOW();";
        $command = Yii::$app->db->createCommand($query);

        return $command->execute();
    }

    /**
     * [[@doctodo method_description:familiarObjects]].
     *
     * @param [[@doctodo param_type:model]] $model [[@doctodo param_description:model]]
     * @param integer                       $limit [[@doctodo param_description:limit]] [optional]
     *
     * @return [[@doctodo return_type:familiarObjects]] [[@doctodo return_description:familiarObjects]]
     */
    public static function familiarObjects($model, $limit = 10)
    {
        $queryModel = new $model();
        $query = $model::find();
        $query->with(['familiarity']);

        if (!is_null($limit)) {
            $query->limit = $limit;
        }
        $query->orderBy = ['familiarity.familiarity' => SORT_DESC, 'familiarity.last_accessed' => SORT_DESC];

        return $query->all();
    }

    /**
     * [[@doctodo method_description:familiarObjectsProvider]].
     *
     * @param [[@doctodo param_type:model]] $model [[@doctodo param_description:model]]
     * @param [[@doctodo param_type:state]] $state [[@doctodo param_description:state]]
     *
     * @return [[@doctodo return_type:familiarObjectsProvider]] [[@doctodo return_description:familiarObjectsProvider]]
     */
    public static function familiarObjectsProvider($model, $state)
    {
        $queryModel = new $model();
        $query = $model::find();
        $query->with(['familiarity']);

        return new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                ],
                'state' => $state,
                'sort' => [
                    'defaultOrder' => array_merge(['familiarity.familiarity' => SORT_DESC, 'familiarity.last_accessed' => SORT_DESC], $queryModel->defaultOrder),
                    'attributes' => [
                        'familiarity' => [
                            'asc' => array_merge(['familiarity.familiarity' => SORT_ASC], $queryModel->defaultOrder),
                            'desc' => array_merge(['familiarity.familiarity' => SORT_DESC], $queryModel->defaultOrder),
                        ],
                        'last_accessed' => [
                            'asc' => array_merge(['familiarity.last_accessed' => SORT_ASC], $queryModel->defaultOrder),
                            'desc' => array_merge(['familiarity.last_accessed' => SORT_DESC], $queryModel->defaultOrder),
                        ],
                        '*',
                    ],
                ],
            ]);
    }

    /**
     * [[@doctodo method_description:familiarObjectsList]].
     *
     * @param [[@doctodo param_type:model]] $model [[@doctodo param_description:model]]
     * @param integer                       $limit [[@doctodo param_description:limit]] [optional]
     *
     * @return [[@doctodo return_type:familiarObjectsList]] [[@doctodo return_description:familiarObjectsList]]
     */
    public static function familiarObjectsList($model, $limit = 10)
    {
        $f = self::familiarObjects($model, $limit);

        return ArrayHelper::map($f, 'id', 'descriptor');
    }
}


<?php

/**
 * Ldap
 *
 * @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.2
 */
namespace Venus\lib;

use \Venus\core\Config as Config;

/**
 * Ldap library
 *
 * @category  	core
 * @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.2
 */
class Ldap
{
    /**
     * connection at ldap server
     *
     * @access private
     * @var    resource
     */
	private $_rConnect;

	/**
	 * the databse to connect
	 *
	 * @access private
	 * @var    string
	 */
	private $_sBase;

	/**
	 * if the user is connected or not
	 *
	 * @access private
	 * @var    bool
	 */
	private $_bConnected = false;

	/**
	 * constructor of class
	 *
	 * @access public
	 * @return \Venus\lib\Ldap
	 */
	public function __construct()
	{
	    $oDbConf = Config::get('ldap')->configuration;

		$this->_sBase = $oDbConf->base;

		$this->_rConnect = ldap_connect($oDbConf->host, $oDbConf->port);

		$this->set_option(LDAP_OPT_REFERRALS, 0);
	}

	/**
	 * Get groups
	 *
	 * @access public
	 * @return array
	 */
    public function getGroups() : array
    {
        $rSearch = ldap_search( $this->_rConnect , $this->_sBase , "objectclass=group" , array("cn") );
        $aEntries = ldap_get_entries($this->_rConnect, $rSearch);
        $aGroups = array();

        for ( $i = 0 ; $i < $aEntries["count"] ; $i++ ) {

            $aGroups[] = utf8_encode($aEntries[$i]["dn"]);
        }

        return $aGroups;
    }

    /**
     * Authentification in Ldap
     *
     * @access public
     * @param  string $sUser
     * @param  string $sPassword
     * @return \Venus\lib\Ldap
     */
	public function bind($sUser, $sPassword) : Ldap
	{
		return $this->_bConnected = ldap_bind($this->_rConnect, $sUser, $sPassword);
		return $this;
	}

	/**
	 * Close authentification in Ldap
	 *
	 * @access public
	 * @return bool
	 */
	public function unbind() : bool
	{
	    if ($this->_bConnected) { return $this->_bConnected = ldap_unbind($this->_rConnect); }
	    else { return true; }
	}

	/**
	 * destructor of the class
	 *
	 * @access public
	 * @return void
	 */
	public function __destruct()
	{
		$this->close();
	}

	/**
	 * Call a classic ldap method. You have to ignore the ldap_ part
	 * You put all parameters without the connector
	 *
	 * @access public
	 * @param  string $sFunctionName
	 * @param  array $aArgv
	 * @return void
	 */
	public function __call(string $sFunctionName, array $aArgv)
	{
		array_unshift($argv, $this->_rConnect);
		return call_user_func_array('ldap_'.$sFunctionName, $aArgv);
	}

	/**
	 * get in Ldap
	 *
	 * @access public
	 * @param  string $sFilter
	 * @param  array $aAttributes
	 * @return array
	 */
	public function get(string $sFilter, array $aAttributes)
	{
		$res = $this->search($sFilter, $aAttributes);

		return $this->getEntries($res, $aAttributes);
	}

	/**
	 * search in Ldap
	 *
	 * @access public
	 * @param  string $sFilter
	 * @param  array $aAttributes
	 * @return resource
	 */
	public function search(string $sFilter, array $aAttributes)
	{
		return ldap_search($this->_rConnect, $this->_sBase, $sFilter, $aAttributes);
	}

	/**
	 * get in Ldap
	 *
	 * @access public
	 * @param  resource $rResultIdentifier
	 * @param  array $aAttributes
	 * @return array
	 */
	public function getEntries($rResultIdentifier, array $aAttributes) : array
	{
		$aEntries = ldap_get_entries($this->_rConnect, $rResultIdentifier);

		$aMask = array_flip($aAttributes);

		$aResultSet = array();

		for ($i = 0, $count = $aEntries['count']; $i < $count; ++$i) {

			$aResultSet[$i] = array_intersect_key($aEntries[$i], $aMask);

			foreach($aResultSet[$i] as &$aValues) {

				unset($aValues['count']);
			}
		}

		return $aResultSet;
	}
}


<?php

namespace ZF2ValidatorBuilder;

/**
 * Toolset to apply InputFilters to form elements
 * @author Cyberrebell
 *
 */
class ValidatorBuilder
{
    protected $form;

    /**
     * @param \Zend\Form\Form $form
     */
    function __construct(\Zend\Form\Form $form) {
        $this->form = $form;
    }

    /**
     * Set element required
     * frontend & backend validation
     * @param \Zend\Form\Element $element
     */
    public function setElementRequired(\Zend\Form\Element $element) {
        $element->setAttribute('required', 'true'); //set browser validation
        $this->form->getInputFilter()->get($element->getAttribute('name'))->setAllowEmpty(false); //set backend requirement
    }

    public function attachEmailAddressValidator(\Zend\Form\Element $element) {
        $elementValidatorChain = $this->getElementValidatorChain($element);
        $elementValidatorChain->attachByName('EmailAddress');
    }

    public function attachEqualsValidator(\Zend\Form\Element $element, $value) {
        $elementValidatorChain = $this->getElementValidatorChain($element);
        $elementValidatorChain->attachByName('Regex', ['pattern' => '/' . $value . '/']);
    }

    public function attachIdenticalValidator(\Zend\Form\Element $elementOne, \Zend\Form\Element $elementTwo) {
        $elementTwoValidatorChain = $this->getElementValidatorChain($elementTwo);
        $elementTwoValidatorChain->attachByName('Identical', ['token' => $elementOne->getAttribute('name'), 'strict' => true]);
    }

    public function attachStringLengthValidator(\Zend\Form\Element $element, $min = NULL, $max = NULL) {
        $elementValidatorChain = $this->getElementValidatorChain($element);
        $options = [];
        if ($min !== NULL) {
            $options['min'] = $min;
        }
        if ($max !== NULL) {
            $options['max'] = $max;
        }
        $elementValidatorChain->attachByName('StringLength', $options);
    }

    /**
     * Get elements validator chain
     * @param \Zend\Form\Element $element
     * @return \Zend\Validator\ValidatorChain
     */
    protected function getElementValidatorChain(\Zend\Form\Element $element) {
        $elementName = $element->getAttribute('name');
        return $this->form->getInputFilter()->get($elementName)->getValidatorChain();
    }
}


<?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 Controller\Theme;

use RedKiteCms\Rendering\Controller\Theme\SaveThemeController as BaseSaveThemeController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to save a site as a theme
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Theme
 */
class SaveThemeController extends BaseSaveThemeController
{
    /**
     * Save a site as a theme action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function saveAction(Request $request, Application $app)
    {
        $options = array(
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
            "plugin_manager" => $app["red_kite_cms.plugin_manager"],
            "theme_deployer" => $app["red_kite_cms.theme_deployer"],
            "page" => clone($app["red_kite_cms.page"]),
        );

        return parent::save($options);
    }
}