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

namespace cascade\components\web\form\fields;

use canis\base\exceptions\Exception;
use canis\helpers\Html;

/**
 * Model [[@doctodo class_description:cascade\components\web\form\fields\Model]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Model extends Base
{
    /**
     * @var [[@doctodo var_type:fileStorageWidgetClass]] [[@doctodo var_description:fileStorageWidgetClass]]
     */
    public $fileStorageWidgetClass = 'cascade\components\web\widgets\form\FileStorage';
    /**
     * @var [[@doctodo var_type:_fieldConfig]] [[@doctodo var_description:_fieldConfig]]
     */
    protected $_fieldConfig = [];
    /**
     * Get field config.
     *
     * @return [[@doctodo return_type:getFieldConfig]] [[@doctodo return_description:getFieldConfig]]
     */
    public function getFieldConfig()
    {
        return array_merge([
                'template' => "
{input}
\n
{error}
",
                'labelOptions' => ['class' => "control-label"],
        ], $this->_fieldConfig);
    }

    /**
     * Set field config.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setFieldConfig($value)
    {
        $this->_fieldConfig = $value;
    }
    /**
     * [[@doctodo method_description:generate]].
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return unknown
     *
     */
    public function generate()
    {
        $model = $this->model;
        if (!$this->generator) {
            throw new Exception("Unable to find generator.");
        }
        if (!$this->generator->form) {
            throw new Exception("Unable to find generator form.");
        }
        $form = $this->generator->form;
        $pre = $post = null;
        $field = $this->getModelFieldName();
        $fieldConfig = $this->fieldConfig;
        $templatePrefix = '';
        if ($this->showLabel) {
            $templatePrefix = "{label}\n";
            $fieldConfig['template'] = $templatePrefix . $fieldConfig['template'];
        }
        $item = $form->field($model, $field, $fieldConfig);
        $item->inputOptions = & $this->htmlOptions;
        $item->inputOptions['value'] = $fieldConfig['value'] = $this->modelField->format->formValue;

        Html::addCssClass($this->htmlOptions, 'form-control');
        if (substr($this->type, 0, 5) === 'smart') {
            $this->type = lcfirst(substr($this->type, 5));
            if (isset($this->smartOptions['watchField'])) {
                $watchFieldId = $this->neightborFieldId($this->smartOptions['watchField']);
                if (!$watchFieldId) {
                    unset($this->smartOptions['watchField']);
                } else {
                    $this->smartOptions['watchField'] = '#' . $watchFieldId;
                }
            }
            $this->htmlOptions['data-value'] = $fieldConfig['value']; //Html::getAttributeValue($model, $field)
            $this->htmlOptions['data-smart'] = json_encode($this->smartOptions);
        }

        switch ($this->type) {
        case 'checkBox':
            $item->checkbox();
            break;
        case 'radioButton':
            $item->radio();
            break;
        case 'checkBoxList':
            $item->checkboxList($this->options);
            break;
        case 'radioButtonList':
        case 'boolean':
            if ($this->type === 'boolean') {
                $this->showLabel = false;
                if (!isset($this->options)) {
                    $this->showLabel = true;
                    $this->options = [1 => 'Yes', 0 => 'No'];
                }
                Html::addCssClass($this->htmlOptions, 'btn-group');
                Html::removeCssClass($this->htmlOptions, 'form-control');
                $this->htmlOptions['data-toggle'] = 'buttons';
                $encode = !isset($this->htmlOptions['encode']) || $this->htmlOptions['encode'];
                $this->htmlOptions['item'] = function ($index, $label, $name, $checked, $value) use ($encode) {
                    $itemOptions = ['container' => false, 'labelOptions' => ['class' => 'btn-primary btn']];
                    if ($checked) {
                        Html::addCssClass($itemOptions['labelOptions'], 'active');
                    }

                    return Html::radio($name, $checked, array_merge($itemOptions, [
                        'value' => $value,
                        'label' => $encode ? Html::encode($label) : $label,
                    ]));
                };
            }
            $item->radioList($this->options);
            break;
        case 'dropDownList':
        case 'smartDropDownList':
            $item->dropDownList($this->options);
            break;
        case 'listBox':
            $item->listBox($this->options);
            break;
        case 'file':
            // $item->fileInput();
            Html::removeCssClass($this->htmlOptions, 'form-control');
            $fileStorageWidgetClass = $this->fileStorageWidgetClass;
            $item = $fileStorageWidgetClass::widget(['item' => $item]);
            break;
        case 'hidden':
            $this->showLabel = false;
            $item = Html::activeHiddenInput($model, $field, $this->htmlOptions);
            break;
        case 'password':
            $item->password();
            break;
        case 'date':
            //$item->template = $templatePrefix . "
{input}
\n
{error}
";
            if (!$item->inputGroupPostfix) {
                $item->inputGroupPostfix = "";
            }
            Html::addCssClass($item->inputGroupHtmlOptions, 'date');
            break;
        case 'textarea':
            $item->textarea();
            break;
        case 'rich':
            Html::addCssClass($this->htmlOptions, 'rich');
            $editorSettings = [
                ];
            $this->htmlOptions['data-editor'] = Json::encode($editorSettings);
            $item = Html::activeTextArea($model, $field, $this->htmlOptions);
            break;
        }
        if (!empty($item)) {
            return $pre . $item . $post;
        }

        return false;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

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

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

Open-Orchestra

Open-Orchestra est une puissante plateforme d’intégration web permettant d’accélérer la
    construction d’écosystèmes digitaux pérennes. Cette solution issue de l’expérience d’Interakting
    dans le développement de plateformes internationales est disponible sous licence Open-Source.

Développé sur Symfony2 et mongoDB dans le strict respect des standards et bonnes pratiques du
    framework. Open-Orchestra est rapide, hautement adaptable et extensible, multi-sites et
    multi-devices.

Open-Orchestra offre des fonctionnalités de CMS avancées et des composants d’intégration SI
    internes et externes hautement configurables, modulaires, taillés pour les fortes charges et la
    sécurité.

Une solution ciblée :

Projet où «l’expérience», qu’elle soit client, collaborateur, partenaires ou distributeurs
        est au cœur de la problématique.

Projet à dimension internationale nécessitant des économies d’échelle.

Projets complexes et où les systèmes d’informations internes et partenaires sont fortement
         sollicités.

Projet dont l’objectif est de bâtir des écosystèmes digitaux (e-commerce, communication,
        référentiel, selfcare, mobilité, distribution, …) cohérents avec des synergies fonctionnelles et
        technologiques.

Notre promesse : « Economies d’échelle et mutualisation des investissements pour une expérience
    web cohérente sur tous les canaux fixe mobile, tablette, TV, bornes… »

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

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

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

Open-Orchestra

Open Orchestra is a powerful web integration platform for accelerating
    the construction of perennial digital ecosystems. This solution outcome of the Interakting experience
    in the development of international platforms is available in open source license.

Developed with Symfony2 and MongoDB in strict compliance to the standards and best practices
    of the framework. Open Orchestra is fast, highly adaptable and expandable, multi-site and multi-devices.

A targeted solution:

Project where experience, whether customer, contributor, partner or distributor is at the heart of the problematic.

Project with a international dimension requiring economies of scale.

Complex projects where internal information systems and partners are highly asked.

Project which aims to build digital ecosystems (e-commerce, communication, reference, selfcare, mobility, distribution, ...)
        consistent with the functional and technological synergies.

Our promise: « Economies of scale and pooling of investments for a consistent
    web experience across all channels fixed mobile, tablet, TV, bollards ... »

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

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

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

Open-Orchestra

Offene Orchestra ist ein leistungsfähiges Web-Integrationsplattform zur Beschleunigung der Bau von mehrjährige digitale Ökosysteme.
     Diese Lösung von Interakting Erfahrung in der Entwicklung der internationalen Plattformen ist verfügbar unter der Open Source Lizenz.

In strikter Übereinstimmung mit den Standards und Best Practices Framework entwickelt auf Symfony2 und MongoDB.
    Offene Orchestra ist schnell, sehr anpassungsfähig und erweiterbar, Multi-Site und Multi-Geräte.

Offene Orchestra CMS bietet erweiterte Funktionen und SI internen und externen Integrationskomponenten
    in hohem Maße konfigurierbar, modular, hohen Belastungen und Sicherheit zugeschnitten.

Eine gezielte Lösung :

Projekt, wo «Erfahrung», ob Kunde, Mitarbeiter, Partner oder Händler ist der Kern des Problems.

Internationale Projekt Skaleneffekte erfordern.

Komplexe Projekte, bei denen interne Informationssysteme und Partner sind hoch beanspruchte.

Projekt, dessen Ziel ist es, digitale Ökosysteme (E-Commerce, Kommunikation, Referenz, Selbst-Pflege, Mobilität, Vertrieb, ...),
        die mit den funktionalen und technologischen Synergien aufzubauen.

Unser versprechen : « Skaleneffekte und die Bündelung von Investitionen für eine konsistente Web-Erfahrung auf allen Kanälen Fixed Mobile,
    Tablet, TV, Poller ... »

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

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

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

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

        $main = new Area();
        $main->addBlock($nodeHomeBlock);
        $main->addBlock($this->fixture->getReference('Wysiwyg logo'.'-'.$language));

        $nodeHome = $this->createBaseNode();
        $keyReference = "node-".NodeInterface::ROOT_NODE_ID.'-'.$language.'-'.$this->version;
        if($this->fixture->hasReference($keyReference)) {
            $nodeHome = $this->fixture->getReference($keyReference);

        }
        $nodeHome->setArea('main', $main);

        $nodeHome->setLanguage($language);
        $nodeHome->setNodeId(NodeInterface::ROOT_NODE_ID);
        $nodeHome->setCreatedBy('fake_admin');
        $nodeHome->setParentId(NodeInterface::ROOT_PARENT_ID);
        $nodeHome->setOrder(0);
        $nodeHome->setRoutePattern($routePattern);
        $nodeHome->setInFooter(false);
        $nodeHome->setInMenu(true);
        $nodeHome->setSitemapChangefreq('hourly');
        $nodeHome->setSitemapPriority('0.8');
        $nodeHome->setName('Orchestra ?');
        $nodeHome->setVersionName($this->getVersionName($nodeHome));
        $nodeHome->setVersion($this->version);
        $nodeHome->setStatus($this->fixture->getReference($this->status));

        return $nodeHome;
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

/**
 * @link http://redis.io/commands/hmset
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class HMSET extends RedisCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'HMSET';
    }

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (count($arguments) === 2 && is_array($arguments[1])) {
            $flattenedKVs = array($arguments[0]);
            $args = $arguments[1];

            foreach ($args as $k => $v) {
                $flattenedKVs[] = $k;
                $flattenedKVs[] = $v;
            }

            $arguments = $flattenedKVs;
        }

        parent::setArguments($arguments);
    }
}


<?php

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

namespace ItePHP\Component\Form;

use ItePHP\Validator\ValidatorAbstract;

/**
 * FormBuilder field
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
abstract class FormField{

    /**
     * @var mixed[]
     */
	private $tags;

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

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

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

	/**
	 * @param mixed[] $options - array with configure data. All field is optional eg:
	 * [
	 * 	'name'=>'{text}' //tag name
	 * 	,'validator'=>'{text}' //validator class name
	 * 	,'id'=>'{text}' //tag id
	 * 	,'value'=>'{text}' //tag value
	 * 	,'required'=>{boolean} //tag required
	 * 	,...
	 * ]
	 */
	public function __construct($options){

		if(isset($options['validator'])){
			$this->validator=$options['validator'];
			unset($options['validator']);
		}

		if(isset($options['label'])){
			$this->label=$options['label'];
			unset($options['label']);
		}

		$options+=[
			'value'=>''
			,'name'=>null
			,'id'=>null
			,'class'=>''
			,'required'=>false
			];

		$this->tags=$options;

		$this->setRequired($this->isRequired());//invoke configure validator by execute setters

	}

	/**
	 * Set html tag name
	 *
	 * @param string $name - value of tag name:
	 */
	public function setName($name){
		$this->tags['name']=$name;
	}

	/**
	 * Get value of html tag name
	 *
	 * @return string
	 */
	public function getName(){
		return $this->tags['name'];
	}

	/**
	 * Set html tag id
	 *
	 * @param string $id - value of tag id:
	 */
	public function setId($id){
		$this->tags['id']=$id;
	}

	/**
	 * Get value of html tag id
	 *
	 * @return string
	 */
	public function getId(){
		return $this->tags['id'];
	}

	/**
	 * Set validator class rule
	 *
	 * @param ValidatorAbstract $validator - validator class
	 */
	public function setValidator($validator=null){
		$this->validator=$validator;
	}

	/**
	 * Get validator class
	 *
	 * @return ValidatorAbstract
	 */
	public function getValidator(){
		return $this->validator;
	}

	/**
	 * Add part html tag class
	 *
	 * @param string $name - class name:
	 */
	public function addClass($name){
		$classParts=explode(' ',$this->tags['class']);
		foreach($classParts as $part){
			if($name==$part)
				return;
		}

		$this->tags['class'].=' '.$name;
		$this->tags['class']=trim($this->tags['class']);
	}

	/**
	 * Remove part html tag class
	 *
	 * @param string $name - class name:
	 */
	public function removeClass($name){
		$classParts=explode(' ',$this->tags['class']);
		$className='';
		foreach($classParts as $part){
			if($name!=$part){
				$className.=' '.$part;
			}
		}

		$this->tags['class']=trim($className);

	}

	/**
	 * Get value of html tag class
	 *
	 * @return string
	 */
	public function getClass(){
		return  $this->tags['class'];
	}

	/**
	 * Set label name for field
	 *
	 * @param string $label
	 */
	public function setLabel($label){
		$this->label=$label;
	}

	/**
	 * Get value of label field
	 *
	 * @return string
	 */
	public function getLabel(){
		return $this->label;
	}

	/**
	 * Set html tag required
	 *
	 * @param bool $flag - if true then required else optional
	 */
	public function setRequired($flag){
		$this->tags['required']=$flag;
		if($this->validator){
			$this->validator->setOption('empty',!$flag);
		}
	}

	/**
	 * Get value of html tag required
	 *
	 * @return bool
	 */
	public function isRequired(){
		return $this->tags['required'];
	}

	/**
	 * Set html tag
	 *
	 * @param string $name - tag name
	 * @param mixed $value - value of tag
	 */
	public function setTag($name,$value){
		$this->tags[$name]=$value;
	}

    /**
     * Get html tag
     *
     * @param string $name - tag name
     * @return mixed
     * @throws AttributeNotFoundException
     */
	public function getTag($name){
	    if(!isset($this->tags[$name])){
	        throw new AttributeNotFoundException($name);
        }
		return $this->tags[$name];
	}

	/**
	 * Get all html tags
	 *
	 * @return mixed[]
	 */
	public function getTags(){
		return $this->tags;
	}

	/**
	 * Check valid field
	 *
	 * @return boolean
	 */
	public function isValid(){
		return $this->isValid;
	}

	/**
	 * Get error message
	 *
	 * @return string
	 */
	public function getError(){
		return $this->error;
	}

	/**
	 * Set error message
	 *
	 * @param string $error - message
	 */
	public function setError($error){
		$this->error=$error;
		$this->isValid=false;
	}

	/**
	 * Implement render html label and field
	 *
	 * @return string
	 */
	abstract public function render();

	/**
	 * Set confirmed data
	 *
	 * @param mixed $data - confirmed data
	 */
	abstract public function setData($data);

	/**
	 * Get value field
	 *
	 * @return mixed
	 */
	abstract public function getData();

	/**
	 * Remove field data
	 */
	abstract public function clearData();

	/**
	 * Implement render html field
	 *
	 * @return string
	 */
	abstract public function componentRender();

	/**
	 * implement render html label
	 *
	 * @return string
	 */
	abstract public function labelRender();

}


<?php

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

namespace Predis\Connection\Cluster;

use Predis\ClientException;
use Predis\Cluster\RedisStrategy as RedisClusterStrategy;
use Predis\Cluster\SlotMap;
use Predis\Cluster\StrategyInterface;
use Predis\Command\CommandInterface;
use Predis\Command\RawCommand;
use Predis\Connection\ConnectionException;
use Predis\Connection\FactoryInterface;
use Predis\Connection\NodeConnectionInterface;
use Predis\NotSupportedException;
use Predis\Response\ErrorInterface as ErrorResponseInterface;

/**
 * Abstraction for a Redis-backed cluster of nodes (Redis >= 3.0.0).
 *
 * This connection backend offers smart support for redis-cluster by handling
 * automatic slots map (re)generation upon -MOVED or -ASK responses returned by
 * Redis when redirecting a client to a different node.
 *
 * The cluster can be pre-initialized using only a subset of the actual nodes in
 * the cluster, Predis will do the rest by adjusting the slots map and creating
 * the missing underlying connection instances on the fly.
 *
 * It is possible to pre-associate connections to a slots range with the "slots"
 * parameter in the form "$first-$last". This can greatly reduce runtime node
 * guessing and redirections.
 *
 * It is also possible to ask for the full and updated slots map directly to one
 * of the nodes and optionally enable such a behaviour upon -MOVED redirections.
 * Asking for the cluster configuration to Redis is actually done by issuing a
 * CLUSTER SLOTS command to a random node in the pool.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class RedisCluster implements ClusterInterface, \IteratorAggregate, \Countable
{
    private $useClusterSlots = true;
    private $pool = array();
    private $slots = array();
    private $slotmap;
    private $strategy;
    private $connections;
    private $retryLimit = 5;

    /**
     * @param FactoryInterface  $connections Optional connection factory.
     * @param StrategyInterface $strategy    Optional cluster strategy.
     */
    public function __construct(
        FactoryInterface $connections,
        StrategyInterface $strategy = null
    ) {
        $this->connections = $connections;
        $this->strategy = $strategy ?: new RedisClusterStrategy();
        $this->slotmap = new SlotMap();
    }

    /**
     * Sets the maximum number of retries for commands upon server failure.
     *
     * -1 = unlimited retry attempts
     *  0 = no retry attempts (fails immediatly)
     *  n = fail only after n retry attempts
     *
     * @param int $retry Number of retry attempts.
     */
    public function setRetryLimit($retry)
    {
        $this->retryLimit = (int) $retry;
    }

    /**
     * {@inheritdoc}
     */
    public function isConnected()
    {
        foreach ($this->pool as $connection) {
            if ($connection->isConnected()) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        if ($connection = $this->getRandomConnection()) {
            $connection->connect();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function disconnect()
    {
        foreach ($this->pool as $connection) {
            $connection->disconnect();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function add(NodeConnectionInterface $connection)
    {
        $this->pool[(string) $connection] = $connection;
        $this->slotmap->reset();
    }

    /**
     * {@inheritdoc}
     */
    public function remove(NodeConnectionInterface $connection)
    {
        if (false !== $id = array_search($connection, $this->pool, true)) {
            $this->slotmap->reset();
            $this->slots = array_diff($this->slots, array($connection));
            unset($this->pool[$id]);

            return true;
        }

        return false;
    }

    /**
     * Removes a connection instance by using its identifier.
     *
     * @param string $connectionID Connection identifier.
     *
     * @return bool True if the connection was in the pool.
     */
    public function removeById($connectionID)
    {
        if (isset($this->pool[$connectionID])) {
            $this->slotmap->reset();
            $this->slots = array_diff($this->slots, array($connectionID));
            unset($this->pool[$connectionID]);

            return true;
        }

        return false;
    }

    /**
     * Generates the current slots map by guessing the cluster configuration out
     * of the connection parameters of the connections in the pool.
     *
     * Generation is based on the same algorithm used by Redis to generate the
     * cluster, so it is most effective when all of the connections supplied on
     * initialization have the "slots" parameter properly set accordingly to the
     * current cluster configuration.
     */
    public function buildSlotMap()
    {
        $this->slotmap->reset();

        foreach ($this->pool as $connectionID => $connection) {
            $parameters = $connection->getParameters();

            if (!isset($parameters->slots)) {
                continue;
            }

            foreach (explode(',', $parameters->slots) as $slotRange) {
                $slots = explode('-', $slotRange, 2);

                if (!isset($slots[1])) {
                    $slots[1] = $slots[0];
                }

                $this->slotmap->setSlots($slots[0], $slots[1], $connectionID);
            }
        }
    }

    /**
     * Queries the specified node of the cluster to fetch the updated slots map.
     *
     * When the connection fails, this method tries to execute the same command
     * on a different connection picked at random from the pool of known nodes,
     * up until the retry limit is reached.
     *
     * @param NodeConnectionInterface $connection Connection to a node of the cluster.
     *
     * @return mixed
     */
    private function queryClusterNodeForSlotMap(NodeConnectionInterface $connection)
    {
        $retries = 0;
        $command = RawCommand::create('CLUSTER', 'SLOTS');

        RETRY_COMMAND: {
            try {
                $response = $connection->executeCommand($command);
            } catch (ConnectionException $exception) {
                $connection = $exception->getConnection();
                $connection->disconnect();

                $this->remove($connection);

                if ($retries === $this->retryLimit) {
                    throw $exception;
                }

                if (!$connection = $this->getRandomConnection()) {
                    throw new ClientException('No connections left in the pool for `CLUSTER SLOTS`');
                }

                ++$retries;
                goto RETRY_COMMAND;
            }
        }

        return $response;
    }

    /**
     * Generates an updated slots map fetching the cluster configuration using
     * the CLUSTER SLOTS command against the specified node or a random one from
     * the pool.
     *
     * @param NodeConnectionInterface $connection Optional connection instance.
     */
    public function askSlotMap(NodeConnectionInterface $connection = null)
    {
        if (!$connection && !$connection = $this->getRandomConnection()) {
            return;
        }

        $this->slotmap->reset();

        $response = $this->queryClusterNodeForSlotMap($connection);

        foreach ($response as $slots) {
            // We only support master servers for now, so we ignore subsequent
            // elements in the $slots array identifying slaves.
            list($start, $end, $master) = $slots;

            if ($master[0] === '') {
                $this->slotmap->setSlots($start, $end, (string) $connection);
            } else {
                $this->slotmap->setSlots($start, $end, "{$master[0]}:{$master[1]}");
            }
        }
    }

    /**
     * Guesses the correct node associated to a given slot using a precalculated
     * slots map, falling back to the same logic used by Redis to initialize a
     * cluster (best-effort).
     *
     * @param int $slot Slot index.
     *
     * @return string Connection ID.
     */
    protected function guessNode($slot)
    {
        if (!$this->pool) {
            throw new ClientException('No connections available in the pool');
        }

        if ($this->slotmap->isEmpty()) {
            $this->buildSlotMap();
        }

        if ($node = $this->slotmap[$slot]) {
            return $node;
        }

        $count = count($this->pool);
        $index = min((int) ($slot / (int) (16384 / $count)), $count - 1);
        $nodes = array_keys($this->pool);

        return $nodes[$index];
    }

    /**
     * Creates a new connection instance from the given connection ID.
     *
     * @param string $connectionID Identifier for the connection.
     *
     * @return NodeConnectionInterface
     */
    protected function createConnection($connectionID)
    {
        $separator = strrpos($connectionID, ':');

        return $this->connections->create(array(
            'host' => substr($connectionID, 0, $separator),
            'port' => substr($connectionID, $separator + 1),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getConnectionByCommand(CommandInterface $command)
    {
        $slot = $this->strategy->getSlot($command);

        if (!isset($slot)) {
            throw new NotSupportedException(
                "Cannot use '{$command->getId()}' with redis-cluster."
            );
        }

        if (isset($this->slots[$slot])) {
            return $this->slots[$slot];
        } else {
            return $this->getConnectionBySlot($slot);
        }
    }

    /**
     * Returns the connection currently associated to a given slot.
     *
     * @param int $slot Slot index.
     *
     * @throws \OutOfBoundsException
     *
     * @return NodeConnectionInterface
     */
    public function getConnectionBySlot($slot)
    {
        if (!SlotMap::isValid($slot)) {
            throw new \OutOfBoundsException("Invalid slot [$slot].");
        }

        if (isset($this->slots[$slot])) {
            return $this->slots[$slot];
        }

        $connectionID = $this->guessNode($slot);

        if (!$connection = $this->getConnectionById($connectionID)) {
            $connection = $this->createConnection($connectionID);
            $this->pool[$connectionID] = $connection;
        }

        return $this->slots[$slot] = $connection;
    }

    /**
     * {@inheritdoc}
     */
    public function getConnectionById($connectionID)
    {
        if (isset($this->pool[$connectionID])) {
            return $this->pool[$connectionID];
        }
    }

    /**
     * Returns a random connection from the pool.
     *
     * @return NodeConnectionInterface|null
     */
    protected function getRandomConnection()
    {
        if ($this->pool) {
            return $this->pool[array_rand($this->pool)];
        }
    }

    /**
     * Permanently associates the connection instance to a new slot.
     * The connection is added to the connections pool if not yet included.
     *
     * @param NodeConnectionInterface $connection Connection instance.
     * @param int                     $slot       Target slot index.
     */
    protected function move(NodeConnectionInterface $connection, $slot)
    {
        $this->pool[(string) $connection] = $connection;
        $this->slots[(int) $slot] = $connection;
        $this->slotmap[(int) $slot] = $connection;
    }

    /**
     * Handles -ERR responses returned by Redis.
     *
     * @param CommandInterface       $command Command that generated the -ERR response.
     * @param ErrorResponseInterface $error   Redis error response object.
     *
     * @return mixed
     */
    protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error)
    {
        $details = explode(' ', $error->getMessage(), 2);

        switch ($details[0]) {
            case 'MOVED':
                return $this->onMovedResponse($command, $details[1]);

            case 'ASK':
                return $this->onAskResponse($command, $details[1]);

            default:
                return $error;
        }
    }

    /**
     * Handles -MOVED responses by executing again the command against the node
     * indicated by the Redis response.
     *
     * @param CommandInterface $command Command that generated the -MOVED response.
     * @param string           $details Parameters of the -MOVED response.
     *
     * @return mixed
     */
    protected function onMovedResponse(CommandInterface $command, $details)
    {
        list($slot, $connectionID) = explode(' ', $details, 2);

        if (!$connection = $this->getConnectionById($connectionID)) {
            $connection = $this->createConnection($connectionID);
        }

        if ($this->useClusterSlots) {
            $this->askSlotMap($connection);
        }

        $this->move($connection, $slot);
        $response = $this->executeCommand($command);

        return $response;
    }

    /**
     * Handles -ASK responses by executing again the command against the node
     * indicated by the Redis response.
     *
     * @param CommandInterface $command Command that generated the -ASK response.
     * @param string           $details Parameters of the -ASK response.
     *
     * @return mixed
     */
    protected function onAskResponse(CommandInterface $command, $details)
    {
        list($slot, $connectionID) = explode(' ', $details, 2);

        if (!$connection = $this->getConnectionById($connectionID)) {
            $connection = $this->createConnection($connectionID);
        }

        $connection->executeCommand(RawCommand::create('ASKING'));
        $response = $connection->executeCommand($command);

        return $response;
    }

    /**
     * Ensures that a command is executed one more time on connection failure.
     *
     * The connection to the node that generated the error is evicted from the
     * pool before trying to fetch an updated slots map from another node. If
     * the new slots map points to an unreachable server the client gives up and
     * throws the exception as the nodes participating in the cluster may still
     * have to agree that something changed in the configuration of the cluster.
     *
     * @param CommandInterface $command Command instance.
     * @param string           $method  Actual method.
     *
     * @return mixed
     */
    private function retryCommandOnFailure(CommandInterface $command, $method)
    {
        $failure = false;

        RETRY_COMMAND: {
            try {
                $response = $this->getConnectionByCommand($command)->$method($command);
            } catch (ConnectionException $exception) {
                $connection = $exception->getConnection();
                $connection->disconnect();

                $this->remove($connection);

                if ($failure) {
                    throw $exception;
                } elseif ($this->useClusterSlots) {
                    $this->askSlotMap();
                }

                $failure = true;

                goto RETRY_COMMAND;
            }
        }

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function writeRequest(CommandInterface $command)
    {
        $this->retryCommandOnFailure($command, __FUNCTION__);
    }

    /**
     * {@inheritdoc}
     */
    public function readResponse(CommandInterface $command)
    {
        return $this->retryCommandOnFailure($command, __FUNCTION__);
    }

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

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

        return $response;
    }

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

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        if ($this->slotmap->isEmpty()) {
            $this->useClusterSlots ? $this->askSlotMap() : $this->buildSlotMap();
        }

        $connections = array();

        foreach ($this->slotmap->getNodes() as $node) {
            if (!$connection = $this->getConnectionById($node)) {
                $this->add($connection = $this->createConnection($node));
            }

            $connections[] = $connection;
        }

        return new \ArrayIterator($connections);
    }

    /**
     * Returns the underlying slot map.
     *
     * @return SlotMap
     */
    public function getSlotMap()
    {
        return $this->slotmap;
    }

    /**
     * Returns the underlying command hash strategy used to hash commands by
     * using keys found in their arguments.
     *
     * @return StrategyInterface
     */
    public function getClusterStrategy()
    {
        return $this->strategy;
    }

    /**
     * Returns the underlying connection factory used to create new connection
     * instances to Redis nodes indicated by redis-cluster.
     *
     * @return FactoryInterface
     */
    public function getConnectionFactory()
    {
        return $this->connections;
    }

    /**
     * Enables automatic fetching of the current slots map from one of the nodes
     * using the CLUSTER SLOTS command. This option is enabled by default as
     * asking the current slots map to Redis upon -MOVED responses may reduce
     * overhead by eliminating the trial-and-error nature of the node guessing
     * procedure, mostly when targeting many keys that would end up in a lot of
     * redirections.
     *
     * The slots map can still be manually fetched using the askSlotMap()
     * method whether or not this option is enabled.
     *
     * @param bool $value Enable or disable the use of CLUSTER SLOTS.
     */
    public function useClusterSlots($value)
    {
        $this->useClusterSlots = (bool) $value;
    }
}


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

namespace RedKiteCms\Rendering\Controller\Security;

use RedKiteCms\Rendering\Controller\Cms\BackendController;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class AuthenticationController is the object assigned to sign in to the CMS backend
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Security
 */
abstract class AuthenticationController extends BackendController
{
    /**
     * Implements the action to sign in to the CMS backend
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function login(array $options)
    {
        $response = null;
        $template = 'RedKiteCms/Resources/views/Security/Login/login-form.html.twig';
        if ($options["is_ajax"]) {
            $response = new Response();
            $response->setStatusCode('403');

            return $response;
        }

        $params['target'] = '/backend/' . $options["red_kite_cms_config"]->homepagePermalink();
        $params['error'] = $options["error"];
        $params['last_username'] = $options["last_username"];
        $params['template_assets_manager'] = $options["template_assets"];
        $params['template_assets_manager']->add($options["assets"]);

        return $options["twig"]->render($template, $params, $response);
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\AnnotationTools\Factory;

use Doctrine\Common\Annotations\Reader;
use Ruwork\AnnotationTools\Mapping\MappingInterface;
use Ruwork\AnnotationTools\Metadata\ClassMetadata;
use Ruwork\AnnotationTools\Metadata\MethodMetadata;
use Ruwork\AnnotationTools\Metadata\PropertyMetadata;

abstract class AbstractMetadataFactory implements MetadataFactoryInterface
{
    protected const TARGET_CLASS = 0;
    protected const TARGET_PROPERTY = 1;
    protected const TARGET_METHOD = 2;

    private $reader;

    public function __construct(Reader $reader)
    {
        $this->reader = $reader;
    }

    /**
     * {@inheritdoc}
     */
    final public function getMetadata(string $class): ClassMetadata
    {
        $targetsMap = array_flip($this->getTargets());
        $reflectionClass = new \ReflectionClass($class);
        $classMappings = [];
        $properties = [];
        $methods = [];

        if (isset($targetsMap[self::TARGET_CLASS])) {
            $classMappings = $this->getClassMappings($reflectionClass);
        }

        if (isset($targetsMap[self::TARGET_PROPERTY])) {
            $this->getPropertiesMetadata($reflectionClass, $properties);
        }

        if (isset($targetsMap[self::TARGET_METHOD])) {
            $this->getMethodsMetadata($reflectionClass, $methods);
        }

        return new ClassMetadata($class, $classMappings, $properties, $methods);
    }

    abstract protected function getTargets(): array;

    abstract protected function supports($mapping, int $target): bool;

    private function getClassMappings(\ReflectionClass $reflectionClass): array
    {
        $mappings = [];

        foreach ($this->reader->getClassAnnotations($reflectionClass) as $annotation) {
            if ($annotation instanceof MappingInterface &&
                $this->supports($annotation, self::TARGET_CLASS)
            ) {
                $mappings[$annotation::getName()][] = $annotation;
            }
        }

        return $mappings;
    }

    private function getPropertyMappings(\ReflectionProperty $reflectionProperty): array
    {
        $mappings = [];

        foreach ($this->reader->getPropertyAnnotations($reflectionProperty) as $annotation) {
            if ($annotation instanceof MappingInterface &&
                $this->supports($annotation, self::TARGET_PROPERTY)
            ) {
                $mappings[$annotation::getName()][] = $annotation;
            }
        }

        return $mappings;
    }

    private function getMethodMappings(\ReflectionMethod $reflectionMethod): array
    {
        $mappings = [];

        foreach ($this->reader->getMethodAnnotations($reflectionMethod) as $annotation) {
            if ($annotation instanceof MappingInterface &&
                $this->supports($annotation, self::TARGET_METHOD)
            ) {
                $mappings[$annotation::getName()][] = $annotation;
            }
        }

        return $mappings;
    }

    private function getPropertiesMetadata(\ReflectionClass $reflectionClass, array &$properties): void
    {
        if ($reflectionClass->getParentClass()) {
            $this->getPropertiesMetadata($reflectionClass->getParentClass(), $properties);
        }

        foreach ($reflectionClass->getProperties() as $reflectionProperty) {
            $name = $reflectionProperty->getName();
            $mappings = $this->getPropertyMappings($reflectionProperty);
            $properties[$name] = new PropertyMetadata($name, $mappings);
        }
    }

    private function getMethodsMetadata(\ReflectionClass $reflectionClass, array &$methods): void
    {
        if ($reflectionClass->getParentClass()) {
            $this->getMethodsMetadata($reflectionClass->getParentClass(), $methods);
        }

        foreach ($reflectionClass->getMethods() as $reflectionMethod) {
            $name = $reflectionMethod->getName();
            $mappings = $this->getMethodMappings($reflectionMethod);
            $methods[$name] = new MethodMetadata($name, $mappings);
        }
    }
}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form\Element;

use Xloit\Bridge\Zend\Filter\TimeToDateTime;
use Zend\Filter;
use Zend\Form\Element\Date as ZendDate;

/**
 * A {@link Time} class.
 *
 * @package Xloit\Bridge\Zend\Form\Element
 */
class Time extends ZendDate
{
    /**
     * Accepted options for DateTime:
     * - format: A \DateTime compatible string
     *
     * @param array|\Traversable $options
     *
     * @return $this
     */
    public function setOptions($options)
    {
        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (isset($options['time_format'])) {
            $this->setFormat($options['time_format']);

            unset($options['time_format']);
        }

        parent::setOptions($options);

        return $this;
    }

    /**
     * Provide default input rules for this element and attaches default validators for the Date input.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        $dateValidator     = $this->getDateValidator();
        $dateValidatorName = get_class($dateValidator);

        return [
            'name'       => $this->getName(),
            'required'   => true,
            'filters'    => [
                Filter\StringTrim::class    => [
                    'name' => Filter\StringTrim::class
                ],
                Filter\StripNewlines::class => [
                    'name' => Filter\StripNewlines::class
                ],
                Filter\StripTags::class     => [
                    'name' => Filter\StripTags::class
                ],
                TimeToDateTime::class       => [
                    'name'    => TimeToDateTime::class,
                    'options' => [
                        'time_format' => $this->getFormat()
                    ]
                ]
            ],
            'validators' => [
                $dateValidatorName => $dateValidator
            ]
        ];
    }
}


<?php

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

namespace ItePHP\Component\Form;

/**
 * FormBuilder field
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
abstract class InputField extends FormField{

    /**
     * {@inheritdoc}
     */
	public function __construct($options){
		parent::__construct($options);
	}

	/**
	 * Set html tag pattern
	 *
	 * @param string $pattern - value of tag pattern (regular expression)
	 */
	public function setPattern($pattern){
		$this->setTag('pattern',$pattern);
		if($this->getValidator()){
			$this->getValidator()->setOption('pattern',$pattern);
		}
	}

	/**
	 * Get value of html tag pattern
	 *
	 * @return string
	 */
	public function getPattern(){
		return $this->getTag('pattern');
	}

	/**
	 * Set value field
	 *
	 * @param mixed $value - value field
	 */
	public function setValue($value){
		$this->setTag('value',$value);
	}

	/**
	 * Get value field
	 *
	 * @return mixed
	 */
	public function getValue(){
		return $this->getTag('value');
	}

    /**
     * {@inheritdoc}
     */
	public function render(){
		$template=$this->labelRender();
		$template.=$this->componentRender();
		return $template;
	}

    /**
     * {@inheritdoc}
     */
	public function labelRender(){
		return '<label for="'.$this->getId().'">'.htmlspecialchars($this->getLabel()).'</label>';
	}

    /**
     * {@inheritdoc}
     */
	public function componentRender(){
		$template='<input ';
		foreach($this->getTags() as $kTag=>$tag){
			if($tag!='')
				$template.=$kTag.'="'.htmlspecialchars($tag).'" ';
		}
		$template.=' />';
		return $template;

	}

    /**
     * {@inheritdoc}
     */
	public function setData($value){
		$this->setValue($value);
	}

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

    /**
     * {@inheritdoc}
     */
	public function clearData(){
		return $this->setValue(null);
	}
}


<?php

namespace Wambo\Catalog\Model;

use Wambo\Catalog\Exception\SKUException;

/**
 * Class SKU represents an unique identifier (stock keeping unit) for a product (e.g. "fancy-short-1")
 *
 * @package Wambo\Catalog\Model
 */
class SKU
{
    /**
     * @var string $whiteSpacePattern A regular expression that matches white-space characters
     */
    private $whiteSpacePattern = '/[\s]/';

    /**
     * @var string $invalidCharactersPattern A regular expression that matches all characters that are invalid for a SKU
     */
    private $invalidCharactersPattern = '/[^a-z0-9-]/';

    /**
     * @var string $uppercaseCharactersPattern A regular expression that matches uppercase characters
     */
    private $uppercaseCharactersPattern = '/[A-Z]/';

    /**
     * @var string $invalidPrefixCharacters A regular expression that matches characters that cannot be used as a prefix
     *      for SKUs
     */
    private $invalidPrefixCharacters = '/^[-]/';

    /**
     * @var string $invalidSuffixCharacters A regular expression that matches characters that cannot be used as a prefix
     *      for SKUs
     */
    private $invalidSuffixCharacters = '/[-]$/';

    /**
     * @var int $minLength Defines the minimum length for a SKU
     */
    private $minLength = 2;

    /**
     * @var int $maxLength Defines the maximum length of a SKU
     */
    private $maxLength = 32;
    /**
     * @var string
     */
    private $sku;

    /**
     * Create a new SKU instance
     *
     * @param string $sku A unique identifier for a product (e.g. "fancy-short-1")
     *
     * @throws SKUException If the given $sku is invalid
     */
    public function __construct(string $sku)
    {
        $this->validateSKU($sku);
        $this->sku = $sku;
    }

    /**
     * Get a string representation of the current SKU.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->sku;
    }

    /**
     * Validate the given SKU
     *
     * @param string $sku A unique identifier for a product (e.g. "fancy-short-1")
     *
     * @return void
     *
     * @throws SKUException If the given $sku is invalid
     */
    private function validateSKU(string $sku)
    {
        if (strlen($sku) == 0) {
            throw new SKUException("A SKU cannot be empty");
        }

        // check for white-space
        $containsWhitespace = preg_match($this->whiteSpacePattern, $sku) == 1;
        if ($containsWhitespace) {
            throw new SKUException(sprintf("A SKU cannot contain white space characters: \"%s\"", $sku));
        }

        // uppercase
        $containsUppercaseCharacters = preg_match($this->uppercaseCharactersPattern, $sku) == 1;
        if ($containsUppercaseCharacters) {
            throw new SKUException(sprintf("A SKU cannot contain uppercase characters: \"%s\"", $sku));
        }

        // check for invalid characters
        $containsInvalidCharacters = preg_match($this->invalidCharactersPattern, $sku) == 1;
        if ($containsInvalidCharacters) {
            throw new SKUException(sprintf("The SKU \"%s\" contains invalid characters. A SKU can only contain the following characters: a-z, 0-9 and -",
                $sku));
        }

        // check prefix
        $prefixMatches = [];
        $prefixContainsInvalidCharacters = preg_match($this->invalidPrefixCharacters, $sku, $prefixMatches) == 1;
        if ($prefixContainsInvalidCharacters) {
            throw new SKUException(sprintf("A SKU cannot start with the given characters: \"%s\"",
                implode("", $prefixMatches)));
        }

        // check suffix
        $suffixMatches = [];
        $suffixContainsInvalidCharacters = preg_match($this->invalidSuffixCharacters, $sku, $suffixMatches) == 1;
        if ($suffixContainsInvalidCharacters) {
            throw new SKUException(sprintf("A SKU cannot end with the given characters: \"%s\"",
                implode("", $suffixMatches)));
        }

        // check minimum length
        if (strlen($sku) < $this->minLength) {
            throw new SKUException(sprintf("The given SKU \"%s\" is too short. The minimum length for a SKU is: %s",
                $sku, $this->minLength));
        }

        // check maximum length
        if (strlen($sku) > $this->maxLength) {
            throw new SKUException(sprintf("The given SKU \"%s\" is too long (%s character). The maximum length for a SKU is: %s",
                strlen($sku), $sku, $this->maxLength));
        }
    }
}


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

use dektrium\user\models\Token;
use dektrium\user\models\User;
use yii\base\Component;

/**
 * Mailer.
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class Mailer extends Component
{
    /** @var string */
    public $viewPath = '@dektrium/user/views/mail';

    /** @var string|array */
    public $sender = 'no-reply@example.com';

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

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

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

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

    /**
     * Sends an email to a user with credentials and confirmation link.
     *
     * @param  User  $user
     * @param  Token $token
     * @return bool
     */
    public function sendWelcomeMessage(User $user, Token $token = null)
    {
        return $this->sendMessage($user->email,
            $this->welcomeSubject,
            'welcome',
            ['user' => $user, 'token' => $token]
        );
    }

    /**
     * Sends an email to a user with confirmation link.
     *
     * @param  User  $user
     * @param  Token $token
     * @return bool
     */
    public function sendConfirmationMessage(User $user, Token $token)
    {
        return $this->sendMessage($user->email,
            $this->confirmationSubject,
            'confirmation',
            ['user' => $user, 'token' => $token]
        );
    }

    /**
     * Sends an email to a user with reconfirmation link.
     *
     * @param  User  $user
     * @param  Token $token
     * @return bool
     */
    public function sendReconfirmationMessage(User $user, Token $token)
    {
        if ($token->type == Token::TYPE_CONFIRM_NEW_EMAIL) {
            $email = $user->unconfirmed_email;
        } else {
            $email = $user->email;
        }
        return $this->sendMessage($email,
            $this->reconfirmationSubject,
            'reconfirmation',
            ['user' => $user, 'token' => $token]
        );
    }

    /**
     * Sends an email to a user with recovery link.
     *
     * @param  User  $user
     * @param  Token $token
     * @return bool
     */
    public function sendRecoveryMessage(User $user, Token $token)
    {
        return $this->sendMessage($user->email,
            $this->recoverySubject,
            'recovery',
            ['user' => $user, 'token' => $token]
        );
    }

    /**
     * @param  string $to
     * @param  string $subject
     * @param  string $view
     * @param  array  $params
     * @return bool
     */
    protected function sendMessage($to, $subject, $view, $params = [])
    {
        $mailer = \Yii::$app->mailer;
        $mailer->viewPath = $this->viewPath;
        $mailer->getView()->theme = \Yii::$app->view->theme;

        return $mailer->compose(['html' => $view, 'text' => 'text/' . $view], $params)
            ->setTo($to)
            ->setFrom($this->sender)
            ->setSubject($subject)
            ->send();
    }
}


<?php

/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NetHelper\Service;

use RuntimeException as Exception;

class Net {

    /**
     * @var Resource $ch
     */
    protected $ch;

    protected function setCurlDefaults() {
        $options = array(
            /**
             * @TODO show html body for 4xx HTTP codes
             */
            CURLOPT_FAILONERROR => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPGET => true,
            CURLOPT_SAFE_UPLOAD => true,
            CURLOPT_ENCODING => ''
        );
        $result = curl_setopt_array($this->ch, $options);
        if (!$result) {
            throw new Exception('curl_setopt_array() failed');
        }
    }

    protected function setCurlOption($option, $value) {
        if (!curl_setopt($this->ch, $option, $value)) {
            throw new Exception('curl_setopt() failed');
        }
    }

    protected function setUrl($url) {
        if (empty($url)) {
            throw new Exception('empty url is not allowed');
        }
        $this->setCurlOption(CURLOPT_URL, $url);
    }

    /**
     *
     * @throws Exception
     */
    public function __construct() {
        $this->ch = curl_init();
        if ($this->ch === false) {
            throw new Exception('curl_init() failed');
        }
        $this->setCurlDefaults();
    }

    /**
     * Set user agent
     * @param string $ua
     */
    public function setUserAgent($ua) {
        $this->setCurlOption(CURLOPT_USERAGENT, $ua);
    }

    /**
     *
     * @return string
     * @throws Exception
     */
    protected function curlExec() {
        $data = curl_exec($this->ch);
        if ($data === false) {

            $http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
            throw new Exception('curl_exec() failed, HTTP code: ' . $http_code);
        }
        return $data;
    }

    protected function setNoAuth() {
        $this->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_NONE);
        $this->setCurlOption(CURLOPT_USERPWD, null);
    }

    protected function requireAuth($user, $password) {

        $this->setCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $this->setCurlOption(CURLOPT_USERPWD, $user . ':' . $password);
    }

    /**
     * HTTP GET
     * @param string $url
     * @return string
     */
    public function get($url) {

        $this->setUrl($url);
        $this->setCurlOption(CURLOPT_HTTPGET, true);
        $this->setNoAuth();

        $data = $this->curlExec();

        return $data;
    }

    /**
     * HTTP POST
     * @param string $url
     * @param array $data post data
     * @param array|null $auth [null] array with indexes user and password
     * @return string response data(maybe html or json)
     */
    public function post($url, $data = null, $auth = null) {
        $this->setUrl($url);
        $this->setCurlOption(CURLOPT_POST, true);
        if (!is_null($data)) {
            $this->setCurlOption(CURLOPT_POSTFIELDS, http_build_query($data));
        }

        if (!is_null($auth)) {
            $this->requireAuth($auth['user'], $auth['password']);
        } else {
            $this->setNoAuth();
        }

        return $this->curlExec();
    }

}


<?php
namespace FelixOnline\Base;

/*
 * Theme class
 * Handles rendering views etc
 */
class Theme
{
    protected $name; // theme name
    protected $directory; // theme directory
    protected $url;
    protected $page; // current page
    protected $parent; // parent page
    protected $data = array(); // data to be added to rendered page
    protected $hierarchy = array(); // template hierarchy
    protected $sidebar = array(); // array of sidebar modules
    protected $site; // current site
    protected $themeclass; // theme specific class

    public function __construct($name)
    {
        $app = App::getInstance();
        $currentuser = $app['currentuser'];

        $this->name = $name;
        $this->directory = BASE_DIRECTORY.'/themes/'.$this->name.'/';
        $this->url = STANDARD_URL.'themes/'.$this->name.'/';

        /*
         * Check if there is theme specific theme class and load in if there is
         */
        $classfile = $this->directory.'/core/theme-'.$this->name.'.class.php';
        $name = 'Theme'.ucfirst($this->name);
        if (file_exists($classfile) && get_class($this) != $name) {
            require_once($classfile);
            $this->themeclass = new $name($this->name);
        } else {
            $this->appendData(array(
                'currentuser' => $currentuser,
                'theme' => $this
            ));

            require($this->directory.'/index.php');
            $this->themeclass = $this;
        }
    }

    public function getClass()
    {
        return $this->themeclass;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getDirectory()
    {
        return $this->directory;
    }
    public function getURL()
    {
        return $this->url;
    }

    public function appendData($array)
    {
        $this->data = array_merge($this->data, $array);
    }

    public function setHierarchy($hierarchy)
    {
        return $this->hierarchy = $hierarchy;
    }

    /*
     * Render specific template
     *
     * $page - page to render
     * $data - data to include with render [array]
     */
    public function render($page, $data = null)
    {
        if ($data) {
            $this->appendData($data);
        }
        if (!$this->parent) {
            $this->parent = $page;
        }
        $this->page = $page;
        $this->includePage($this->cascade());
    }

    /*
     * Private: Include page in enclosed function
     */
    private function includePage($themePage)
    {
        $themeData = $this->data;
        call_user_func(function () use ($themeData, $themePage) {
            extract($themeData);
            include($this->directory.'/'.$themePage.'.php');
        });
    }

    /*
     * Private: Cascade through template hierarchy
     *
     * Returns matched page
     */
    private function cascade()
    {
        if ($this->hierarchy) { // if there is a hierarchy defined
            foreach ($this->hierarchy as $key => $value) { // loop through each hierarchy
                $file = $this->page . '-' . $value;
                if ($this->fileExists($file)) { // if that file exists then return it
                    $this->hierarchy = array(); // reset hierarchy for further renders
                    return $file;
                }
            }
            $this->hierarchy = array(); // reset hierarchy for further renders
        }
        return $this->page; // if no page found then return base page
    }

    /*
     * Private: Check whether file exists
     */
    private function fileExists($file)
    {
        return file_exists($this->directory.'/'.$file.'.php');
    }

    /*
     * Translates a string with dashes into camel case (e.g. first-name -> FirstName)
     * $str - String in dash format
     * $ucfirst - If true, capitalise the first char in $str
     * Returns string - $str translated into camel caps
     */
    private function toCamelCase($str, $ucfirst = true)
    {
        $parts = explode('-', $str);
        $parts = $parts ? array_map('ucfirst', $parts) : array($str);
        $parts[0] = $ucfirst ? ucfirst($parts[0]) : lcfirst($parts[0]);
        return implode('', $parts);
    }

    /*
     * Public: Check if current view is $query
     */
    public function isPage($query)
    {
        if ($query == $this->parent) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * Public: Set sidebar modules
     * Overrides any previous sidebar modules
     */
    public function setSidebar($modules)
    {
        $this->sidebar = $modules;
        return $this->sidebar;
    }

    /*
     * Public: Render sidebar with set modules
     */
    public function renderSidebar()
    {
        if (!$this->sidebar || empty($this->sidebar)) {
            throw new InternalException('No sidebar modules set');
            return false;
        }
        foreach ($this->sidebar as $key => $module) {
            $this->render('sidebar/'.$module);
        }
    }

    /*
     * Public: Get sidebar
     */
    public function getSidebar()
    {
        return $this->sidebar;
    }

    /*
     * Public: Add module to end of sidebar
     * Add a new module to the end of sidebar
     */
    public function addSidebarEnd($module)
    {
        array_push($this->sidebar, $module);
        return $this->sidebar;
    }

    /*
     * Public: Add module to beginning of sidebar
     * Add a new module to the beginning of sidebar
     */
    public function addSidebarBeginning($module)
    {
        array_unshift($this->sidebar, $module);
        return $this->sidebar;
    }

    /*
     * Public: Set site
     *
     * Returns site
     */
    public function setSite($site)
    {
        return $this->site = $site;
    }

    public function getSite()
    {
        return $site;
    }

    public function isSite($site)
    {
        $return = false;
        if ($site == $this->site) {
            $return = true;
        }
        return $return;
    }
}


<?php

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

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

	/**
	 * translate the content
	 *
	 * @access public
	 * @param  string $sFile
	 * @return string
	 */
	public static function toJs(string $sFile) : string
	{
	    $aFile = pathinfo($sFile);
	    $sFolder = uniqid();

	    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {

	        $sCmd = self::TYPESCRIPT_WINDOWS." ".$sFile." --outDir ".__DIR__.'../../'.CACHE_DIR.$sFolder.'/';
            $sContent = shell_exec($sCmd);
	    }
	    else {

	        $sCmd = "tsc ".$sFile." --outDir ".__DIR__.'../../'.CACHE_DIR.$sFolder.'/';
            $sContent = shell_exec($sCmd);
	    }

        header("content-type:text/javascript");
        return file_get_contents(__DIR__ . '../../' .$aFile['filename'].'.js');
	}
}


<?php

namespace Alexsoft;

/**
 * Neat and tidy cURL wrapper for PHP
 *
 * @method string get
 * @method string head
 * @method string post
 * @method string put
 * @method string patch
 * @method string delete
 *
 * @package Curl
 * @author  Alex Plekhanov
 * @link    https://github.com/alexsoft/curl
 * @license MIT
 * @version 0.4.0-dev
 */
class Curl
{
    const VERSION = '0.4.0-dev';

    const GET = 'GET';
    const POST = 'POST';
    const HEAD = 'HEAD';
    const PUT = 'PUT';
    const DELETE = 'DELETE';
    const PATCH = 'PATCH';

    /**
     * cURL handle
     * @var resource
     */
    protected $resource;

    /**
     * Response string from curl_exec
     * @var string
     */
    protected $response;

    /**
     * URL to query
     * @var string
     */
    protected $url;

    /**
     * HTTP Verb
     * @var string
     */
    protected $method;

    /**
     * Key => value of data to send
     * @var array
     */
    protected $data = [];

    /**
     * Key => value of headers to send
     * @var array
     */
    protected $headers = [];

    /**
     * Key => value of cookies to send
     * @var array
     */
    protected $cookies = [];

    /**
     * User agent for query
     * @var string
     */
    protected $userAgent = 'alexsoft/curl';

    /**
     * Array of available HTTP Verbs
     * @var array
     */
    protected $availableMethods = [self::GET, self::POST, self::HEAD, self::PUT, self::DELETE, self::PATCH];

    /**
     * @param $url string URL for query
     */
    public function __construct($url = null)
    {
        $this->url = $url;
    }

    /**
     * Add data for sending
     * @param array $data
     * @return $this
     */
    public function addData(array $data)
    {
        $this->data = array_merge(
            $this->data,
            $data
        );
        return $this;
    }

    /**
     * Add headers for sending
     * @param array $headers
     * @return $this
     */
    public function addHeaders(array $headers)
    {
        $this->headers = array_merge(
            $this->headers,
            $headers
        );
        return $this;
    }

    /**
     * Add cookies for sending
     * @param array $cookies
     * @return $this
     */
    public function addCookies(array $cookies)
    {
        $this->cookies = array_merge(
            $this->cookies,
            $cookies
        );
        return $this;
    }

    /**
     * Methods which can be called:
     * get(), post(), head(), put(), delete(), options()
     * @param $name
     * @param $arguments
     * @return array|NULL
     * @throws \Exception
     */
    function __call($name, $arguments)
    {
        if (!empty($arguments)) {
            $url = $arguments[0];
            if (is_string($url) && filter_var($url, FILTER_VALIDATE_URL)) {
                $this->url = $url;
            } else {
                throw new \Exception('Wrong url. Give a correct url in a string format.');
            }
        } else {
            if (is_null($this->url)) {
                throw new \Exception('Provide a url either in constructor or while calling verb method.');
            }
        }

        if (in_array(mb_strtoupper($name), $this->availableMethods)) {
            return $this->request(mb_strtoupper($name));
        } else {
            throw new \Exception('Method ' . mb_strtoupper($name) . ' is not supported');
        }
    }

    /**
     * @param $method string method of query
     * @return array|NULL
     */
    protected function request($method)
    {
        $this->resource = curl_init();
        $this->method = $method;
        $this->prepareRequest();
        $this->response = curl_exec($this->resource);
        curl_close($this->resource);
        return $this->parseResponse();
    }

    /**
     * Method which sets all the data, headers, cookies
     * and other options for the query
     */
    protected function prepareRequest()
    {
        // Set data for GET queries
        if ($this->method === static::GET && !empty($this->data)) {
            $url = trim($this->url, '/') . '?';
            $url .= http_build_query($this->data);
        } else {
            $url = $this->url;
        }

        // Set options
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_POST => $this->method === static::POST,
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => $this->method === static::HEAD,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT => $this->userAgent,
            CURLOPT_SSL_VERIFYPEER => false
        );

        if (!in_array($this->method, [static::GET, static::HEAD, static::POST])) {
            $options[CURLOPT_CUSTOMREQUEST] = $this->method;
        }

        // Set data for not GET queries
        if (!empty($this->data) && $this->method !== static::GET) {
            $options[CURLOPT_POSTFIELDS] = http_build_query($this->data);
        }

        // Set headers if needed
        if (!empty($this->headers)) {
            $headersToSend = [];
            foreach ($this->headers as $key => $value) {
                $headersToSend[] = "{$key}: {$value}";
            }
            $options[CURLOPT_HTTPHEADER] = $headersToSend;
        }

        // Set cookies if needed
        if (!empty($this->cookies)) {
            $cookiesToSend = [];
            foreach ($this->cookies as $key => $value) {
                $cookiesToSend[] = "{$key}={$value}";
            }
            $options[CURLOPT_COOKIE] = implode('; ', $cookiesToSend);
        }

        curl_setopt_array($this->resource, $options);
    }

    /**
     * Method which parses cURL response
     * @return array|NULL
     */
    protected function parseResponse()
    {
        if (isset($this->response)) {
            list($responseParts['headersString'], $responseParts['body']) = explode("\r\n\r\n", $this->response, 2);
            $responseParts['body'] = htmlspecialchars($responseParts['body']);
            $headers = explode("\r\n", $responseParts['headersString']);

            $cookies = [];
            if (preg_match_all('/Set-Cookie: (.*?)=(.*?)(\n|;)/i', $responseParts['headersString'], $matches)) {
                if (!empty($matches)) {
                    foreach ($matches[1] as $key => $value) {
                        $cookies[$value] = $matches[2][$key];
                    }
                    $responseParts['cookies'] = $cookies;
                }
            }
            unset($responseParts['headersString']);

            $first = true;
            foreach ($headers as $header) {
                if ($first) {
                    list($responseParts['protocol'], $responseParts['statusCode']) = explode(' ', $header, 2);
                    $first = false;
                } else {
                    $tmp = (explode(': ', $header));
                    if ($tmp[0] === 'Set-Cookie') {
                        continue;
                    } else {
                        $responseParts['headersArray'][$tmp[0]] = $tmp[1];
                    }
                }
            }
            return $responseParts;
        } else {
            return null;
        }
    }

    /**
     * Validate that a value is a valid URL.
     * @param  mixed $value
     * @return bool
     */
    protected function isValidUrl($value)
    {
        return filter_var($value, FILTER_VALIDATE_URL) !== false;
    }
}


<?php

/*
 * Chill is a software for social workers
 * Copyright (C) 2014 Champs-Libres Coopérative <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Chill\CustomFieldsBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Exception\ParseException;
use Chill\CustomFieldsBundle\Entity\CustomField;

/**
 * Class for the command 'chill:custom_fields:populate_group' that
 * Create custom fields from a yml file
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 * @author Marc Ducobu <marc.ducobu@champs-libres.coop>
 */
class CreateFieldsOnGroupCommand extends ContainerAwareCommand
{
    const ARG_PATH = 'path';
    const ARG_DELETE = 'delete';

    protected function configure()
    {
        $this->setName('chill:custom_fields:populate_group')
            ->setDescription('Create custom fields from a yml file')
            ->addArgument(self::ARG_PATH, InputOption::VALUE_REQUIRED,
                'Path to description file')
            ->addOption(self::ARG_DELETE, null, InputOption::VALUE_NONE,
                'If set, delete existing fields');
    }

    /**
     * Delete the existing custom fields for a given customFieldGroup
     *
     * @param CustomFieldsGroup $customFieldsGroup : The custom field group
     */
    protected function deleteFieldsForCFGroup($customFieldsGroup)
    {
        $em = $this->getContainer()
            ->get('doctrine.orm.default_entity_manager');

        foreach ($customFieldsGroup->getCustomFields() as $field) {
            $em->remove($field);
        }
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dialog = $this->getHelperSet()->get('dialog');
        $em = $this->getContainer()
            ->get('doctrine.orm.default_entity_manager');

        $customFieldsGroups = $em
            ->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')
            ->findAll();

        if (count($customFieldsGroups) === 0) {
            $output->writeln('<error>There aren\'t any CustomFieldsGroup recorded'
                . ' Please create at least one.</error>');
        }

        $table = $this->getHelperSet()->get('table');
        $table->setHeaders(array_merge(array('id', 'entity'), $this->getContainer()
                ->getParameter('chill_main.available_languages')))
            ->setRows($this->_prepareRows($customFieldsGroups));
        $table->render($output);

        $customFieldsGroup = $dialog->askAndValidate($output,
            "Enter the customfieldGroup's id on which the custom fields "
            . "should be added :",
            function($answer) use ($customFieldsGroups) {
                foreach ($customFieldsGroups as $customFieldsGroup) {
                    if ($answer == $customFieldsGroup->getId()) {
                        return $customFieldsGroup;
                    }
                }

                throw new \RunTimeException('The id does not match an existing '
                    . 'CustomFieldsGroup');
            }
        );

        if ($input->getOption(self::ARG_DELETE)) {
            $this->deleteFieldsForCFGroup($customFieldsGroup);
        }

        $fieldsInput = $this->_parse($input->getArgument(self::ARG_PATH),
            $output);

        $fields = $this->_addFields($customFieldsGroup, $fieldsInput, $output);
    }

    private function _prepareRows ($customFieldsGroups)
    {
        $rows = array();
        $languages = $this->getContainer()
            ->getParameter('chill_main.available_languages');
        //gather entitites and create an array to access them easily
        $customizableEntities = array();
        foreach ($this->getContainer()
                ->getParameter('chill_custom_fields.customizables_entities') as $entry) {
            $customizableEntities[$entry['class']] = $entry['name'];
        }

        array_walk($customFieldsGroups,
            function(CustomFieldsGroup $customFieldGroup, $key)
                use ($languages, &$rows, $customizableEntities) {
                    //set id and entity
                    $row = array(
                        $customFieldGroup->getId(),
                        $customizableEntities[$customFieldGroup->getEntity()]
                    );

                    foreach ($languages as $lang) {
                        //todo replace with service to find lang when available
                        $row[] = (isset($customFieldGroup->getName()[$lang])) ?
                                $customFieldGroup->getName()[$lang] :
                            'Not available in this language';
                    }
                    $rows[] = $row;
                }
        );

        return $rows;
    }

    private function _parse($path, OutputInterface $output)
    {
        $parser = new Parser();

        if (!file_exists($path)) {
            throw new \RunTimeException("file does not exist");
        }

        try {
            $values = $parser->parse(file_get_contents($path));
        } catch (ParseException $ex) {
            throw new \RunTimeException("The yaml file is not valid", 0, $ex);
        }

        return $values;
    }

    private function _addFields(CustomFieldsGroup $group, $values, OutputInterface $output)
    {
        $cfProvider = $this->getContainer()->get('chill.custom_field.provider');
        $em = $this->getContainer()->get('doctrine.orm.default_entity_manager');

        $languages = $this->getContainer()
            ->getParameter('chill_main.available_languages');

        foreach($values['fields'] as $slug => $field) {
            //check the cf type exists
            $cfType = $cfProvider->getCustomFieldByType($field['type']);
            if ($cfType === NULL) {
                throw new \RunTimeException('the type '.$field['type'].' '
                    . 'does not exists');
            }

            $cf = new CustomField();
            $cf->setSlug($slug)
                ->setName($field['name'])
                ->setOptions(isset($field['options']) ? $field['options'] : array() )
                ->setOrdering($field['ordering'])
                ->setType($field['type'])
                ->setCustomFieldsGroup($group);

            //add to table
            $names = array();
            foreach ($languages as $lang) {
                //todo replace with service to find lang when available
                $names[] = (isset($cf->getName()[$lang])) ?
                    $cf->getName()[$lang] :
                        'Not available in this language';
            }

            if ($this->getContainer()->get('validator')->validate($cf)) {
                $em->persist($cf);
                $output->writeln("<info>Adding Custom Field of type "
                    .$cf->getType()."\t with slug ".$cf->getSlug().
                    "\t and names : ".implode($names, ', ')."</info>");
            } else {
                throw new \RunTimeException("Error in field ".$slug);
            }
        }

        $em->flush();
    }
}


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

namespace CmsUser\Factory\Form\Element;

use Zend\Form\ElementInterface,
    Zend\ServiceManager\DelegatorFactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsAuthentication\Form\Element\Identity,
    CmsUser\Options\AuthenticationOptionsInterface,
    CmsUser\Options\ModuleOptions;

class IdentityElementDelegatorFactory implements DelegatorFactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return ElementInterface
     */
    public function createDelegatorWithName(
        ServiceLocatorInterface $serviceLocator,
        $name,
        $requestedName,
        $callback
    ) {
        $identityElement = $callback();

        if (!$identityElement instanceof Identity) {
            return $identityElement;
        }

        $services = $serviceLocator->getServiceLocator();

        /* @var $options AuthenticationOptionsInterface */
        $options = $services->get(ModuleOptions::class);

        if ($fields = $options->getIdentityFields()) {
            $last = ucfirst(array_pop($fields));
            if (count($fields) > 0) {
                $fields = array_map('ucfirst', $fields);

                $fields = (array) implode(', ', $fields);
                $fields[] = $last;

                $label = implode(' or ', $fields);
            } else {
                $label = $last;
            }

            $identityElement->setLabel($label);
            $identityElement->setOption('text_domain', 'CmsUser');
        }

        return $identityElement;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Service\Calc\Forecast;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\Calc as SubCalc;
use Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\GetDownline as PGetDownline;

class Plain
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** string 'YYYY', 'YYYYMM' or 'YYYYMMDD' */
    const CTX_IN_PERIOD = 'in.period';
    /** @var \Praxigento\Accounting\Repo\Dao\Account */
    private $daoAcc;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\Accounting\Api\Service\Balance\Get\Turnover */
    private $servBalanceGetTurnover;
    /** @var \Praxigento\BonusBase\Service\Period\Calc\IAdd */
    private $servPeriodAdd;
    /** @var  \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\Calc */
    private $subCalc;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\GetDownline */
    private $subGetDownline;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Accounting\Repo\Dao\Account $daoAcc,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\Accounting\Api\Service\Balance\Get\Turnover $servBalanceGetTurnover,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\Calc $subCalc,
        \Praxigento\BonusHybrid\Service\Calc\Forecast\Plain\GetDownline $subGetDownline,
        \Praxigento\BonusBase\Service\Period\Calc\IAdd $servPeriodAdd
    )
    {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->daoAcc = $daoAcc;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->daoCalc = $daoCalc;
        $this->servBalanceGetTurnover = $servBalanceGetTurnover;
        $this->subCalc = $subCalc;
        $this->subGetDownline = $subGetDownline;
        $this->servPeriodAdd = $servPeriodAdd;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        $this->logger->info("'Forecast Plain' calculation is started.");

        $period = $ctx->get(self::CTX_IN_PERIOD);

        /* get calculation period (begin, end dates) */
        list($dateFrom, $dateTo) = $this->getPeriod($period);

        /* register new calculation for period */
        $calcId = $this->registerNewCalc($dateFrom, $dateTo);
        $this->logger->info("New 'Forecast Plain' calculation is registered: #$calcId ($dateFrom-$dateTo).");

        /* get customers downline for $dateTo */
        $ctxDwnl = new \Praxigento\Core\Data();
        $ctxDwnl->set(PGetDownline::CTX_IN_CALC_ID, $calcId);
        $ctxDwnl->set(PGetDownline::CTX_IN_DATE_ON, $dateTo);
        $this->subGetDownline->exec($ctxDwnl);
        /** @var \Praxigento\BonusHybrid\Repo\Data\Downline[] $dwnlTree */
        $dwnlTree = $ctxDwnl->get(PGetDownline::CTX_OUT_DWNL);

        /* get system customer */
        $custSysId = $this->daoAcc->getSystemCustomerId();

        /* get PV turnover for period */
        $entries = $this->getPvTurnover($dateFrom, $dateTo);

        /* extract only not zero turnovers */
        $filteredTurnover = [];
        $totalPvPositive = $totalPvNegative = 0;
        /** @var \Praxigento\Accounting\Api\Service\Balance\Get\Turnover\Response\Entry $entry */
        foreach ($entries as $entry) {
            $turnover = $entry->turnover;
            $customerId = $entry->customerId;
            if (
                (abs($turnover) > Cfg::DEF_ZERO) &&
                ($customerId != $custSysId)
            ) {
                $filteredTurnover[$customerId] = $entry;
                /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $dwnlEntry */
                $dwnlEntry = $dwnlTree[$customerId];
                $dwnlEntry->setPv($turnover);
                if ($turnover > 0) {
                    $totalPvPositive += $turnover;
                } else {
                    $totalPvNegative += $turnover;
                }
            }
        }
        $this->logger->info("Total positive turnover: $totalPvPositive PV; total negative turnover: $totalPvNegative PV.");

        /* perform calculation */
        $ctx = new \Praxigento\Core\Data();
        $ctx->set(SubCalc::CTX_DWNL_TREE, $dwnlTree);
        $this->subCalc->exec($ctx);

        /* replace actual data in repository */
        $this->saveDownline($dwnlTree);

        /* finalize calculation */
        $this->daoCalc->markComplete($calcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("'Forecast Plain' calculation is completed.");
    }

    /**
     * Return 2 dates (period being/end): first day of the month and today.
     *
     * @param string $requested 'YYYY', 'YYYYMM' or 'YYYYMMDD'
     * @return array
     */
    private function getPeriod($requested)
    {
        $month = substr($requested, 0, 6);
        $begin = $this->hlpPeriod->getPeriodFirstDate($month);
        $end = $this->hlpPeriod->getPeriodLastDate($month);
        $result = [$begin, $end];
        return $result;
    }

    private function getPvTurnover($dateFrom, $dateTo)
    {
        $reqTurnover = new \Praxigento\Accounting\Api\Service\Balance\Get\Turnover\Request();
        $reqTurnover->assetTypeCode = Cfg::CODE_TYPE_ASSET_PV;
        $reqTurnover->dateFrom = $dateFrom;
        $reqTurnover->dateTo = $dateTo;
        $respTurnover = $this->servBalanceGetTurnover->exec($reqTurnover);
        $result = $respTurnover->entries;
        return $result;
    }

    /**
     * Register new period and related calculation.
     *
     * @param string $from begin of the period (YYYYMMDD)
     * @param string $to end of the period (YYYYMMDD)
     * @return int registered calculation ID
     *
     */
    private function registerNewCalc($from, $to)
    {
        $result = null;
        $ctx = new \Praxigento\Core\Data();
        $ctx->set($this->servPeriodAdd::CTX_IN_DSTAMP_BEGIN, $from);
        $ctx->set($this->servPeriodAdd::CTX_IN_DSTAMP_END, $to);
        $ctx->set($this->servPeriodAdd::CTX_IN_CALC_TYPE_CODE, Cfg::CODE_TYPE_CALC_FORECAST_PLAIN);
        $this->servPeriodAdd->exec($ctx);
        $success = $ctx->get($this->servPeriodAdd::CTX_OUT_SUCCESS);
        if ($success) {
            $result = $ctx->get($this->servPeriodAdd::CTX_OUT_CALC_ID);
        }
        return $result;
    }

    private function saveDownline($items)
    {
        foreach ($items as $item) {
            $this->daoBonDwnl->create($item);
        }
    }
}


<?php

/**
 * Validates the presence of the User-Agent header.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.controller.plugins.html Zend_Controller_Plugin_Abstract
 */
class Benri_Controller_Plugin_RequireUserAgentHeader extends Zend_Controller_Plugin_Abstract
{
    /**
     * @internal
     * @var array
     */
    private static $_errMessage = [
        'Request forbidden by administrative rules.',
        'Please make sure your request has a User-Agent header.',
    ];

    /**
     * Validates the current request.
     *
     * All requests MUST include a valid User-Agent header. Requests with no
     * User-Agent header will be rejected.
     *
     * @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 routeStartup(Zend_Controller_Request_Abstract $request)
    {
        if (!$request->getHeader('User-Agent')) {
            $this
                ->getResponse()
                ->setHttpResponseCode(403)
                ->setHeader('Content-Type', 'text/plain; charset=utf-8')
                ->setBody(implode("\n", self::$_errMessage))
                ->sendResponse();

            exit(403);
        }
    }
}


<?php
namespace HtSettingsModule\Service;

use Zend\ServiceManager\ServiceLocatorInterface;
use HtSettingsModule\Options\ModuleOptionsInterface;
use Zend\Stdlib\Hydrator\HydratorInterface;
use HtSettingsModule\Exception;

class NamespaceHydratorProvider implements NamespaceHydratorProviderInerface
{
    protected $hydrators;

    protected $options;

    public function __construct(ServiceLocatorInterface $hydrators, ModuleOptionsInterface $options)
    {
        $this->hydrators = $hydrators;
        $this->options = $options;
    }

    /**
     * {@inheritDoc}
     */
    public function getHydrator($namespace)
    {
        $namespaceOptions = $this->options->getNamespaceOptions($namespace);
        $hydrator = $namespaceOptions->getHydrator();
        if ($hydrator instanceof HydratorInterface) {
            return $hydrator;
        }
        if (is_string($hydrator)) {
            if ($this->hydrators->has($hydrator)) {
                return $this->hydrators->get($hydrator);
            }
            if (class_exists($hydrator)) {
                $hydratorObject = new $hydrator;
                if ($hydratorObject instanceof HydratorInterface) {
                    return $hydratorObject;
                }
            }
        }

        throw new Exception\RuntimeException(sprintf(
            'Hydrator of settings namespace, %s is neither a service or class name or instanceof Zend\Stdlib\Hydrator\HydratorInterface; %s provided instead',
            $namespace,
            is_object($hydrator) ? get_class($hydrator) : gettype($hydrator)
        ));
    }
}


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

namespace RedKiteCms\Bridge\Dispatcher;

use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\EventSystem\Event\Event;
use RedKiteCms\Exception\Event\EventAbortedException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * This object statically handles the Symfony events dispatcher
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Assetic
 */
class Dispatcher
{
    /**
     * @type EventDispatcherInterface
     */
    private static $dispatcher = null;

    /**
     * Sets the dispatcher
     *
     * @param null|EventDispatcherInterface $dispatcher
     */
    public static function setDispatcher(EventDispatcherInterface $dispatcher = null)
    {
        self::$dispatcher = $dispatcher;
    }

    /**
     * Dispatches the event
     *
     * @param       $eventName
     * @param Event $event
     * @return Event
     */
    public static function dispatch($eventName, Event $event)
    {
        if (null === self::$dispatcher) {
            return $event;
        }

        self::$dispatcher->dispatch($eventName, $event);
        DataLogger::log(sprintf('The "%s" event was dispatched', $eventName));
        if ($event->getAbort()) {
            DataLogger::log(sprintf('The "%s" event was aborted', $eventName), DataLogger::ERROR);

            throw new EventAbortedException($event->getAbortMessage());
        }

        return $event;
    }
}