<?php

namespace Chill\PersonBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{

    private $validationBirthdateNotAfterInfos = "The period before today during which"
            . " any birthdate is not allowed. The birthdate is expressed as ISO8601 : "
            . "https://en.wikipedia.org/wiki/ISO_8601#Durations";
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('cl_chill_person');

        $rootNode
                ->canBeDisabled()
                ->children()
                    ->arrayNode('search')
                        ->canBeDisabled()
                        ->children()
                            ->booleanNode('use_double_metaphone')
                                ->defaultFalse()
                                ->end() // use_double_metaphone, parent = children for 'search'
                            ->booleanNode('use_trigrams')
                                ->defaultFalse()
                                ->end() // use_trigrams, parent = children of 'search'
                        ->end() //children for 'search', parent = array node 'search'
                    ->end() // array 'search', parent = children of root
                    ->arrayNode('validation')
                        ->canBeDisabled()
                        ->children()
                            ->scalarNode('birthdate_not_after')
                            ->info($this->validationBirthdateNotAfterInfos)
                            ->defaultValue('P1D')
                            ->validate()
                                ->ifTrue(function($period) {
                                    try {
                                        $interval = new \DateInterval($period);
                                    } catch (\Exception $ex) {
                                        return true;
                                    }
                                    return false;
                                })
                                ->thenInvalid('Invalid period for birthdate validation : "%s" '
                                        . 'The parameter should match duration as defined by ISO8601 : '
                                        . 'https://en.wikipedia.org/wiki/ISO_8601#Durations')
                            ->end() // birthdate_not_after, parent = children of validation

                        ->end() // children for 'validation', parent = validation
                    ->end() //validation, parent = children of root
                ->end() // children of root, parent = root
                    ->arrayNode('person_fields')
                        ->canBeDisabled()
                        ->children()
                                ->append($this->addFieldNode('place_of_birth'))
                                ->append($this->addFieldNode('email'))
                                ->append($this->addFieldNode('phonenumber'))
                                ->append($this->addFieldNode('nationality'))
                                ->append($this->addFieldNode('country_of_birth'))
                                ->append($this->addFieldNode('marital_status'))
                                ->append($this->addFieldNode('spoken_languages'))
                                ->append($this->addFieldNode('address'))
                        ->end() //children for 'person_fields', parent = array 'person_fields'
                    ->end() // person_fields, parent = children of root
                ->end() // children of 'root', parent = root
                ;

        return $treeBuilder;
    }

    private function addFieldNode($key)
    {
        $tree = new TreeBuilder();
        $node = $tree->root($key, 'enum');

        $node
                ->values(array('hidden', 'visible'))
                ->defaultValue('visible')
                ->info("If the field $key must be shown")
            ->end();
        //var_dump($node);
        return $node;
    }
}


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

use RedKiteCms\Configuration\ConfigurationHandler;

/**
 * Class PermalinkManager is the object assigned to handle the blocks which contain one or more permalinks.
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Page
 */
class PermalinkManager
{
    /**
     * @type array|mixed
     */
    private $permalinks = array();
    /**
     * @type string
     */
    private $permalinksFile = "";
    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    private $configurationHandler;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
        $this->permalinksFile = $this->configurationHandler->siteDir() . '/permalinks.json';
        if (file_exists($this->permalinksFile)) {
            $this->permalinks = json_decode(file_get_contents($this->permalinksFile), true);
        }
    }

    /**
     * returns the information for the requested permalink
     * @param $permalink
     *
     * @return array
     */
    public function getPermalink($permalink)
    {
        if (!array_key_exists($permalink, $this->permalinks)) {
            return array();
        }

        return $this->permalinks[$permalink];
    }

    /**
     * Adds a block to permalinks list
     *
     * @param string $blockFile
     * @param string $blockContent
     *
     * @return $this
     */
    public function add($blockFile, $blockContent)
    {
        $this->removeBlock($blockFile);
        $blockPermalinks = $this->fetchPermalinksFromBlock($blockContent, $blockFile);
        if (!empty($blockPermalinks)) {
            $this->permalinks = array_merge_recursive($this->permalinks, $blockPermalinks);
        }

        return $this;
    }

    /**
     * Removes the given block from permalinks list
     *
     * @param $blockFile
     *
     * @return $this
     */
    public function removeBlock($blockFile)
    {
        foreach ($this->permalinks as $permalink => $associatedBlocks) {
            $tmp = array_flip($associatedBlocks);
            unset($tmp[$blockFile]);
            if (empty($tmp)) {
                unset($this->permalinks[$permalink]);

                continue;
            }

            $this->permalinks[$permalink] = array_flip($tmp);
        }

        return $this;
    }

    /**
     * Updates a permalink
     *
     * @param $previousPermalink
     * @param $newPermalink
     *
     * @return $this
     */
    public function update($previousPermalink, $newPermalink)
    {
        $blocks = $this->permalinks[$previousPermalink];
        $this->remove($previousPermalink);
        $this->permalinks[$newPermalink] = $blocks;

        return $this;
    }

    /**
     * Removes a permalink from the list
     * @param string $permalink
     *
     * @return $this
     */
    public function remove($permalink)
    {
        if (array_key_exists($permalink, $this->permalinks)) {
            unset($this->permalinks[$permalink]);
        }

        return $this;
    }

    /**
     * Saves the permalinks
     *
     * @return $this
     */
    public function save()
    {
        file_put_contents($this->permalinksFile, json_encode($this->permalinks));

        return $this;
    }

    private function fetchPermalinksFromBlock($htmlBlock, $blockFile)
    {
        if (!preg_match_all('/href[^"]+"([^"]+)"/is', $htmlBlock, $matches)) {
            return array();
        }

        $permalinks = array();
        $links = $matches[1];
        foreach ($links as $link) {
            if ($this->checkEmptyLink($link)) {
                continue;
            }

            if ($this->checkLinkProtocol($link)) {
                continue;
            }

            $permalinks[$link][] = $blockFile;
        }

        return $permalinks;
    }

    private function checkEmptyLink($link)
    {
        if (empty($link) || $link == "#") {
            return true;
        }

        return false;
    }

    private function checkLinkProtocol($link)
    {
        $protocols = array(
            "http:",
            "https:",
            "mailto:",
            "afs:",
            "cid:",
            "file:",
            "ftp:",
            "mid:",
            "news:",
            "x-exec:",
            "javascript:",
        );

        foreach ($protocols as $protocol) {
            if (strpos($link, $protocol) !== false) {
                return true;
            }
        }

        return false;
    }
}


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

namespace cascade\modules\WidgetWatching\widgets;

use canis\helpers\Html;
use yii\helpers\Url;

/**
 * Content [[@doctodo class_description:cascade\modules\WidgetWatching\widgets\Content]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Content extends \cascade\components\web\widgets\Widget
{
    /**
     * @var [[@doctodo var_type:_lazyObjectWidget]] [[@doctodo var_description:_lazyObjectWidget]]
     */
    protected $_lazyObjectWidget;
    /**
     * @var [[@doctodo var_type:id]] [[@doctodo var_description:id]]
     */
    public $id = 'Watching';

    /**
     * @inheritdoc
     */
    protected $_title = 'Activity';
    /**
     * @inheritdoc
     */
    public $icon = 'fa-eye';

    /**
     * @inheritdoc
     */
    public function init()
    {
        Html::addCssClass($this->htmlOptions, 'ic-watching-widget');

        parent::init();
    }

    /**
     * [[@doctodo method_description:generateStart]].
     *
     * @return [[@doctodo return_type:generateStart]] [[@doctodo return_description:generateStart]]
     */
    public function generateStart()
    {
        $this->htmlOptions['data-instructions'] = json_encode($this->refreshInstructions);
        if ($this->lazy) {
            Html::addCssClass($this->htmlOptions, 'widget-lazy');
        }

        return parent::generateStart();
    }

    /**
     * @inheritdoc
     */
    public function getTitle()
    {
        switch ($this->currentScope) {
            case 'watching':
                return $this->_title . ' of Watched Items';
            break;
            case 'familiar':
                return $this->_title . ' of Familiar Items';
            break;
        }

        return $this->_title;
    }

    /**
     * Get grid cell settings.
     *
     * @return [[@doctodo return_type:getGridCellSettings]] [[@doctodo return_description:getGridCellSettings]]
     */
    public function getGridCellSettings()
    {
        $gridSettings = parent::getGridCellSettings();
        $gridSettings['columns'] = 6;
        $gridSettings['maxColumns'] = 12;

        return $gridSettings;
    }

    /**
     * @inheritdoc
     */
    public function generateContent()
    {
        $parts = [];
        $instructions = [];
        $instructions['ajax']  = ['url' => Url::to(['/app/activity'])];
        $instructions['scope'] = $this->currentScope;
        $parts[] = Html::tag('div', '', ['data-activity-feed' => json_encode($instructions), 'data-height' => json_encode(['min' => 1000, 'max' => 'body'])]);
        $parts[] = Html::tag('div', str_repeat(Html::tag('div', '', ['class' => 'widget-lazy-placeholder']), 30), ['class' => 'activity-feed-thinking']);

        return implode($parts);
    }

    /**
     * Get current scope.
     *
     * @return [[@doctodo return_type:getCurrentScope]] [[@doctodo return_description:getCurrentScope]]
     */
    public function getCurrentScope()
    {
        return $this->getState('scope', 'familiar');
    }

    /**
     * Get widget classes.
     *
     * @return [[@doctodo return_type:getWidgetClasses]] [[@doctodo return_description:getWidgetClasses]]
     */
    public function getWidgetClasses()
    {
        $classes = parent::getWidgetClasses();
        $classes[] = 'refreshable';

        return $classes;
    }

    /**
     * @inheritdoc
     */
    public function getHeaderMenu()
    {
        $items = [];
        $topChooser = [
            'label' => '<i class="fa fa-ellipsis-v"></i>',
            'linkOptions' => ['title' => 'Choose'],
            'url' => '#',
            'items' => [],
            'options' => ['class' => 'dropleft'],
        ];

        $isActive = $this->currentScope === 'all';
        $scopeKeyName = $this->stateKeyName('scope');
        $topChooser['items'][] = [
            'label' => 'All Items',
            'linkOptions' => [
                'title' => 'All Recent Activity',
                'data-state-change' => json_encode([$scopeKeyName => 'all']),
            ],
            'options' => [
                'class' => $isActive,
            ],
            'url' => '#',
            'active' => $isActive,
        ];

        $isActive = $this->currentScope === 'watching';
        $topChooser['items'][] = [
            'label' => 'Watched Items',
            'linkOptions' => [
                'title' => 'Watched Items',
                'data-state-change' => json_encode([$scopeKeyName => 'watching']),
            ],
            'options' => [
                'class' => ($isActive) ? 'active' : '',
            ],
            'url' => '#',
            'active' => $isActive,
        ];

        $isActive = $this->currentScope === 'familiar';
        $topChooser['items'][] = [
            'label' => 'Familiar Items',
            'linkOptions' => [
                'title' => 'Familiar Objects',
                'data-state-change' => json_encode([$scopeKeyName => 'familiar']),
            ],
            'options' => [
                'class' => ($isActive) ? 'active' : '',
            ],
            'url' => '#',
            'active' => $isActive,
        ];

        $items[] = $topChooser;

        return $items;
    }
}


<?php

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

namespace ItePHP\Component\Grid;

/**
 * Interface of column formatter (cell in grid).
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class Column{

	/**
	 * List of id.
	 *
	 * @var string[] $keys
	 */
	private $keys;

	/**
	 * Column label/name.
	 *
	 * @var string $label
	 */
	private $label;

	/**
	 * Class with pattern to generate html.
	 *
	 * @var ColumnFormatter $formatter
	 */
	private $formatter;

	/**
	 * List of sort id.
	 *
	 * @var mixed[] $sortKeys
	 */
	private $sortKeys;

	/**
	 * Constructor
	 *
	 * @param mixed $keys list of id for column or one element
	 * @param string $label
	 * @param ColumnFormatter $formatter class with template to format column
	 * @param mixed $sortKeys sort by list of id
	 */
	public function __construct($keys,$label,ColumnFormatter $formatter=null,$sortKeys=null){
		if(!is_array($keys)){
			$keys=[$keys];
		}

		$this->keys=$keys;

		$this->label=$label;

		if(!$formatter){
			$formatter=new BasicColumnFormatter();
		}

		$this->setFormatter($formatter);
		if($sortKeys===null){
			$sortKeys=$keys;
		}
		$this->setSortBy($sortKeys);
	}

	/**
	 * Set formatter class
	 *
	 * @param ColumnFormatter $formatter class with template to format column
	 */
	public function setFormatter(ColumnFormatter $formatter){
		$this->formatter=$formatter;
	}

	/**
	 * Set sortable column by Keys
	 *
	 * @param mixed $sortKeys sort by list of id
	 */
	public function setSortBy($sortKeys){

		if($sortKeys==null){
			$sortKeys=[];
		}

		if(!is_array($sortKeys)){
			$sortKeys=[$sortKeys];
		}
		$this->sortKeys=$sortKeys;
	}

	/**
	 *
	 * @return mixed[]
	 */
	public function getSortKeys(){
		return $this->sortKeys;
	}

	/**
	 * Check sortable column
	 *
	 * @return bool
	 */
	public function isSortable(){
		return !empty($this->sortKeys);
	}

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

	/**
	 * Get column formatter
	 *
	 * @return ColumnFormatter
	 */
	public function getFormatter(){
		return $this->formatter;
	}

	/**
	 * Get column keys
	 *
	 * @return string[]
	 */
	public function getKeys(){
		return $this->keys;
	}

}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @package		lib\Form
 * @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\Form;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @package		lib\Form
 * @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 Input extends Common
{
    /**
     * the name of element
     *
     * @access private
     * @var    string
     */
    private $_sType = null;

    /**
     * the label of element
     *
     * @access private
     * @var    string
     */
    private $_sLabel = null;

    /**
     * the value of element
     *
     * @access private
     * @var    string
     */
    private $_sValue = null;

    /**
     * constructor that it increment (static) for all use
     *
     * @access public
     * @param  string $sName name
     * @param  string $sType type of input
     * @param  string $sLabel label of input
     * @param  string $sValue value of input
     */
    public function __construct(string $sName, string $sType, string $sLabel = null, string $sValue = null)
    {
        $this->setName($sName);
        $this->setType($sType);
        $this->setValue($sValue);

        if ($sLabel !== null) { $this->setLabel($sLabel); } else { $this->setLabel($sName); }
    }

    /**
     * get the type
     *
     * @access public
     * @return string
     */
    public function getType() : string
    {
        return $this->_sType;
    }

    /**
     * set the type
     *
     * @access public
     * @param  string $sType type of input;
     * @return \Venus\lib\Form\Input
     */
    public function setType(string $sType) : Input
    {
        $this->_sType = $sType;
        return $this;
    }

    /**
     * get the Value
     *
     * @access public
     * @return string
     */
    public function getValue()
    {
        return $this->_sValue;
    }

    /**
     * set the Value
     *
     * @access public
     * @param  string $sValue Value of input;
     * @return \Venus\lib\Form\Input
     */
    public function setValue(string $sValue = null) : Input
    {
        $this->_sValue = $sValue;
        return $this;
    }

    /**
     * get the Label
     *
     * @access public
     * @return string
     */
    public function getLabel() : string
    {
        return $this->_sLabel;
    }

    /**
     * set the Label
     *
     * @access public
     * @param  string $sLabel Label of input;
     * @return \Venus\lib\Form\Input
     */
    public function setLabel(string $sLabel) : Input
    {
        $this->_sLabel = $sLabel;
        return $this;
    }

    /**
     * if the button is clicked
     *
     * @access public
     * @param  string $sType type of input;
     * @return boolean
     */
    public function isClicked(string $sType) : bool
    {
        if ($this->getType() === 'submit' || $this->getType() === 'button') {

            if (isset($_POST[$this->getName()])) { return true; }
        }

        return false;
    }

    /**
     * get the <html>
     *
     * @access public
     * @return string
     */
    public function fetch() : string
    {
        $sContent = '';

        if ($this->getType() === 'text' || $this->getType() === 'password' || $this->getType() === 'file'
            || $this->getType() === 'tel' || $this->getType() === 'url' || $this->getType() === 'email'
            || $this->getType() === 'search' || $this->getType() === 'date' || $this->getType() === 'time'
            || $this->getType() === 'datetime' || $this->getType() === 'month' || $this->getType() === 'week'
            || $this->getType() === 'number' || $this->getType() === 'range' || $this->getType() === 'color') {

            $sContent .= '<label>'.$this->getLabel().'</label> ';
        }

        $sContent .= '<input type="'.$this->getType().'" name="'.$this->getName().'" id="'.$this->getName().'"';

        if ($this->getValue() !== null) { $sContent .= ' value="'.$this->getValue().'"'; }

        $sContent .= '/>';

        return $sContent;
    }
}


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

namespace MimeMailer;

use \Patterns\Abstracts\AbstractSingleton;
use \Patterns\Interfaces\OptionableInterface;
use \Library\Converter\Html2Text;
use \Library\Helper\Directory as DirectoryHelper;
use \Validator\EmailValidator;

/**
 * @author  piwi <me@e-piwi.fr>
 */
class Helper
{

    // --------------------
// RFC 2822 builder
// --------------------

    /**
     * Build a person string compliant to RFC2822
     *
     * @param string $mail The person's email address
     * @param string $name The person's name if so
     * @return string The generated tag
     */
    public static function mailTagger($mail = '', $name = null)
    {
        return((!is_int($name) ? "\"".$name."\" <" : '').$mail.(!is_int($name) ? ">" : ''));
    }

    /**
     * Build a list of person strings compliant to RFC2822
     *
     * @param string|array $list
     * @return string
     */
    public static function mailListTagger(array $list)
    {
        $str = '';
        foreach ($list as $name=>$mail) {
            if (is_string($mail)) {
                $str .= self::mailTagger($mail, $name).Mailer::$ADDERSSES_SEPARATOR;
            } elseif (is_array($mail)) {
                foreach ($mail as $subname=>$submail) {
                    $str .= self::mailTagger($submail, $subname).Mailer::$ADDERSSES_SEPARATOR;
                }
            }
        }
        return $str;
    }

    /**
     * Build a mail header tag compliant to RFC2822
     *
     * @param string $name The name of the tag
     * @param string $value The value of the tag
     * @param array $adds A variable=>value pairs to add to the tag string
     * @return string The generated header tag string
     */
    public static function headerTagger($name = '', $value = '', $adds = array())
    {
        $str = $name.': '.$value;
        if (count($adds)) {
            foreach ($adds as $n=>$v) {
                $str .= Mailer::$HEADERS_SEPARATOR.($n=='boundary' ? "\n\t" : '').$n."=\"".$v."\"";
            }
        }
        return(trim($str, Mailer::$HEADERS_SEPARATOR));
    }

    /**
     * Build a list of name=>email pairs compliant to RFC2822
     *
     * @param array $list A list of name=>email pairs
     * @param string $type The type of the field
     * @return string The generated list
     */
    public static function listAddresses($list = array(), $type = 'to')
    {
        if (empty($list)) {
            return;
        }
        $str = ucfirst(strtolower($type)).': '.self::mailListTagger($list);
        return(trim($str, Mailer::$ADDERSSES_SEPARATOR).Mailer::$LINE_ENDING);
    }

// --------------------
// Utilities
// --------------------

    /**
     * Format a text with a special encoding
     *
     * @param string $txt The text to format
     * @param string $type The type of the encoding : 'plain' or 'ascii'
     * @param bool $spaces Replace all spaces with underscores or not (default is FALSE)
     * @return string The transformed text
     */
    public static function formatText($txt = '', $type = 'plain', $spaces = false)
    {
        switch ($type) {
            case 'ascii' :
                $_txt = '';
                if ($spaces==true) {
                    $txt = str_replace(' ', '_', $txt);
                }
                for ($i=0; $i<strlen($txt);$i++) {
                    $_txt .= self::charAscii($txt[$i]);
                }
                $txt = $_txt;
                break;
            default : break;
        }

        $mailer = Mailer::getInstance();
        $limit = $mailer->getOption('wordwrap_limit');
        $formated='';
        foreach (explode("\n", $txt) as $_line) {
            $_line = trim($_line);
            if (strlen($_line)>$limit) {
                $_line = wordwrap($_line, $limit, Mailer::$LINE_ENDING);
            }
            if (strlen($_line)) {
                $formated .= $_line.Mailer::$LINE_ENDING;
            }
        }
        return $formated;
    }

    /**
     * Search the MIME type of a file
     *
     * @param string $filename The filename to check
     * @return string The associated MIME type
     */
    public static function getMimeType($filename = '')
    {
        $ext = strtolower(substr($filename, strrpos($filename, '.')));
        switch ($ext) {
            case '.jpeg': case '.jpg': $mimetype = 'image/jpeg'; break;
            case '.gif': $mimetype = 'image/gif'; break;
            case '.png': $mimetype = 'image/png'; break;
            case '.txt': $mimetype = 'text/plain'; break;
            case '.html': case '.htm': $mimetype = 'text/html'; break;
            case '.zip': $mimetype = 'application/x-zip-compressed'; break;
            default: $mimetype = 'application/octet-stream';
        }
        return $mimetype;
    }

    /**
     * Converts HTML to plain text
     *
     * @param string $str The HTML content to transform
     * @return string The associated plain text version
     */
    public static function html2text($str)
    {
        return Html2Text::convert($str);
    }

    /**
     * De-duplicate a set of name=>email pairs to let each email just once
     *
     * @param array $array
     * @return array
     */
    public static function deduplicate($array)
    {
        if (empty($array)) {
            return $array;
        }
        $known = array();
        foreach ($array as $_index=>$entry) {
            if (is_array($entry)) {
                foreach ($entry as $i=>$_email) {
                    if (!in_array($_email, $known)) {
                        $known[] = $_email;
                    } else {
                        unset($array[$_index]);
                    }
                }
            } elseif (is_string($entry)) {
                if (!in_array($entry, $known)) {
                    $known[] = $entry;
                } else {
                    unset($array[$_index]);
                }
            }
        }
        return $array;
    }

    /**
     * Clean and build a set of name=>email pairs
     *
     * Arguments can be writtent as :
     * ( 'my@email.address' )
     * ( 'my@email.address', 'my name' )
     * ( array( 'my name'=>'my@email.address' ) )
     * ( array( 'my name'=>'my@email.address', 'another name'=>'another@email.address' ) )
     * ( array( 'my name'=>'my@email.address', 'another@email.address' ) )
     *
     * @return array
     */
    public static function checkPeopleArgs()
    {
        $args = func_get_args();
        if (empty($args)) {
            return array();
        }

        // 1 only email
        if (count($args)==1 && is_string($args[0]) && self::isEmail($args[0])) {
            return array( array($args[0]) );
        }

        // 2 args and 2nd is not an email
        if (
            count($args)==2 &&
            (isset($args[0]) && true===self::isEmail($args[0])) &&
            (isset($args[1]) && false===self::isEmail($args[1]))
        ) {
            return array( array( $args[1]=>$args[0] ) );
        }

        // a set of name=>email pairs
        if (count($args)==1) {
            $args = $args[0];
        }
        $result=array();
        foreach ($args as $name=>$email) {
            if (is_string($name) && true===self::isEmail($email)) {
                $result[] = array( $name=>$email );
            } elseif (is_numeric($name) && true===self::isEmail($email)) {
                $result[] = array($email);
            }
        }
        return $result;
    }

    /**
     * Returns the ASCII equivalent of a character
     *
     * @param string $char The character to test
     * @return string The ASCII valid character
     */
    public static function charAscii($char)
    {
        if (self::isAscii($char)) {
            return $char;
        }
        $char = htmlentities($char);
        return $char;
    }

    /**
     * ASCII validator
     *
     * @param string $string The content to test
     * @return bool
     */
    public static function isAscii($string)
    {
        return !strlen(preg_replace(',[\x09\x0A\x0D\x20-\x7E],sS', '', $string));
    }

    /**
     * Check if an email address is valid
     *
     * @param string $str The email address to check
     * @return bool
     */
    public static function isEmail($str = '')
    {
        $v = new EmailValidator;
        return $v->validate($str);
    }
}

// Endfile


<?php

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

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

namespace EasyWeChat\Menu;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Menu.
 */
class Menu extends AbstractAPI
{
    const API_CREATE = 'https://api.weixin.qq.com/cgi-bin/menu/create';
    const API_GET = 'https://api.weixin.qq.com/cgi-bin/menu/get';
    const API_DELETE = 'https://api.weixin.qq.com/cgi-bin/menu/delete';
    const API_QUERY = 'https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info';
    const API_CONDITIONAL_CREATE = 'https://api.weixin.qq.com/cgi-bin/menu/addconditional';
    const API_CONDITIONAL_DELETE = 'https://api.weixin.qq.com/cgi-bin/menu/delconditional';
    const API_CONDITIONAL_TEST = 'https://api.weixin.qq.com/cgi-bin/menu/trymatch';

    /**
     * Get all menus.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function all()
    {
        return $this->parseJSON('get', [self::API_GET]);
    }

    /**
     * Get current menus.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function current()
    {
        return $this->parseJSON('get', [self::API_QUERY]);
    }

    /**
     * Add menu.
     *
     * @param array $buttons
     * @param array $matchRule
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function add(array $buttons, array $matchRule = [])
    {
        if (!empty($matchRule)) {
            return $this->parseJSON('json', [self::API_CONDITIONAL_CREATE, [
                'button' => $buttons,
                'matchrule' => $matchRule,
            ]]);
        }

        return $this->parseJSON('json', [self::API_CREATE, ['button' => $buttons]]);
    }

    /**
     * Destroy menu.
     *
     * @param int $menuId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function destroy($menuId = null)
    {
        if ($menuId !== null) {
            return $this->parseJSON('json', [self::API_CONDITIONAL_DELETE, ['menuid' => $menuId]]);
        }

        return  $this->parseJSON('get', [self::API_DELETE]);
    }

    /**
     * Test conditional menu.
     *
     * @param string $userId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function test($userId)
    {
        return $this->parseJSON('json', [self::API_CONDITIONAL_TEST, ['user_id' => $userId]]);
    }
}


<?php

namespace Esockets;

use Esockets\Base\AbstractAddress;
use Esockets\Base\AbstractClient;
use Esockets\Base\AbstractConnectionResource;
use Esockets\Base\AbstractProtocol;
use Esockets\Base\BlockingInterface;
use Esockets\Base\CallbackEventListener;
use Esockets\Base\ConnectorInterface;
use Esockets\Base\Exception\SendException;
use Esockets\Base\PingPacket;
use Esockets\Base\PingSupportInterface;
use Esockets\Base\ReaderInterface;
use Esockets\Base\SenderInterface;

/**
 * Враппер над связкой протокол-клиент.
 */
class Client implements ConnectorInterface, ReaderInterface, SenderInterface, BlockingInterface
{
    protected const TIME_LAST_CHECK = 'last_check';
    protected const TIME_LAST_PING = 'last_ping';
    protected const TIME_LAST_RECONNECT = 'last_reconnect';

    private $connection;
    private $protocol;
    private $timeout;
    private $pingInterval; // время успешной работы соединения
    private $reconnectInterval; // время последнего пинга
    private $reconnectSupport = false; // время последней попытки реконнекта
    private $times = [];

    public function __construct(
        AbstractClient $connection,
        AbstractProtocol $protocol,
        int $timeout,
        int $pingInterval,
        int $reconnectInterval
    )
    {
        $this->connection = $connection;
        $this->protocol = $protocol;
        $this->timeout = $timeout;
        $this->pingInterval = $pingInterval;
        $this->reconnectInterval = $reconnectInterval;

        $this->resetTime();
        $this->protocol->onReceive(function () {
            $this->resetTime();
        });
        if ($this->protocol instanceof PingSupportInterface) {
            $this->protocol->onPingReceived(function (PingPacket $ping) {
                $this->resetTime();
                $this->resetTime(self::TIME_LAST_PING);
            });
        }
    }

    public function getPeerAddress(): AbstractAddress
    {
        return $this->connection->getPeerAddress();
    }

    public function getClientAddress(): AbstractAddress
    {
        return $this->connection->getClientAddress();
    }

    /**
     * @inheritdoc
     */
    public function connect(AbstractAddress $address): void
    {
        $this->connection->connect($address);
        $this->reconnectSupport = true;
    }

    /**
     * @inheritdoc
     */
    public function onConnect(callable $callback): CallbackEventListener
    {
        return $this->connection->onConnect($callback);
    }

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

    /**
     * @inheritdoc
     */
    public function disconnect(): void
    {
        $this->connection->disconnect();
    }

    /**
     * @inheritdoc
     */
    public function onDisconnect(callable $callback): CallbackEventListener
    {
        return $this->connection->onDisconnect($callback);
    }

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

    public function ready(): bool
    {
        if (!$this->isConnected()) {
            return false;
        }

        return $this->connection->ready();
    }

    /**
     * @inheritdoc
     */
    public function read(): bool
    {
        if (!$this->isConnected()) {
            return false;
        }

        try {
            return $this->protocol->read();
        } catch (SendException $e) {
            if ($this->isConnected()) {
                $this->disconnect();
            }

            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function returnRead()
    {
        if (!$this->isConnected()) {
            return false;
        }

        return $this->protocol->returnRead();
    }

    /**
     * @inheritdoc
     */
    public function onReceive(callable $callback): CallbackEventListener
    {
        return $this->protocol->onReceive($callback);
    }

    /**
     * @inheritdoc
     */
    public function send($data): bool
    {
        if (!$this->isConnected()) {
            return false;
        }
        return $this->protocol->send($data);
    }

    public function setTimeout(int $timeout)
    {
        $this->timeout = $timeout;
    }

    public function setReconnectInterval(int $interval)
    {
        $this->reconnectInterval = $interval;
    }

    public function getStatistic(): ClientStatistic
    {
        return new ClientStatistic(
            $this->connection->getReceivedBytesCount(),
            $this->connection->getReceivedPacketCount(),
            $this->connection->getTransmittedBytesCount(),
            $this->connection->getTransmittedPacketCount()
        );
    }

    /**
     * @inheritdoc
     */
    public function block(): void
    {
        if ($this->connection instanceof BlockingInterface) {
            $this->connection->block();
        }
    }

    /**
     * @inheritdoc
     */
    public function unblock(): void
    {
        if ($this->connection instanceof BlockingInterface) {
            $this->connection->unblock();
        }
    }

    public function isBlocked(): bool
    {
        if ($this->connection instanceof BlockingInterface) {
            return $this->connection->isBlocked();
        }

        return false;
    }

    /**
     * Поддерживает жизнь соединения.
     * Что делает:
     * - контролирует текущее состояние соединения,
     * - проверяет связь с заданным интервалом,
     * //     * - выполняет чтение входящих данных,
     * - выполняет переподключение при обрыве связи, если это включено (кроме серверного сокета),
     *
     * Возвращает true, если сокет жив, false если не работает.
     * Можно использовать в бесконечном цикле:
     * while ($NET->live()) {
     *     // тут делаем что-то.
     * }
     *
     * @return bool живое соединение, или не живое
     */
    public function live(): bool
    {
        $alive = true;
        $time = time();

        if ($this->isConnected()) {
            if ($this->getTime() + $this->timeout <= $time) {
                $alive = false;
            } elseif (
                $this->getTime(self::TIME_LAST_PING) + $this->pingInterval <= $time
                && $this->getTime() + $this->pingInterval <= $time
            ) {
                // иногда пингуем соединение
                $this->ping();
                $this->resetTime(self::TIME_LAST_PING);
            }
        } elseif ($this->reconnectSupport) {
            if ($this->getTime(self::TIME_LAST_RECONNECT) + $this->reconnectInterval <= $time) {
                if ($this->reconnect()) {
                    $this->resetTime();
                } else {
                    sleep($this->reconnectInterval);
                }
            } else {
                $this->resetTime(self::TIME_LAST_RECONNECT);
            }
            // todo reconnect limit
        } else {
            $alive = false;
        }

        return $alive;
    }

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

    protected function getTime(string $key = self::TIME_LAST_CHECK): int
    {
        return $this->times[$key] ?? 0;
    }

    protected function ping()
    {
        if ($this->protocol instanceof PingSupportInterface) {
            $pingRequest = PingPacket::request(mt_rand(1, 9999));
            $this->protocol->pong(function (PingPacket $pingResponse) use ($pingRequest) {
                if ($pingResponse->isResponse() && $pingRequest->getValue() === $pingRequest->getValue()) {
                    $this->resetTime();
                } else {
                    throw new \RuntimeException(
                        'Unknown ping response value '
                        . $pingRequest->getValue() . ':' . $pingResponse->getValue()
                    );
                }
            });
            $this->protocol->ping($pingRequest);
        }
    }

    protected function resetTime(string $key = self::TIME_LAST_CHECK)
    {
        $this->times[$key] = time();
    }
}


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

namespace RedKiteCms\Action\Block;

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

/**
 * Class EditBlockAction defines the object assigned to edit a block on a web site page
 *
 * @package RedKiteCms\Action
 */
class EditBlockAction extends BaseAction
{
    /**
     * {@inheritdoc}
     */
    public function execute(array $options, $username)
    {
        $data = $options["data"];
        $editOptions = array(
            'page' => $data['page'],
            'language' => $data['language'],
            'country' => $data['country'],
            'slot' => $data['slot'],
            'blockname' => $data['name'],
        );

        $blockManager = $this->app["red_kite_cms.blocks_manager_factory"]->create('edit');
        $blockManager->edit(
            $this->app["red_kite_cms.configuration_handler"]->siteDir(),
            $editOptions,
            $username,
            $data['data']
        );
    }
}


<?php

namespace Phaker\Service\Collection;

use Phaker\Service\ServiceAbstract;

abstract class CollectionAbstract extends ServiceAbstract
{
    /**
     *
     * @var int
     */
    protected $_limit = 5;

    /**
     *
     * @var string
     */
    protected $_entityClass;

    /**
     * (non-PHPdoc)
     * @see \Phaker\Service\ServiceAbstract::getData()
     */
    public function getData()
    {
        $i = 1;
        $data = array();

        while ($i++ <= $this->_limit) {
            $entity = new $this->_entityClass;

            if( ! $entity instanceof \Phaker\Service\Entity\EntityAbstract ) {
                throw new \Exception();
            }

            $data[] = $entity->getData();
        }

        return $data;
    }

}


<?php

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

/**
 * This class manage the upload
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Upload
{
	/**
	 * max size of upload
	 * @var int
	 */
	private $_iMaxFile = 100000;

	/**
	 * error while upload
	 * @var string
	 */
	private $_sError = '';

	/**
	 * array of extensions allowed
	 * @var array
	 */
	private $_aAllowExtension = array();

	/**
	 * final extension
	 * @var string
	 */
	private $_sExtension = null;

	/**
	 * height of image
	 * @var int
	 */
	private $_iHeight = null;

	/**
	 * width of image
	 * @var int
	 */
	private $_iWidth = null;

	/**
	 * image name
	 * @var string
	 */
	private $_sName = null;

	/**
	 * if the crop or resize
	 * @var bool
	 */
	private $_bProportion = true;

	/**
	 * get an upload file
	 *
	 * @access public
	 * @param  string $sFile
	 * @return bool|object
	 */
	public function upload(string $sFile)
	{
		if ($_FILES[$sFile]['error'] > 0) {

			$this->_sError = "Error while the upload";
			return false;
		}

		if ($_FILES[$sFile]['size'] > $this->_iMaxFile) {

			$this->_sError = "The file is too big";
			return false;
		}

		$sExtension = strtolower(substr(strrchr($_FILES[$sFile]['name'], '.'), 1));

		if (count($this->_aAllowExtension) > 0 && !in_array($sExtension ,$this->_aAllowExtension)) {

			$this->_sError = "The extension is not good";
			return false;
		}

		$sPath = str_replace('bundles'.DIRECTORY_SEPARATOR.'lib',
			'data'.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR, __DIR__);

		if ($this->_sExtension === null) { $this->setExtension($sExtension); }

		if ($this->_sName) { $sName = $sPath.$this->_sName.'.'.$this->_sExtension; }
		else { $sName = $sPath.md5(uniqid(rand(), true)).'.'.$this->_sExtension;}

		if ($this->_bProportion === true && ($this->_iWidth || $this->_iHeight)) {

			$aImageSizes = getimagesize($_FILES[$sFile]['tmp_name']);

			$fRatio = min($aImageSizes[0] / $this->_iWidth, $aImageSizes[1] / $this->_iHeight);
    		$iHeight =  $aImageSizes[1] / $fRatio;
    		$iWidth =  $aImageSizes[0] / $fRatio;
    		$fY = ($iHeight - $this->_iHeight) / 2 * $fRatio;
    		$fX = ($iWidth - $this->_iWidth) / 2 * $fRatio;

			$rNewImage = imagecreatefromjpeg($_FILES[$sFile]['tmp_name']);

			$rNewImgTrueColor = imagecreatetruecolor($this->_iWidth , $this->_iHeight);
			imagecopyresampled($rNewImgTrueColor , $rNewImage, 0, 0, $fX, $fY, $this->_iWidth, $this->_iHeight, $iWidth * $fRatio - $fX * 2, $iHeight * $fRatio - $fY * 2);

			imagejpeg($rNewImgTrueColor , $sName, 100);
		}
		else {

			$bResultat = move_uploaded_file($_FILES[$sFile]['tmp_name'], $sName);

			if ($bResultat) { return true; }
		}

	}

	/**
	 * set max size of upload
	 *
	 * @access public
	 * @param  int $iMaxFile
	 * @return \Venus\lib\Upload
	 */
	public function setMaxSize(int $iMaxFile) : Upload
	{
		$this->_iMaxFile = $iMaxFile;
		return $this;
	}

	/**
	 * set allow extensions to upload
	 *
	 * @access public
	 * @param  array $aAllowExtension
	 * @return \Venus\lib\Upload
	 */
	public function setAllowExtension(array $aAllowExtension) : Upload
	{
		$this->_aAllowExtension = $aAllowExtension;
		return $this;
	}

	/**
	 * set extension of final file
	 *
	 * @access public
	 * @param  string $sExtension
	 * @return \Venus\lib\Upload
	 */
	public function setExtension(string $sExtension) : Upload
	{
		$this->_sExtension = $sExtension;
		return $this;
	}

	/**
	 * set height of image
	 *
	 * @access public
	 * @param  int $iHeight
	 * @return \Venus\lib\Upload
	 */
	public function setHeight(int $iHeight) : Upload
	{
		$this->_iHeight = $iHeight;
		return $this;
	}

	/**
	 * set width of image
	 *
	 * @access public
	 * @param  int $iWidth
	 * @return \Venus\lib\Upload
	 */
	public function setWidth(int $iWidth) : Upload
	{
		$this->_iWidth = $iWidth;
		return $this;
	}

	/**
	 * set name of image
	 *
	 * @access public
	 * @param  string $sName
	 * @return \Venus\lib\Upload
	 */
	public function setName(string $sName) : Upload
	{
		$this->_sName = $sName;
		return $this;
	}
}


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

namespace cascade\components\base;

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

/**
 * CollectorModule is the base class for all collected modules in Cascade.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class CollectorModule extends \canis\base\Module implements \canis\base\collector\CollectedObjectInterface
{
    use CollectedObjectTrait;

    /**
     * Get collector name.
     */
    abstract public function getCollectorName();

    /**
     * @inheritdoc
     */
    public function __construct($id, $parent, $config = null)
    {
        if (isset(Yii::$app->params['modules'][$id])) {
            if (is_array($config)) {
                $config = array_merge_recursive($config, Yii::$app->params['modules'][$id]);
            } else {
                $config = Yii::$app->params['modules'][$id];
            }
        }
        if ($this->collectorName) {
            if (!isset(Yii::$app->collectors[$this->collectorName])) {
                throw new Exception('Cannot find the collector ' . $this->collectorName . '!');
            }
            if (!(Yii::$app->collectors[$this->collectorName]->register(null, $this))) {
                throw new Exception('Could not register ' . $this->shortName . ' in ' . $this->collectorName . '!');
            }
        }
        $this->loadSubmodules();

        Yii::$app->collectors->onAfterInit([$this, 'onAfterInit']);

        parent::__construct($id, $parent, $config);
    }

    /**
     * Load the submodule sof this collected module.
     *
     * @return bool load was successful
     */
    public function loadSubmodules()
    {
        $this->modules = $this->submodules;

        foreach ($this->submodules as $module => $settings) {
            $mod = $this->getModule($module);
            $mod->init();
        }

        return true;
    }

    /**
     * Get submodules.
     *
     * @return array submodules of this modules
     */
    public function getSubmodules()
    {
        return [];
    }

    /**
     * Action after module init.
     *
     * @param Event $event the event parameter
     *
     * @return bool ran successfully
     */
    public function onAfterInit($event)
    {
        return true;
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Container;

use Autarky\Providers\AbstractProvider;

/**
 * Provides the application with a container.
 *
 * This service provider is vital to the framework.
 */
class ContainerProvider extends AbstractProvider
{
	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$this->app->setContainer($dic = new Container);
		$dic->instance('Autarky\Application', $this->app);
	}
}


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

namespace CmsUser\Factory\Form;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsCommon\Form\FormInterface,
    CmsUser\Options\FormOptionsInterface,
    CmsUser\Options\ModuleOptions;

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

        $creationOptions = $options->toArray();
        $creationOptions['label'] = 'Changing Email Address';

        /* @var $form FormInterface */
        $form = $serviceLocator->get($options->getUserEntityClass(), $creationOptions);
        $form->setName('change-email-form');
        $form->setElementGroup([
            'question',
            'answerVerify',
            'email',
        ])->setValidationGroup([
            'answerVerify',
            'email',
        ]);

        $form->get('email')->setLabel('New Email');

        return $form;
    }
}


<?php
/**
 * Definition of Text service
 *
 * @copyright  2014-today Justso GmbH, Frankfurt, Germany
 * @author     j.schirrmacher@justso.de
 *
 * @package    justso\service
 */

namespace justso\justtexts;

use justso\justapi\InvalidParameterException;
use justso\justapi\RestService;
use justso\justapi\SystemEnvironmentInterface;

/**
 * Handles requests regarding website page texts.
 *
 * @package    justso\service
 */
class TextService extends RestService
{
    private $appRoot;
    private $languages;

    /**
     * Initialize private variables.
     *
     * @param SystemEnvironmentInterface $environment
     */
    public function __construct(SystemEnvironmentInterface $environment)
    {
        parent::__construct($environment);
        $bootstrap = $environment->getBootstrap();
        $this->appRoot = $bootstrap->getAppRoot();
        $config = $bootstrap->getConfiguration();
        $this->languages = $config['languages'];
    }

    /**
     * Returns the content of a text container.
     *
     * @throws \justso\justapi\InvalidParameterException
     */
    public function getAction()
    {
        if (!preg_match('/\/page\/(\w+[\-\w]*)\/text\/(..)(\/(\w+))?$/', $this->name, $matches)) {
            throw new InvalidParameterException("Invalid parameters");
        }
        $pageName = $matches[1];
        $language = $matches[2];
        $pageTexts = $this->getTextModel($pageName);
        if (empty($matches[4])) {
            $result = array_values($pageTexts->getTextsWithBaseTexts($language));
        } else {
            $result = $pageTexts->getText($matches[4], $language);
        }
        $this->environment->sendJSONResult($result);
    }

    /**
     * Creates a new text container.
     *
     * @throws \justso\justapi\InvalidParameterException
     */
    public function postAction()
    {
        if (!preg_match('/\/page\/(\w+[\-\w]*)\/text\/(..)$/', $this->name, $matches)) {
            throw new InvalidParameterException("Invalid parameters");
        }
        list($dummy, $pageName, $language) = $matches;

        $request = $this->environment->getRequestHelper();
        $name = $request->getIdentifierParam('name');
        $content = $request->getParam('content', '');

        try {
            $pageTexts = $this->getTextModel($pageName);
            $text = $pageTexts->addTextContainer($name, $this->filter($content), $language);
            $this->environment->sendJSONResult($text);
        } catch (\Exception $e) {
            throw new InvalidParameterException($e->getMessage());
        }
    }

    /**
     * Changes an existing text container.
     *
     * @throws \justso\justapi\InvalidParameterException
     */
    public function putAction()
    {
        if (!preg_match('/\/page\/(\w+[\-\w]*)\/text\/(..)\/(\w+)$/', $this->name, $matches)) {
            throw new InvalidParameterException("Invalid parameters");
        }
        list($dummy, $pageName, $language, $oldName) = $matches;

        $request = $this->environment->getRequestHelper();
        $newName = $request->getIdentifierParam('name');
        $content = $request->getParam('content', '');

        try {
            $pageTexts = $this->getTextModel($pageName);
            $text = $pageTexts->modifyTextContainer($oldName, $newName, $this->filter($content), $language);
            $this->environment->sendJSONResult($text);
        } catch (\Exception $e) {
            throw new InvalidParameterException($e->getMessage());
        }
    }

    /**
     * Deletes a text container.
     *
     * @throws \justso\justapi\InvalidParameterException
     */
    public function deleteAction()
    {
        // @todo It's not necessary to specify a language, since the texts in all languages are removed.

        if (!preg_match('/\/page\/(\w+[\-\w]*)\/text\/..\/(\w+)$/', $this->name, $matches)) {
            throw new InvalidParameterException("Invalid parameters");
        }
        list($dummy, $pageName, $containerName) = $matches;
        $pageTexts = $this->getTextModel($pageName);
        $pageTexts->deleteTextContainer($containerName);

        $this->environment->sendJSONResult('ok');
    }

    /**
     * @param string $pageName
     * @return Text
     */
    protected function getTextModel($pageName)
    {
        return $this->environment->getDIC()->get('\justso\justtexts\Text', [
            $this->environment,
            $pageName
        ]);
    }

    /**
     * Filters out unwanted html code like formatting and so on
     *
     * @param string $content
     * @return string
     */
    private function filter($content)
    {
        return strip_tags($content, '

');
    }
}


<?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\View\Helper;

use Zend\Form\FieldsetInterface;
use Zend\Form\FormInterface;
use Zend\Form\View\Helper\Form as ZendForm;

/**
 * A {@link Form} class.
 *
 * @package Xloit\Bridge\Zend\Form\View\Helper
 */
class Form extends ZendForm
{
    /**
     * Render a form from the provided form.
     *
     * @param FormInterface $form
     *
     * @return string
     */
    public function render(FormInterface $form)
    {
        if (method_exists($form, 'prepare')) {
            $form->prepare();
        }

        // Set form role
        if (!$form->getAttribute('role')) {
            $form->setAttribute('role', 'form');
        }

        $formContent = '';

        foreach ($form as $element) {
            /** @var $element \Zend\Form\Form */
            if ($element instanceof FieldsetInterface) {
                /** @noinspection PhpUndefinedMethodInspection */
                $formContent .= $this->getView()->formCollection($element);
            } else {
                $element->setOption('_form', $form);

                /** @noinspection PhpUndefinedMethodInspection */
                $formContent .= $this->getView()->formRow($element);
            }
        }

        return $this->openTag($form) . $formContent . $this->closeTag();
    }
}


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

namespace Controller\Security;

use RedKiteCms\Rendering\Controller\Security\AuthenticationController as BaseAuthenticationController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to login into the backend
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Security
 */
class AuthenticationController extends BaseAuthenticationController
{
    /**
     * Login action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function loginAction(Request $request, Application $app)
    {
        $options = array(
            "is_ajax" => $request->isXmlHttpRequest(),
            "error" => $app['security.last_error']($request),
            "last_username" => $app['session']->get('_security.last_username'),
            "template_assets" => $app["red_kite_cms.template_assets"],
            "twig" => $app["twig"],
            "red_kite_cms_config" => $app["red_kite_cms.configuration_handler"],
            "assets" => array(
                'getExternalStylesheets' => array(
                    $app["red_kite_cms.configuration_handler"]->webDir(
                    ) . '/components/redkitecms/twitter-bootstrap/css/bootstrap.min.css',
                    $app["red_kite_cms.configuration_handler"]->webDir() . '/sb-admin-2/css/sb-admin-2.css',
                ),
            ),
        );

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


<?php

/**
 * @file
 * Contains Pipeware\Pipeline\Containerized
 */

namespace Pipeware\Pipeline;

use Pipeware\Pipeline\Pipeline as PipewareInterface;
use Pipeware\Stage\RequestHandler;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SyberIsle\Pipeline\Pipeline;

/**
 * Pipeline implementation that uses a PSR-11 Container to instantiate the middleware stack
 *
 * @package Pipeware\Pipeline
 */
class Containerized
	implements PipewareInterface
{
	use IsPipeline {
		IsPipeline::handleStage as traitHandleStage;
	}

	/**
	 * @var ContainerInterface
	 */
	protected $container;

	/**
	 * The list of middleware
	 *
	 * @var array
	 */
	protected $stages = [];

	/**
	 * The list of resolved middleware
	 *
	 * @var array
	 */
	protected $resolved;

	public function __construct($container, $middleware = [])
	{
		$this->container = $container;
		foreach ((array)$middleware as $stage) {
			$this->handleStage($this->stages, $stage);
		}
	}

	/**
	 * Pushes the middleware on pipeline
	 *
	 * @param string|MiddlewareInterface $stage
	 * @return Pipeline
	 */
	public function pipe($stage)
	{
		$pipeline = new self($this->container, $this->stages);
		$this->handleStage($pipeline->stages, $stage);

		return $pipeline;
	}

	/**
	 * Reverses the order of the stages
	 *
	 * @return Containerized
	 */
	public function withReversedOrder(): Containerized
	{
		return new self($this->container, array_reverse($this->stages));
	}

	/**
	 * Returns the iterator
	 *
	 * @return \Generator|\Traversable
	 */
	public function getIterator()
	{
		$this->resolve();
		foreach ($this->resolved as &$stage) {
			yield $stage;
		}
	}

	/**
	 * Returns the list of stages
	 *
	 * This will resolve any string based middleware from the given container
	 *
	 * @return array
	 * @throws \Psr\Container\ContainerExceptionInterface
	 * @throws \Psr\Container\NotFoundExceptionInterface
	 */
	public function stages()
	{
		$this->resolve();

		return $this->resolved;
	}

	/**
	 * Builds the stage as a
	 *
	 * @param $stage
	 * @return MiddlewareInterface
	 * @throws \Psr\Container\ContainerExceptionInterface
	 * @throws \Psr\Container\NotFoundExceptionInterface
	 */
	protected function build($stage)
	{
		if ($stage instanceof MiddlewareInterface) {
			return $stage;
		}

		if ($this->container->has($stage)) {
			$stage = $this->container->get($stage);
			if ($stage instanceof RequestHandlerInterface) {
				return new RequestHandler($stage);
			}

			if ($stage instanceof MiddlewareInterface) {
				return $stage;
			}

			throw new \RuntimeException("Stage is not a valid " . MiddlewareInterface::class);
		}

		// Support aura/di
		if (method_exists($this->container, 'newInstance')) {
			return $this->container->newInstance($stage);
		}

		throw new \RuntimeException("Unable to resolve $stage");
	}

	/**
	 * {@inheritdoc}
	 */
	protected function handleStage(&$stages, $stage)
	{
		if (is_string($stage)) {
			$stages[] = $stage;
		}
		else {
			$this->traitHandleStage($stages, $stage);
		}
	}

	/**
	 * @param $stage
	 * @param $needle
	 * @return bool
	 */
	protected function matches($stage, $needle)
	{
		return $stage == $needle;
	}

	/**
	 * Resolves all stages to middleware
	 */
	protected function resolve()
	{
		if ($this->resolved) {
			return;
		}

		$this->resolved = [];
		foreach ($this->stages as $stage) {
			$this->resolved[] = $this->build($stage);
		}
	}
}


<?php

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

/**
 * Google Map Pro
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0.2
 */
class Geocoding
{
    /**
     * get the URL with the signature for the Pro account of Google Map
     *
     * @access public
     * @param unknown $sUrlToSign
     * @param unknown $sClientId
     * @param unknown $sPrivateKey
     * @return string
     */
    public static function signUrlForGoogle(string $sUrlToSign, string $sClientId, string $sPrivateKey) : string
    {
        $aUrl = parse_url($sUrlToSign);
        $aUrl['query'] .= '&client=' .$sClientId;

        $aUrlToSign = $aUrl['path']."?".$aUrl['query'];

        $decodedKey = base64_decode(str_replace(array('-', '_'), array('+', '/'), $sPrivateKey));

        $sSignature = hash_hmac("sha1", $aUrlToSign, $decodedKey, true);

        $sEncodedSignature = str_replace(array('+', '/'), array('-', '_'), base64_encode($sSignature));

        $sOriginalUrl = $aUrl['scheme']."://".$aUrl['host'].$aUrl['path'] . "?".$aUrl['query'];

        return $sOriginalUrl. '&signature='. $sEncodedSignature;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Praxigento\BonusHybrid\Service\Calc\Z\Helper;

class GetCustomersIds
{
    /** @var array of cached Customers IDs keys by calculation ID */
    private $cachedIds = [];
    /** @var \Praxigento\BonusHybrid\Repo\Query\SignUpDebit\GetLastCalcIdForPeriod */
    private $queryGetCalcId;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit */
    private $daoRegistry;

    public function __construct(
        \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit $daoRegistry,
        \Praxigento\BonusHybrid\Repo\Query\SignUpDebit\GetLastCalcIdForPeriod $queryGetCalcId
    ) {
        $this->daoRegistry = $daoRegistry;
        $this->queryGetCalcId = $queryGetCalcId;
    }

    /**
     * Get IDs of the customers who was processed in Sign Up Volumes Debit calculation.
     *
     * @param int|null $calcId ID of the calculation or null for the last one
     * @return array of customers ids who was processed in Sign Up Volume Debit.
     */
    public function exec($calcId = null)
    {
        if (is_null($calcId)) {
            $calcId = $this->queryGetCalcId->exec();
        }
        if (!isset($this->cachedIds[$calcId])) {
            $ids = [];
            $where = \Praxigento\BonusHybrid\Repo\Data\Registry\SignUpDebit::A_CALC_REF . '=' . (int)$calcId;
            $rs = $this->daoRegistry->get($where);
            /** @var \Praxigento\BonusHybrid\Repo\Data\Registry\SignUpDebit $one */
            foreach ($rs as $one) {
                $ids[] = $one->getCustomerRef();
            }
            $this->cachedIds[$calcId] = $ids;
        }
        return $this->cachedIds[$calcId];
    }
}


<?php

namespace Gaufrette\Core\File;

use Gaufrette\Core\File as FileInterface;
use Gaufrette\Core\Filesystem;

/**
 * Build a new file instance with lazy loading.
 */
final class LazyFile implements FileInterface
{
    /**
     * @type FileInterface
     */
    private $file;

    /**
     * @type Filesystem
     */
    private $filesystem;

    /**
     * @type bool
     */
    private $hydrated;

    /**
     * @param FileInterface $file
     * @param Filesystem    $filesystem
     */
    public function __construct(FileInterface $file, Filesystem $filesystem)
    {
        $this->file       = $file;
        $this->filesystem = $filesystem;
        $this->hydrated   = false;
    }

    /**
     * {@inheritdoc}
     */
    public function __clone()
    {
        return $this->duplicate($this->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function duplicate($name)
    {
        $this->hydrate();

        return $this->file->duplicate($name);
    }

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

    /**
     * {@inheritdoc}
     */
    public function getContent()
    {
        $this->hydrate();

        return $this->file->getContent();
    }

    /**
     * {@inheritdoc}
     */
    public function setContent($content)
    {
        $this->hydrate();
        $this->file->setContent($content);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSize()
    {
        $this->hydrate();

        return $this->file->getSize();
    }

    /**
     * {@inheritdoc}
     */
    public function setSize($size)
    {
        $this->hydrate();
        $this->file->setSize($size);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getChecksum()
    {
        $this->hydrate();

        return $this->file->getChecksum();
    }

    /**
     * {@inheritdoc}
     */
    public function setChecksum($checksum)
    {
        $this->hydrate();
        $this->file->setChecksum($checksum);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getMimeType()
    {
        $this->hydrate();

        return $this->file->getMimeType();
    }

    /**
     * {@inheritdoc}
     */
    public function setMimeType($mimetype)
    {
        $this->hydrate();
        $this->file->setMimeType($mimetype);

        return $this;
    }

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

        return $this->file->getMetadata($key);
    }

    /**
     * {@inheritdoc}
     */
    public function setMetadata(array $metadata)
    {
        $this->hydrate();
        $this->file->setMetadata($metadata);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getLastAccess()
    {
        $this->hydrate();

        return $this->file->getLastAccess();
    }

    /**
     * {@inheritdoc}
     */
    public function setLastAccess(\DateTime $lastAccess)
    {
        $this->hydrate();
        $this->file->setLastAccess($lastAccess);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getLastModification()
    {
        $this->hydrate();

        return $this->file->getLastModification();
    }

    /**
     * {@inheritdoc}
     */
    public function setLastModification(\DateTime $lastModification)
    {
        $this->hydrate();
        $this->file->setLastModification($lastModification);

        return $this;
    }

    /**
     * Get the file from the filesystem. Skip if only hydrated.
     *
     * @return
     */
    private function hydrate()
    {
        if (true === $this->hydrated) {
            return;
        }

        $this->filesystem->get($this->file);
        $this->hydrated = true;
    }
}


<?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\Content\BlockManager;

use JMS\Serializer\SerializerInterface;
use RedKiteCms\Content\Block\BlockFactoryInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * This object is assigned to instantiate a new BlockManager object from the action required
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerFactory
{
    /**
     * @var SerializerInterface
     */
    private $serializer;
    /**
     * @var BlockFactoryInterface
     */
    private $blockFactory;
    /**
     * @var OptionsResolver
     */
    private $optionsResolver;

    /**
     * Constructor
     *
     * @param SerializerInterface $serializer
     * @param OptionsResolver $optionsResolver
     */
    public function __construct(SerializerInterface $serializer, OptionsResolver $optionsResolver)
    {
        $this->serializer = $serializer;
        $this->optionsResolver = $optionsResolver;
    }

    /**
     * Creates a block manager object
     *
     * @param $action
     * @return null|\RedKiteCms\Content\BlockManager\BlockManager
     */
    public function create($action)
    {
        $actionName = ucfirst($action);
        $class = sprintf('RedKiteCms\Content\BlockManager\BlockManager%s', $actionName);

        if (!class_exists($class)) {
            return null;
        }

        $reflectionClass = new \ReflectionClass($class);

        return $reflectionClass->newInstance($this->serializer, $this->optionsResolver);
    }
}


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

namespace cascade\components\dataInterface;

use cascade\models\DataInterfaceLog;
use Yii;

/**
 * @author Jacob Morrison <email@ofjacob.com>
 */
trait ActionTrait
{
    /**
     */
    protected $_interface;
    /**
     */
    protected $_status;
    /**
     */
    protected $_log;
    /**
     */
    protected $_registry = [];

    public function __sleep()
    {
        if (is_object($this->_interface)) {
            $this->_interface = $this->_interface->systemId;
        }

        return parent::__sleep();
    }

    public function setInterface($interface)
    {
        $this->_interface = $interface;
    }

    public function getInterface()
    {
        if (!empty($this->_interface)
            && is_string($this->_interface)
            && Yii::$app->collectors['dataInterfaces']->has($this->_interface)
            ) {
            $this->_interface = Yii::$app->collectors['dataInterfaces']->getOne($this->_interface);
        }
        return $this->_interface;
    }

    public function resumeLog($log)
    {
        $this->_log = $log;
        $this->_log->status = 'running';
        $this->_log->started = date("Y-m-d G:i:s");
        $this->_log->peak_memory = memory_get_usage();
        $this->_log->save();
    }

    /**
     *
     */
    public function start()
    {
        return $this->save() && $this->_id = $this->log->id;
    }

    /**
     *
     */
    public function end($endInterrupted = false)
    {
        return $this->log->end($endInterrupted);
    }

    /**
     *
     */
    public function save()
    {
        parent::save();

        $this->log->message = serialize($this->status);
        $newPeak = memory_get_usage();
        if ($newPeak > $this->log->peak_memory) {
            $this->log->peak_memory = $newPeak;
        }
        if (empty($this->interface)) {
            return true;
        }

        return $this->log->save();
    }

    /**
     * Get log.
     */
    public function getLog()
    {
        if (!isset($this->_log)) {
            $this->_log = new DataInterfaceLog();
            if (!empty($this->interface)) {
                $this->_log->data_interface_id = $this->interface->interfaceObject->id;
            }
            $this->_log->status = 'running';
            $this->_log->started = date("Y-m-d G:i:s");
            $this->_log->peak_memory = memory_get_usage();
        }

        return $this->_log;
    }

    /**
     * Get status.
     */
    public function getStatus()
    {
        if (isset($this->_log)) {
            $this->_status = $this->log->statusLog;
        } elseif (!isset($this->_status)) {
            $this->_status = new Status($this->log);
        }

        return $this->_status;
    }

    /**
     * Get id.
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     *
     */
    public function addRegistry($key, $objectId)
    {
        $this->_registry[$key] = $objectId;
    }

    /**
     * Get registry.
     */
    public function getRegistry()
    {
        return $this->_registry;
    }

    /**
     *
     */
    public function objectInRegistry($objectId)
    {
        return in_array($objectId, $this->_registry);
    }

    /**
     *
     */
    public function keyInRegistry($keyId)
    {
        return isset($this->_registry[$keyId]);
    }
}


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

namespace VinceT\AdminBundle\Menu;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Knp\Menu\FactoryInterface;
use Knp\Menu\MenuItemInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;
use VinceT\AdminBundle\Event\MenuCreateEvent;
use VinceT\AdminBundle\Event\MenuEvents;

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

    /**
     *__constructor
     *
     * @param FactoryInterface   $factory   Menu Factory
     * @param ContainerInterface $container Container
     */
    public function __construct(FactoryInterface $factory, ContainerInterface $container)
    {
        $this->factory = $factory;
        $this->setContainer($container);
    }

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

    /**
     * Create the main menu
     *
     * @param Request $request [description]
     *
     * @return [type]
     */
    public function createMainMenu(Request $request)
    {
        $menu = $this->factory->createItem('root');

        $menu->setCurrentUri($request->getBaseUrl().$request->getPathInfo());

        // create menu from admin pool
        $admin_pool = $this->container->get('sonata.admin.pool');
        foreach ($admin_pool->getDashboardGroups() as $group) {
            $menu->addChild($group['label'], array('translationDomain'=>$group['label_catalogue']));
            foreach ($group['items'] as $admin) {
                if ( $admin->hasRoute('list') && $admin->isGranted('LIST') ) {
                    $menu[$group['label']]->addChild($admin->getLabel(), array('admin'=>$admin));
                }
            }
        }

        $dispatcher = $this->container->get('event_dispatcher');

        $event = new MenuCreateEvent($menu);
        $dispatcher->dispatch(MenuEvents::ADMIN_MENU_CREATE, $event);

        return $menu;
    }

}


<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Bridge\Console\Command;

use Bridge\Action\AbstractAction;
use Bridge\RegistryAwareInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command for executing actions.
 */
class ExecuteCommand extends BridgeCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('execute')
            ->setDescription('Execute an action')
            ->addArgument('name', InputArgument::REQUIRED, 'Name')
            ->addArgument('arguments', InputArgument::IS_ARRAY, 'Arguments');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $action = $this->registry->get($input->getArgument('name'));

        if (!$action instanceof AbstractAction) {
            throw new \Exception(sprintf('Expected action, got %s', get_class($action)));
        }

        if ($action instanceof RegistryAwareInterface) {
            $action->setRegistry($this->registry);
        }

        $response = $action->execute($input->getArgument('arguments'));

        $output->writeln('RESPONSE METADATA');
        $output->writeln(sprintf('<info>Type</info>: %s', gettype($response)));

        $output->writeln('RESPONSE DATA');
        if (!is_callable(array($response, '__toString'))) {
            $response = serialize($response);
        }
        $output->writeln((string) $response);

        $output->writeln('EXTRA DATA');
        foreach ($action->getExtraData() as $key => $value) {
            $output->writeln(sprintf('<info>%s</info>: %s', $key, $value));
        }
    }
}


<?php

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

use \VenusBash\Bash as Bash;
use \Venus\lib\Log\AbstractLogger as AbstractLogger;
use \Venus\lib\Log\LogLevel as LogLevel;

/**
 * This class manage the debug
 *
 * @category  	lib
 * @package   	lib\Entity
 * @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 Debug extends AbstractLogger
{
    /**
     * variable to activate or not the debug
     * @var boolean
     */
    private static $_bActivateDebug = false;

    /**
     * variable to activate or not the error
     * @var boolean
     */
    private static $_bActivateError = false;

    /**
     * variable to activate or not the exception
     * @var boolean
     */
    private static $_bActivateException = false;

    /**
     * variable to activate or not the debug
     * @var boolean
     */
    private static $_sFileLog = null;

    /**
     * first or not activation
     * @var boolean
     */
    private static $_bFirstActivation = true;

    /**
     * kind of report log
     * @var string error_log|screen|all
     */
    private static $_sKindOfReportLog = 'error_log';

    /**
     * instance of logger
     * @var \Venus\lib\Debug
     */
    private static $_oInstance;

    /**
     * Send back the isntance or create it
     *
     * @access public
     */
    public static function getInstance() : Debug
    {
        if (!(self::$_oInstance instanceof self)) { self::$_oInstance = new self(); }

        return self::$_oInstance;
    }

    /**
     * activate debug
     *
     * @access public
     * @return void
     */
    public static function activateDebug()
    {
        if (self::$_bFirstActivation === true) {

            self::_setFileNameInErrorFile();
            self::$_bFirstActivation = false;
        }

        self::_initLogFile();
        self::$_bActivateDebug = true;
        self::activateError(E_ALL);
        self::activateException(E_ALL);
    }

    /**
     * activate debug
     *
     * @access public
     * @return void
     */
    public static function deactivateDebug()
    {
        self::$_bActivateDebug = false;
    }

    /**
     * check if debug is activate or not
     *
     * @access public
     * @return boolean
     */
    public static function isDebug() : bool
    {
        return self::$_bActivateDebug;
    }

    /**
     * activate error reporting
     *
     * @access public
     * @param  int $iLevel level of error
     * @return void
     */
    public static function activateError($iLevel)
    {
        if (self::$_bFirstActivation === true) {

            self::_setFileNameInErrorFile();
            self::$_bFirstActivation = false;
        }

        self::_initLogFile();
        self::$_bActivateError = true;

        error_reporting($iLevel);

        set_error_handler(function ($iErrNo, $sErrStr, $sErrFile, $iErrLine)
        {
            $aContext = array('file' => $sErrFile, 'line' => $iErrLine);

            $sType = self::getTranslateErrorCode($iErrNo);

            self::getInstance()->$sType($sErrStr, $aContext);

            return true;
        }, $iLevel);

        register_shutdown_function(function()
        {
            if (null !== ($aLastError = error_get_last())) {

                $aContext = array('file' => $aLastError['file'], 'line' => $aLastError['line']);

                $sType = self::getTranslateErrorCode($aLastError['type']);

                self::getInstance()->$sType($aLastError['message'], $aContext);
            }
        });
    }

    /**
     * activate error reporting
     *
     * @access public
     * @return void
    */
    public static function deactivateError()
    {
        self::$_bActivateError = false;
    }

    /**
     * check if error reporting is activate or not
     *
     * @access public
     * @return boolean
     */
    public static function isError() : bool
    {
        return self::$_bActivateError;
    }

    /**
     * activate Exception
     *
     * @access public
     * @param  int $iLevel level of error
     * @return void
     */
    public static function activateException(int $iLevel)
    {
        if (self::$_bFirstActivation === true) {

            self::_setFileNameInErrorFile();
            self::$_bFirstActivation = false;
        }

        self::_initLogFile();
        self::$_bActivateException = true;

        set_exception_handler(function ($oException)
        {
            $aContext = array('file' => $oException->getFile(), 'line' => $oException->getLine());
            self::getInstance()->critical($oException->getMessage(), $aContext);
        });
    }

    /**
     * activate Exception
     *
     * @access public
     * @return void
     */
    public static function deactivateException()
    {
        self::$_bActivateException = false;
    }

    /**
     * check if Exception is activate or not
     *
     * @access public
     * @return boolean
     */
    public static function isException() : bool
    {
        return self::$_bActivateException;
    }

    /**
     * set the kind of report Log
     *
     * @access public
     * @param  string $sKindOfReportLog
     * @return void
     */
    public static function setKindOfReportLog(string $sKindOfReportLog)
    {
        if ($sKindOfReportLog === 'screen' || $sKindOfReportLog === 'all') { self::$_sKindOfReportLog = $sKindOfReportLog; }
        else { self::$_sKindOfReportLog = 'error_log'; }
    }

    /**
     * get the kind of report Log
     *
     * @access public
     * @return string
     */
    public static function getKindOfReportLog() : string
    {
        return self::$_sKindOfReportLog;
    }

    /**
     * get the code by LogLevel adapt to the PSR-3
     *
     * @access public
     * @param  int $iCode
     * @return string
     */
    public static function getTranslateErrorCode(int $iCode) : string
    {
        if ($iCode === 1 && $iCode === 16 && $iCode === 256 && $iCode === 4096) { return LogLevel::ERROR; }
        else if ($iCode === 2 && $iCode === 32 && $iCode === 128 && $iCode === 512) { return LogLevel::WARNING; }
        else if ($iCode === 4 && $iCode === 64) { return LogLevel::EMERGENCY; }
        else if ($iCode === 8 && $iCode === 1024) { return LogLevel::NOTICE; }
        else if ($iCode === 2048 && $iCode === 8192 && $iCode === 16384) { return LogLevel::INFO; }
        else return LogLevel::DEBUG;
    }

    /**
     * System is unusable.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function emergency($message, array $context = array())
    {
        $this->log(LogLevel::EMERGENCY, $message, $context);
    }

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function alert($message, array $context = array())
    {
        $this->log(LogLevel::ALERT, $message, $context);
    }

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function critical($message, array $context = array())
    {
        $this->log(LogLevel::CRITICAL, $message, $context);
    }

    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function error($message, array $context = array())
    {
        $this->log(LogLevel::ERROR, $message, $context);
    }

    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function warning($message, array $context = array())
    {
        $this->log(LogLevel::WARNING, $message, $context);
    }

    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function notice($message, array $context = array())
    {
        $this->log(LogLevel::NOTICE, $message, $context);
    }

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function info($message, array $context = array())
    {
        $this->log(LogLevel::INFO, $message, $context);
    }

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array $context
     * @return null
    */
    public function debug($message, array $context = array())
    {
        $this->log(LogLevel::DEBUG, $message, $context);
    }

    /**
     * set the name of the called
     *
     * @access public
     * @return void
     */
    private static function _setFileNameInErrorFile()
    {
        /**
         * We see if it's a cli call or a web call
         */

        if (defined('BASH_CALLED')) {

            error_log(Bash::setColor('############### '.BASH_CALLED.' ###############', 'cyan'));
        }
        else {

            if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
                error_log(Bash::setColor('############### ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . ' ###############', 'cyan'));
            }
        }
    }

    /**
     * init the log file (error_log)
     *
     * @access private
     * @return void
     */
    private static function _initLogFile()
    {
        self::$_sFileLog = str_replace(DIRECTORY_SEPARATOR.'kernel'.DIRECTORY_SEPARATOR.'lib', '', __DIR__).DIRECTORY_SEPARATOR.
            "data".DIRECTORY_SEPARATOR."log".DIRECTORY_SEPARATOR."php-error.log";

        ini_set("log_errors", 1);
        ini_set("error_log", self::$_sFileLog);

        if (file_exists(self::$_sFileLog) === false) { file_put_contents(self::$_sFileLog, ''); }
    }

    /**
     * constructor in private for the singleton
     *
     * @access private
     * @return \Venus\lib\Debug
     */
    private function __construct() {}

    /**
     * not allowed to clone a object
     *
     * @access private
     * @return \Venus\lib\Debug
     */
    private function __clone() {}
}


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

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Core\RedKiteCms\Core\Form\PageCollection\PageType;
use RedKiteCms\Core\RedKiteCms\Core\Form\PageCollection\SeoType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ShowPageCollectionController is the object assigned to show the page collection dashboard interface
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Page
 */
abstract class ShowPageCollectionController extends BasePageCollectionController
{
    /**
     * Implements the action to show the page collection dashboard interface
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function show(array $options)
    {
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);
        $this->options = $resolver->resolve($options);

        $pagesParser = $this->options["pages_collection_parser"];
        $pages = $pagesParser
            ->contributor($this->options["username"])
            ->parse()
            ->pages()
        ;

        $this->options["template_assets"]->boot('dashboard');
        $templates = $this->options["theme"]->templates();
        $formFactory = $this->options['form_factory'];
        $form = $formFactory->create(new PageType(array_combine($templates, $templates)));
        $pageForm = $form->createView();
        $form = $formFactory->create(new SeoType());
        $seoForm = $form->createView();

        $template = 'RedKiteCms/Resources/views/Dashboard/pages.html.twig';
        $languages = $this->options["configuration_handler"]->languages();

        return $options["twig"]->render(
            $template,
            array(
                "template_assets_manager" => $this->options["template_assets"],
                "pages" => rawurlencode(json_encode($pages)),
                "pageForm" => $pageForm,
                "seoForm" => $seoForm,
                "version" => ConfigurationHandler::getVersion(),
                "home_template" => $this->options["theme"]->homepageTemplate(),
                "languages" => $languages,
            )
        );
    }

    /**
     * Configures the options for the resolver
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setRequired(
            array(
                'configuration_handler',
                'pages_collection_parser',
                'theme',
                'template_assets',
                'form_factory',
                'twig',
            )
        );

        $resolver->setAllowedTypes(
            array(
                'configuration_handler' => '\RedKiteCms\Configuration\ConfigurationHandler',
                'pages_collection_parser' => '\RedKiteCms\Content\PageCollection\PagesCollectionParser',
                'theme' => '\RedKiteCms\Content\Theme\Theme',
                'template_assets' => '\RedKiteCms\Rendering\TemplateAssetsManager\TemplateAssetsManager',
                'form_factory' => '\Symfony\Component\Form\FormFactory',
                'twig' => '\Twig_Environment',
            )
        );
    }
}