<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types = 1);

namespace Cawa\Renderer;

use Cawa\Events\DispatcherFactory;
use Cawa\Events\TimerEvent;
use Cawa\Intl\TranslatorFactory;

class HtmlPage extends HtmlContainer
{
    use TranslatorFactory;
    use AssetTrait;
    use DispatcherFactory;

    /**
     *
     */
    public function __construct()
    {
        parent::__construct('<html>');

        $this->head = new HtmlContainer('<head>');
        $this->add($this->head);

        $this->footer = new Container();

        $this->body = new HtmlContainer('<body>');
        $this->add($this->body);
    }

    /**
     * @var HtmlContainer
     */
    private $head;

    /**
     * @return HtmlContainer
     */
    public function getHead() : HtmlContainer
    {
        return $this->head;
    }

    /**
     * @var HtmlContainer
     */
    private $footer;

    /**
     * @return Container
     */
    public function getFooter() : Container
    {
        return $this->footer;
    }

    /**
     * @var HtmlContainer
     */
    private $body;

    /**
     * @return HtmlContainer
     */
    public function getBody() : HtmlContainer
    {
        return $this->body;
    }

    /**
     * @var HtmlElement
     */
    protected $headTitle;

    /**
     * @return bool
     */
    public function hasHeadTitle() : bool
    {
        return !is_null($this->headTitle);
    }

    /**
     * @return string|null
     */
    public function getHeadTitle()
    {
        return $this->headTitle ? $this->headTitle->getContent() : null;
    }

    /**
     * @param string $title
     *
     * @return $this|self
     */
    public function setHeadTitle(string $title) : self
    {
        if (!$this->headTitle) {
            $this->headTitle = new HtmlElement('<title>');
            $this->head->addFirst($this->headTitle);
        }
        $this->headTitle->setContent($title);

        return $this;
    }

    /**
     * @var HtmlElement
     */
    protected $headDescription;

    /**
     * @return bool
     */
    public function hasHeadDescription() : bool
    {
        return !is_null($this->headDescription);
    }

    /**
     * @return string|null
     */
    public function getHeadDescription()
    {
        return $this->headDescription ? $this->headDescription->getContent() : null;
    }

    /**
     * @param string $description
     *
     * @return $this|self
     */
    public function setHeadDescription(string $description) : self
    {
        if (!$this->headDescription) {
            $this->headDescription = new HtmlElement('<meta>');
            $this->headDescription->addAttribute('name', 'description');
            $this->head->add($this->headDescription);
        }
        $this->headDescription->addAttribute('content', $description);

        return $this;
    }

    /**
     * @var HtmlElement
     */
    protected $headImage;

    /**
     * @return string|null
     */
    public function getHeadImage()
    {
        return $this->headImage ? $this->headImage->getContent() : null;
    }

    /**
     * @param string $image
     *
     * @return $this|self
     */
    public function setHeadImage(string $image) : self
    {
        if (!$this->headImage) {
            $this->headImage = new HtmlElement('<link>');
            $this->headImage->addAttribute('rel', 'image_src');
            $this->head->add($this->headImage);
        }
        $this->headImage->addAttribute('href', $image);

        return $this;
    }

    /**
     * Add Css file inclusion.
     *
     * @param string $css
     * @param array $attributes
     *
     * @return $this|self
     */
    public function addCss(string $css, array $attributes = []) : self
    {
        if (substr($css, -4) == '.css' ||
            substr($css, 0, 2) == '//' ||
            substr($css, 0, 4) == 'http'
        ) {
            list($path, $hash) = $this->getAssetData($css);

            $meta = new HtmlElement('<link />');

            if ($hash) {
                $meta->addAttribute('name', str_replace(['.css', '.', '/', ':'], ['', '_', '_', '_'], $css));
            }

            $meta->addAttributes([
                'type' => 'text/css',
                'rel' => 'stylesheet',
                'href' => (string) $path,
            ]);
        } else {
            $meta = new HtmlElement('<style>');
            $meta->addAttributes($attributes);
            $meta->addAttribute('type', 'text/css')
                ->setContent($css);
        }

        $this->head->add($meta);

        return $this;
    }

    /**
     * Add Css file inclusion.
     *
     * @param string $javascript
     * @param array $attributes
     * @param bool $footer
     *
     * @return $this|self
     */
    public function addJs(string $javascript, array $attributes = [], bool $footer = true) : self
    {
        $meta = new HtmlElement('<script>');
        $meta->addAttribute('type', 'text/javascript');
        $meta->addAttributes($attributes);

        if (substr($javascript, -3) == '.js' ||
            substr($javascript, 0, 2) == '//' ||
            substr($javascript, 0, 4) == 'http'
        ) {
            list($path, $hash) = $this->getAssetData($javascript);
            if ($hash) {
                $meta->addAttribute('name', str_replace(['.js', '.', '/', ':'], ['', '_', '_', '_'], $javascript));
            }

            $meta->addAttribute('src', (string) $path);
        } else {
            $meta->setContent($javascript);
        }

        if ($footer) {
            $this->footer->add($meta);
        } else {
            $this->head->add($meta);
        }

        // add a preload header
        if ($meta->getAttribute('src') && $footer) {
            $preload = new HtmlElement('<link>');
            $preload->addAttributes([
                'as' => 'script',
                'href' => $meta->getAttribute('src'),
                'rel' => 'preload',
            ]);
            $this->head->add($preload);
        }

        return $this;
    }

    /**
     * @return string
     */
    public function render()
    {
        $timerEvent = new TimerEvent('router.htmlPage', [
            'elements' => sizeof($this->elements),
        ]);

        $out = '<!DOCTYPE html>' . "\n";

        // default seo
        if (!$this->headTitle && $title = self::trans('seo.default/title')) {
            $this->setHeadTitle($title);
        }

        if (!$this->headDescription && $description = self::trans('seo.default/description')) {
            $this->setHeadDescription($description);
        }

        // add mandatory headers
        $language = new HtmlElement('<meta />');
        $language->addAttributes([
            'http-equiv' => 'Content-Language',
            'content' => self::locale(),
        ]);
        $this->head->addFirst($language);

        $charset = new HtmlElement('<meta />');
        $charset->addAttribute('charset', 'utf-8');
        $this->head->addFirst($charset);

        $content = $this->body->getContent();
        if ($content) {
            $this->body->setContent($content . $this->footer->render());
        } elseif (sizeof($this->body->elements)) {
            $this->body->add($this->footer);
        } else {
            $this->body->setContent($this->footer->render());
        }

        $parent = parent::render();
        $out .= $parent;

        $timerEvent->addData(['size' => $this->getContent() ? strlen($this->getContent()) : strlen($parent)]);
        self::emit($timerEvent);

        return $out;
    }
}


<?php
/**
 * A class containing all generic pake tasks
 *
 * @author    G. Giunta
 * @copyright (C) G. Giunta 2013-2014
 * @license   code licensed under the GNU GPL 2.0: see README file
 */

namespace eZExtBuilder;

use pakeApp;

class GenericTasks extends Builder
{
    static function run_default( $task=null, $args=array(), $cliopts=array() )
    {
        pake_echo ( "eZ Extension Builder ver." . self::VERSION .
            "\n\nSyntax: ezextbuilder [--\$pake-options] \$task [\$extension] [\$version] [--\$general-options] [--\$task-options]\n" .
            "  If no extension name is provided, a default configuration file will be searched for.\n" .
            "  If no version number is provided, it will be searched for in the configuration file.\n" .
            "  General options:\n" .
            "    --config-dir=\$dir             to be used instead of ./pake\n" .
            "    --config-file=\$file           to be used instead of ./pake/options-\$ext.yaml\n" .
            "    --user-config-file=\$file      to be used instead of ./pake/options-user.yaml\n" .
            "    --option.\$option.\$name=\$value to override any configuration setting\n" .
            "\nRun: ezextbuilder help       to learn about the options for pake.\n" .
            "Run: ezextbuilder --tasks    to list available tasks.\n" .
            "Run: ezextbuilder -P         to display tasks dependencies.\n" .
            "Run: ezextbuilder help \$task to display description and options of a specific task\n"
        );
    }

    /**
     * Displays current-version number
     */
    static function run_tool_version( $task=null, $args=array(), $cliopts=array() )
    {
        pake_echo( "eZ Extension Builder ver." . self::VERSION . "\nRunning on pake " . pakeApp::VERSION );
    }

    /**
     * Shows the properties for the current build configuration files (and options given on command-line)
     */
    static function run_show_properties( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        pake_echo ( print_r( $opts, true ) );
    }

    /**
     * Displays the list of extensions which can be built (which have a config file available in the pake subdir)
     */
    static function run_list_extensions( $task=null, $args=array(), $cliopts=array() )
    {
        self::setConfigDir( $cliopts );
        $exts = self::getAvailableExtNames();
        switch( count( $exts ) )
        {
            case 0:
                pake_echo ( 'Available extensions: -' );
                break;
            case 1:
                pake_echo ( 'Available extensions: ' . $exts[0] . ' (default)' );
                break;
            default:
                pake_echo ( 'Available extensions: ' . implode( ', ', $exts ) );
        }
    }

    /**
     * Creates a sample yaml configuration file used to drive the build for a given extension.
     * Will ask to overwrite an existing config file if found, unless option overwrite-existing is given
     */
    static function run_generate_extension_config( $task=null, $args=array(), $cliopts=array() )
    {
        self::setConfigDir( $cliopts );
        $overwrite = @$cliopts['overwrite-existing'];
        if ( count( $args ) == 0 )
        {
            throw new pakeException( "Missing extension name" );
        }
        $extname = $args[0];
        $configfile = self::getOptionsDir() . "/options-$extname.yaml";
        if ( file_exists( $configfile ) && ! $overwrite )
        {
            pake_echo( "File $configfile already exists. Must overwrite it to continue" );
            $ok = pake_input( "Do you want to overwrite it? [y/n]", 'n' );
            if ( $ok != 'y' )
            {
                return;
            }
        }
        pake_mkdirs( self::getOptionsDir() );
        pake_copy( self::getResourceDir() . '/options-sample.yaml', $configfile, array( 'override' => true ) );
        pake_echo( "Created file $configfile, now go and edit it" );
    }

    /**
     * Downloads the yaml file used to drive the build for a given extension, from projects.ez.no/github/some random url.
     * You have to provide the url to the config file as 2nd parameter, unless your extension is set up on projects.ez.no,
     * in which case we try to figure it out automatically.
     * Will ask to overwrite an existing config file if found, unless option overwrite-existing is given
     */
    static function run_download_extension_config( $task=null, $args=array(), $cliopts=array() )
    {
        self::setConfigDir( $cliopts );
        $overwrite = @$cliopts['overwrite-existing'];
        if ( count( $args ) == 0 )
        {
            throw new pakeException( "Missing extension name" );
        }
        $extname = $args[0];
        if ( count( $args ) > 1 )
        {
            $exturl = $args[1];
        }
        else
        {
            /// @todo add support for custom branches

            $page = pake_read_file( 'http://projects.ez.no/' . $extname );
            if ( !preg_match( '#]+>Source#', $page, $matches ) )
            {
                throw new pakeException( "Can not download or parse http://projects.ez.no/$extname" );
            }
            /// @todo we should test that $matches[1] is not an absolute url
            $exturl = 'http://projects.ez.no' . $matches[1];
            $extpage = pake_read_file( $exturl );
            if ( preg_match( '#svn checkout #', $extpage, $matches ) )
            {
                $source = 'svn';
                //$exturl = $matches[1];
            }
            else if ( preg_match( '#<a +href *= *"https://github.com/([^/]+)/([^"]+)"#', $extpage, $matches ) )
            {
                $source = 'github';
                $username = $matches[1];
                $gitext = rtrim( $matches[2], '/' );
            }
            else
            {
                throw new pakeException( "Can not download or parse $exturl" );
            }

            pake_echo ( "Scm system found: $source" );

            $targetfile = self::getOptionsDir() . "/options-$extname.yaml";
            if ( $source == 'github' )
            {
                $branch = 'master';

                $exturl = "https://github.com/$username/$gitext/raw/$branch/$targetfile";
            }
            elseif ( $source == 'svn' )
            {
                $extpage = pake_read_file( "http://svn.projects.ez.no/$extname" );
                if ( preg_match( '#
[tT]runk
>#', $extpage, $matches ) )
                {
                    $branch = $matches[1];
                }
                else
                {
                    /// @todo what if there is no 'trunk' but there are branches?
                    $branch = '';
                }

                pake_echo ( "Branch found: $branch" );

                // for extensions still on projects.ez.no svn, try different possibilities
                $exturl = "http://svn.projects.ez.no/$extname/$branch/extension/$extname/$targetfile";
                if ( !file_exists( $exturl ) )
                {
                    $exturl = "http://svn.projects.ez.no/$extname/$branch/$targetfile";
                }
                if ( !file_exists( $exturl ) )
                {
                    $exturl = "http://svn.projects.ez.no/$extname/$branch/packages/{$extname}_extension/ezextension/$extname/$targetfile";
                }
                if ( !file_exists( $exturl ) )
                {
                    throw new pakeException( "Can not download from $source build config file $targetfile" );
                }
            }
            else
            {
                throw new pakeException( "Can not download from scm build config file for $extname" );
            }
        }

        /// @todo check that $extconf is a valid yaml file with minimal params
        $extconf = pake_read_file( $exturl );

        $configfile = self::getOptionsDir() . "/options-$extname.yaml";
        if ( file_exists( $configfile ) && ! $overwrite )
        {
            pake_echo( "File $configfile already exists. Must overwrite it to continue" );
            $ok = pake_input( "Do you want to overwrite it them? [y/n]", 'n' );
            if ( $ok != 'y' )
            {
                return;
            }
        }
        pake_mkdirs( self::getOptionsDir() );
        pake_write_file( $configfile, $extconf, true );
    }

    /**
     * Updates the yaml config file for an extension from its own scm url
     * This is mostly useful for the case of generic build servers.
     */
    /*
    static function run_update_extension_config( $task=null, $args=array(), $cliopts=array() )
    {
        $opts = self::getOpts( @$args[0], @$args[1], $cliopts );
        $destfile = self::getOptionsDir() . "/options-.yaml";
        if ( @$opts['svn']['url'] != '' )
        {
            pake_echo( 'Updating yaml config from SVN repository' );
            pakeSubversion::checkout( $opts['svn']['url'], $destfile );
            /// @todo test that we got at least one file
        }
        else if ( @$opts['git']['url'] != '' )
        {
            pake_echo( 'Updating yaml config from GIT repository' );
            pakeGit::clone_repository( $opts['git']['url'], $destfile );
            if ( @$opts['git']['branch'] != '' )
            {
                /// @todo test checking out a specific branch
                pakeGit::checkout_repo( $destdir, $opts['git']['branch'] );
                /// @todo test that we got at least one file
            }
        }
        else if ( @$opts['file']['url'] != '' )
        {
            pake_echo( 'Updating yaml config from local repository' );
            /// @todo (!important) exclude stuff we know we're going to delete immediately afterwards
            $files = pakeFinder::type( 'any' )->in( $opts['file']['url'] );
            if ( count( $files ) == 0 )
            {
                throw new pakeException( "Empty source repo option: no files found in {$opts['file']['url']}" );
            }

            pake_mirror( $files, $opts['file']['url'], $destdir );
        }
        else
        {
            throw new pakeException( "Missing source repo option: either svn:url, git:url or file:url" );
        }
    }*/

    /**
     * Converts an existing ant properties file in its corresponding yaml version
     *
     * Converts the .properties files used to hold configuration settings for old
     * versions of ezextensionbuilder (the ones based on ant) to a .yaml configuration
     * file that is suitable for this version of the script.
     * It is recommended to inspect by hand the generated .yaml file after executing
     * the conversion.
     */
    static function run_convert_configuration( $task=null, $args=array(), $cliopts=array() )
    {
        self::setConfigDir( $cliopts );
        $extname = @$args[0];
        if ( $extname == '' )
        {
            $extname = dirname( __FILE__ );
        }
        while ( !is_file( "ant/$extname.properties" ) )
        {
            $extname = pake_input( 'What is the name of the current extension?' );
            if ( !is_file( "ant/$extname.properties" ) )
            {
                pake_echo( "File ant/$extname.properties not found" );
            }
        }

        self::convertPropertyFileToYamlFile(
            "ant/$extname.properties",
            self::getConfigDir() . "/options-$extname.yaml",
            array( $extname => '', 'external' => 'dependencies', 'dependency' => 'extensions', 'repository' => array( 'svn', 'url' ) ),
            "extension:\n    name: $extname\n\n" );

        foreach( array( 'files.to.parse.txt' => 'to_parse', 'files.to.exclude.txt' => 'to_exclude' ) as $file => $option )
        {
            $src = "ant/$file";
            if ( file_exists( $src ) )
            {
                //$ok = !file_exists( $dst ) || ( pake_input( "Destionation file $dst exists. Overwrite? [y/n]", 'n' ) == 'y' );
                //$ok && pake_copy( $src, $dst, array( 'override' => true ) );
                if ( count( $in = file( $src, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES ) ) )
                {
                    $in = "\n\nfiles:\n    $option: [" . implode( ', ', $in ) . "]\n";
                    file_put_contents( self::getConfigDir() . "options-$extname.yaml", $in, FILE_APPEND );
                }
            }
        }
    }

}


<?php

namespace nadir2\core;

/**
 * This class provides the choosing of controller, passing the request parameters
 * in it and binding with corresponding layout and view.
 * @author Leonid Selikhov
 */
class WebCtrlResolver extends AbstractCtrlResolver
{
    /** @var \nadir2\core\Request Объект запроса. */
    protected $request = null;

    /**
     * It inits the request property.
     * @param \nadir2\core\Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    /**
     * It creates the controller object, assignes it with default view and layout
     * objects.
     * @return \nadir2\core\AWebController
     * @throws \nadir2\core\Exception It's thrown if the 'componentsRootMap.controllers'
     * field not presented in the main config.
     */
    protected function createCtrl(): AbstractCtrl
    {
        $view              = ViewFactory::createView(
            str_replace('action', '', $this->actionName),
            $this->ctrlName
        );
        $componentsRootMap = AppHelper::getInstance()->getConfig('componentsRootMap');
        if (!isset($componentsRootMap['controllers'])) {
            throw new Exception("The field 'componentsRootMap.controllers' must be "
                .'presented in the main configuration file.');
        }
        $ctrlNamespace = str_replace(
            \DIRECTORY_SEPARATOR,
            '\\',
            $componentsRootMap['controllers']
        );
        $ctrlFullName  = $ctrlNamespace.'\\'.$this->ctrlName;
        if (!is_null($view)) {
            $layoutName = AppHelper::getInstance()->getConfig('defaultLayout');
            if (!is_null($layoutName)) {
                $layout = ViewFactory::createLayout($layoutName, $view);
                $ctrl   = new $ctrlFullName($this->request, $layout);
            } else {
                $ctrl = new $ctrlFullName($this->request, $view);
            }
        } else {
            $ctrl = new $ctrlFullName($this->request);
        }
        return $ctrl;
    }

    /**
     *  {@inheritdoc}
     */
    protected function tryAssignController(): void
    {
        $method = strtolower($this->request->getMethod());
        if (isset($this->routeMap[$method])) {
            foreach ($this->routeMap[$method] as $route => $config) {
                $actionArgs = [];
                if (preg_match(
                    '#^'.$route.'/?$#u',
                    urldecode($this->request->getUrlPath()),
                    $actionArgs
                )) {
                    AppHelper::getInstance()->setRouteConfig($config);
                    $this->ctrlName   = $config['ctrl'][0];
                    $this->actionName = $config['ctrl'][1];
                    unset($actionArgs[0]);
                    $this->actionArgs = array_values($actionArgs);
                    break;
                }
            }
        }
    }

    /**
     * It runs the controller action on execution.
     * @throws \nadir2\core\Exception It's thrown if the attempt to assign controller
     * with current route path was failed.
     */
    public function run(): void
    {
        $this->tryAssignController();
        if (!$this->isControllerAssigned()) {
            throw new Exception("It's unable to assign controller to this route path.");
        }
        (new CtrlWrapper($this->createCtrl()))
            ->{$this->actionName}($this->actionArgs);
    }
}


<?php

/**
 * @author Brett O'Donnell <cornernote@gmail.com>
 * @copyright 2013 Mr PHP
 * @link https://github.com/cornernote/yii-token-manager
 * @license BSD-3-Clause https://raw.github.com/cornernote/yii-token-manager/master/license.txt
 *
 * @package yii-token-manager
 */
class ETokenManager extends CApplicationComponent
{

    /**
     * @var string the ID of the {@link CDbConnection} application component. If not set,
     * a SQLite3 database will be automatically created and used. The SQLite database file
     * is protected/runtime/token-TokenVersion.db.
     */
    public $connectionID;

    /**
     * @var string name of the DB table to store token content. Defaults to 'Token'.
     * @see autoCreateTokenTable
     */
    public $tokenTableName = 'token';

    /**
     * @var boolean whether the token DB table should be created automatically if it does not exist. Defaults to true.
     * If you already have the table created, it is recommended you set this property to be false to improve performance.
     * @see tokenTableName
     */
    public $autoCreateTokenTable = true;

    /**
     * @var CDbConnection the DB connection instance
     */
    private $_db;

    /**
     * @return string the version of Yii Token Manager
     */
    public static function getVersion()
    {
        return '1.0.0';
    }

    /**
     * Initializes this application component.
     *
     * This method is required by the {@link IApplicationComponent} interface.
     * It ensures the existence of the token DB table.
     * It also removes expired data items from the table.
     */
    public function init()
    {
        parent::init();
        $db = $this->getDbConnection();
        $db->setActive(true);
        if ($this->autoCreateTokenTable) {
            $sql = "DELETE FROM {$this->tokenTableName} WHERE (expires>0 AND expires<" . time() . ") OR (uses_allowed>0 AND uses_remaining<1)";
            try {
                $db->createCommand($sql)->execute();
            } catch (Exception $e) {
                $this->createTokenTable($db, $this->tokenTableName);
            }
        }
    }

    /**
     * Creates the token DB table.
     * @param CDbConnection $db the database connection
     * @param string $tableName the name of the table to be created
     */
    protected function createTokenTable($db, $tableName)
    {
        $driver = $db->getDriverName();
        $file = dirname(__DIR__) . '/migrations/' . $this->tokenTableName . '.' . $db->getDriverName();
        $pdo = $this->getDbConnection()->pdoInstance;
        $sql = file_get_contents($file);
        $sql = rtrim($sql);
        $sqls = preg_replace_callback("/\((.*)\)/", create_function('$matches', 'return str_replace(";"," $$$ ",$matches[0]);'), $sql);
        $sqls = explode(";", $sqls);
        foreach ($sqls as $sql) {
            if (!empty($sql)) {
                $sql = str_replace(" $$$ ", ";", $sql) . ";";
                $pdo->exec($sql);
            }
        }
    }

    /**
     * @return CDbConnection the DB connection instance
     * @throws CException if {@link connectionID} does not point to a valid application component.
     */
    public function getDbConnection()
    {
        if ($this->_db !== null)
            return $this->_db;
        elseif (($id = $this->connectionID) !== null) {
            if (($this->_db = Yii::app()->getComponent($id)) instanceof CDbConnection)
                return $this->_db;
            else
                throw new CException(Yii::t('yii', 'ETokenManager.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
                    array('{id}' => $id)));
        }
        else {
            $dbFile = Yii::app()->getRuntimePath() . DIRECTORY_SEPARATOR . 'token-' . ETokenManager::getVersion() . '.db';
            return $this->_db = new CDbConnection('sqlite:' . $dbFile);
        }
    }

    /**
     * Sets the DB connection used by the token component.
     * @param CDbConnection $value the DB connection instance
     * @since 1.1.5
     */
    public function setDbConnection($value)
    {
        $this->_db = $value;
    }

    /**
     * @param $expires
     * @param $model_name
     * @param $model_id
     * @param $uses_allowed
     * @return string
     */
    public function createToken($expires, $model_name, $model_id, $uses_allowed = 0)
    {
        $plain = md5($this->hashToken(uniqid(true)));
        $token = $this->hashToken($plain);
        $this->getDbConnection()->getCommandBuilder()->createInsertCommand($this->tokenTableName, array(
            'uses_allowed' => $uses_allowed,
            'uses_remaining' => $uses_allowed,
            'expires' => $expires,
            'model_name' => $model_name,
            'model_id' => $model_id,
            'token' => $token,
            'created' => time(),
        ))->execute();
        return $plain;
    }

    /**
     * @param $model_name
     * @param $model_id
     * @param $plain
     * @return bool|array
     */
    public function checkToken($model_name, $model_id, $plain)
    {
        // get the token
        $sql = "SELECT id, token, uses_allowed, uses_remaining, expires FROM {$this->tokenTableName} WHERE model_name=:model_name AND model_id=:model_id ORDER BY created DESC, id DESC LIMIT 1";
        $token = $this->getDbConnection()->createCommand($sql)->queryRow(true, array(
            ':model_name' => $model_name,
            ':model_id' => $model_id,
        ));
        $log = 'checkToken failed [' . $model_name . '|' . $model_id . '|' . $plain . '] - ';
        // check for valid token
        if (!$token) {
            Yii::log($log . 'no token found');
            return false;
        }
        // check uses remaining
        if ($token['uses_allowed'] > 0 && $token['uses_remaining'] < 1) {
            Yii::log($log . 'no uses remaining');
            return false;
        }
        // check expires
        if ($token['expires'] > 0 && $token['expires'] <= time()) {
            Yii::log($log . 'token is expired');
            return false;
        }
        // check token plain
        if (!$this->verifyToken($plain, $token['token'])) {
            Yii::log($log . 'token is invalid');
            return false;
        }
        return $token;
    }

    /**
     * @param $model
     * @param $model_id
     * @param $plain
     * @return bool
     */
    public function useToken($model, $model_id, $plain)
    {
        $token = $this->checkToken($model, $model_id, $plain);
        if (!$token)
            return false;
        // deduct from uses remaining
        if ($token['uses_allowed'] > 0) {
            $sql = "UPDATE {$this->tokenTableName} SET uses_remaining = :uses_remaining WHERE id = :id";
            $this->getDbConnection()->createCommand($sql)->execute(array(
                ':id' => $token['id'],
                ':uses_remaining' => $token['uses_remaining'] - 1,
            ));
        }
        return true;
    }

    /**
     * @param $plain
     * @param null $encrypted
     * @return boolean validates a token
     */
    public function verifyToken($plain, $encrypted = null)
    {
        if (!$plain || !$encrypted)
            return false;
        return CPasswordHelper::verifyPassword($plain, $encrypted);
    }

    /**
     * @param $plain
     * @return string creates a token hash
     */
    public function hashToken($plain)
    {
        return CPasswordHelper::hashPassword($plain);
    }

}


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

namespace cascade\models;

use canis\db\ActiveQuery;
use canis\db\Query;

/**
 * AclRoleQuery [[@doctodo class_description:cascade\models\AclRoleQuery]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class AclRoleQuery extends ActiveQuery
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->on(Query::EVENT_BEFORE_QUERY, [$this, 'prioritizeNonType']);
    }

    /**
     * [[@doctodo method_description:prioritizeNonType]].
     *
     * @param [[@doctodo param_type:event]] $event [[@doctodo param_description:event]] [optional]
     */
    public function prioritizeNonType($event = null)
    {
        $objectTypePrefix = ObjectType::modelPrefix() . '-';
        if (!isset($this->orderBy)) {
            $this->orderBy = [];
        }
        $prioritize = [
            'IF([[controlled_object_id]] LIKE "' . addslashes($objectTypePrefix) . '%", 0, 1)' => SORT_DESC,
        ];
        $this->orderBy = array_merge($prioritize, $this->orderBy);
    }
}


<?php
namespace HtSettingsModule\Mapper\FileSystem\Adapter;

class Json implements AdapterInterface
{
    /**
     * {@inheritDoc}
     */
    public function prepareForWriting(array $data)
    {
        return \Zend\Json\Json::encode($data);
    }

    /**
     * {@inheritDoc}
     */
    public function onRead($contents)
    {
        return \Zend\Json\Json::decode($contents, \Zend\Json\Json::TYPE_ARRAY);
    }

    /**
     * {@inheritDoc}
     */
    public function getFileName($namespace)
    {
        return 'ht-settings-' . $namespace . '.json';
    }
}


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

use RedKiteCms\Rendering\Controller\BaseController;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\OptionsResolver\OptionsResolver;

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

        $request = $this->options["request"];
        $password = $request->get('password');
        $user = $this->fetchUser($this->options['security'], $this->options['configuration_handler']);

        $factory = $this->options['encoder_factory'];
        $encoder = $factory->getEncoder($user);
        $salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
        $password = $encoder->encodePassword($password, $salt);

        $userName = "admin";
        $usersFile = $this->options['configuration_handler']->usersDir() . '/users.json';
        $users = json_decode(FilesystemTools::readFile($usersFile), true);
        $user = $users[$userName];
        $user["password"] = $password;
        $user["salt"] = $salt;
        $users[$userName] = $user;
        FilesystemTools::writeFile($usersFile, json_encode($users));
    }

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

        $resolver->setAllowedTypes(
            array(
                'template_assets' => '\RedKiteCms\Rendering\TemplateAssetsManager\TemplateAssetsManager',
                'configuration_handler' => '\RedKiteCms\Configuration\ConfigurationHandler',
                'twig' => '\Twig_Environment',
                'request' => '\Symfony\Component\HttpFoundation\Request',
                'encoder_factory' => 'Symfony\Component\Security\Core\Encoder\EncoderFactory',
                'security' => 'Symfony\Component\Security\Core\SecurityContext',
            )
        );
    }
}


<?php

namespace C33s\ContactFormBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use C33s\ContactFormBundle\Model\ContactInquiry;
use C33s\ContactFormBundle\Form\Type\ContactFormType;
use Symfony\Component\HttpFoundation\Request;

class ContactFormController extends Controller
{
    /**
     * @Route("/contact_form/show", name="C33s_ContactFormBundle_form")
     * @Template()
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function formAction(Request $request)
    {
        $useAjax = $request->get('use_ajax', true);

        $inquiry = new ContactInquiry();

        $form = $this->createForm(ContactFormType::class, $inquiry, array(
            'action' => $this->generateUrl('C33s_ContactFormBundle_form'),
            'method' => 'POST',
            'attr' => array(
                'id' => 'c33s_contact_form',
            ),
        ));

        $message = $request->get('success_message', false);
        $form->handleRequest($request);

        if ($form->isValid()) {
            if ($this->container->getParameter('c33s_contact_form.database.enabled') === true) {
                $inquiry->save();
            }
            if ($this->container->getParameter('c33s_contact_form.email.enabled') === true) {
                $this->sendEmails($inquiry);
            }

            return array('form' => null, 'use_ajax' => $useAjax, 'success_message' => null, 'success' => true);
        }

        return array('form' => $form->createView(), 'use_ajax' => $useAjax, 'success_message' => $message, 'success' => false);
    }

    /**
     * Send all notification emails for the given inquiry object.
     *
     * @param ContactInquiry $inquiry
     */
    protected function sendEmails(ContactInquiry $inquiry)
    {
        $recipients = $this->container->getParameter('c33s_contact_form.email.recipients');
        if ($this->container->getParameter('c33s_contact_form.email.send_copy_to_user') && $inquiry->hasSenderEmail()) {
            $recipients[] = $inquiry->getSenderEmail();
        }

        if (empty($recipients)) {
            return;
        }

        $translator = $this->get('translator');

        $subject = $this->container->getParameter('c33s_contact_form.email.subject');

        $message = \Swift_Message::newInstance()
            ->setSubject($translator->trans($subject, array(), 'C33sContactForm'))
            ->setFrom($this->container->getParameter('c33s_contact_form.email.sender_email'))
            ->setTo($recipients)
            ->setBody(
                $this->renderView(
                    'C33sContactFormBundle:ContactForm:email.txt.twig',
                    array('inquiry' => $inquiry)
                )
            )
        ;

        $this->get('mailer')->send($message);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Inflector\Inflector;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use OpenOrchestra\ModelInterface\Model\FieldOptionInterface;
use OpenOrchestra\ModelInterface\Model\FieldTypeInterface;

/**
 * Description of Base FieldType
 *
 * @ODM\EmbeddedDocument
 */
class FieldType implements FieldTypeInterface
{
    /**
     * @var string $fieldId
     *
     * @ODM\Field(type="string")
     */
    protected $fieldId;

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

    /**
     * @var string $defaultValue
     *
     * @ODM\Field(type="raw")
     */
    protected $defaultValue;

    /**
     * @var boolean $searchable
     *
     * @ODM\Field(type="boolean")
     */
    protected $searchable;

    /**
     * @var boolean $orderable
     *
     * @ODM\Field(type="boolean")
     */
    protected $orderable;

    /**
     * @var string $fieldTypeSearchable
     *
     * @ODM\Field(type="string")
     */
    protected $fieldTypeSearchable;

    /**
     * @var boolean $translatable
     *
     * @ODM\Field(type="boolean")
     */
    protected $translatable = true;

    /**
     * @var boolean $listable
     *
     * @ODM\Field(type="boolean")
     */
    protected $listable;

    /**
     * @var string $type
     *
     * @ODM\Field(type="string")
     */
    protected $type;

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

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

    /**
     * Set FieldId
     *
     * @param string $fieldId
     */
    public function setFieldId($fieldId)
    {
        $this->fieldId = $fieldId;
    }

    /**
     * Get FieldId
     *
     * @return string
     */
    public function getFieldId()
    {
        return $this->fieldId;
    }

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

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

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

        return '';
    }

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

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

    /**
     * Set Default Value
     *
     * @param string $value
     */
    public function setDefaultValue($value)
    {
        $this->defaultValue = $value;
    }

    /**
     * Get Default Value
     *
     * @return string
     */
    public function getDefaultValue()
    {
        return $this->defaultValue;
    }

    /**
     * @return boolean
     */
    public function getListable()
    {
        return $this->listable;
    }

    /**
     * Set Searchable
     *
     * @param boolean $listable
     */
    public function setListable($listable)
    {
        $this->listable = $listable;
    }

    /**
     * Set Searchable
     *
     * @param boolean $searchable
     */
    public function setSearchable($searchable)
    {
        $this->searchable = $searchable;
    }

    /**
     * @return boolean
     */
    public function isSearchable()
    {
        return $this->searchable;
    }

    /**
     * Set Orderable
     *
     * @param boolean $orderable
     */
    public function setOrderable($orderable)
    {
        $this->orderable = $orderable;
    }

    /**
     * @return boolean
     */
    public function isOrderable()
    {
        return $this->orderable;
    }

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

    /**
     * Set field searchable
     *
     * @param string $fieldTypeSearchable
     */
    public function setFieldTypeSearchable($fieldTypeSearchable)
    {
        $this->fieldTypeSearchable = $fieldTypeSearchable;
    }

    /**
     * Set Type
     *
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Get Type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param FieldOptionInterface $option
     */
    public function addOption(FieldOptionInterface $option)
    {
        $this->options->add($option);
    }

    /**
     * @param FieldOptionInterface $option
     */
    public function removeOption(FieldOptionInterface $option)
    {
        $this->options->removeElement($option);
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function hasOption($key)
    {
        return $this->options->filter(function(FieldOptionInterface $option) use ($key) {
            return $option->getKey() == $key;
        })->count() != 0;
    }

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

    /**
     * Set Options
     */
    public function clearOptions()
    {
        $this->options = new ArrayCollection();
    }

    /**
     * @return array
     */
    public function getFormOptions()
    {
        $formOptions = array();

        foreach ($this->getOptions() as $option) {
            $formOptions[Inflector::tableize($option->getKey())] = $option->getValue();
        }

        return $formOptions;
    }

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

    /**
     * Initialize collection
     */
    protected function initializeCollection()
    {
        $this->options = new ArrayCollection();
    }

    /**
     * @return boolean
     */
    public function isTranslatable()
    {
        return $this->translatable;
    }

    /**
     * @param boolean $translatable
     */
    public function setTranslatable($translatable)
    {
        $this->translatable = $translatable;
    }
}


<?php

namespace Brash\TypeCollection;

use Illuminate\Support\Collection;
use UnexpectedValueException;

/**
 * Class AbstractTypeCollection
 * @package Brash\TypeCollection
 */
abstract class AbstractTypeCollection extends Collection
{
    /**
     * AbstractTypeCollection constructor.
     *
     * @param array $items
     */
    public function __construct($items = [])
    {
        $items = $this->getArrayableItems($items);

        $this->validateValues($items);

        parent::__construct($items);
    }

    /**
     * @param array $items
     */
    private function validateValues(array $items)
    {
        foreach ($items as $item) {
            $this->validateValue($item);
        }
    }

    /**
     * @param $value
     */
    private function validateValue($value)
    {
        if (!$this->willAcceptType($value)) {
            throw new UnexpectedValueException(sprintf(
                "Invalid value passed to %s",
                get_class($this)
            ));
        }
    }

    /**
     * @param mixed $value
     *
     * @return $this
     */
    final public function push($value)
    {
        $this->validateValue($value);

        return parent::push($value);
    }

    /**
     * @param mixed $key
     * @param mixed $value
     *
     * @return $this
     */
    final public function put($key, $value)
    {
        $this->validateValue($value);

        return parent::put($key, $value);
    }

    /**
     * @param $value
     *
     * @return bool
     */
    abstract protected function willAcceptType($value): bool;
}


<?php
/*///////////////////////////////////////////////////////////////
 /** ID: | /-- ID: Indonesia
 /** EN: | /-- EN: English
 ///////////////////////////////////////////////////////////////*/

/**
 * Session - Library untuk framework kecik, library ini khusus untuk membantu masalah session
 *
 * @author 		Dony Wahyu Isp
 * @copyright 	2015 Dony Wahyu Isp
 * @link 		http://github.com/kecik-framework/session
 * @license		MIT
 * @version 	1.0.1-alpha
 * @package		Kecik\Session
 **/
namespace Kecik;

/**
 * Session
 * @package 	Kecik\Session
 * @author 		Dony Wahyu Isp
 * @since 		1.0.0-alpha
 **/
class Session {
	/**
	 * @var bool $status
	 **/
	private $status = FALSE;

	/**
	 * @var string $key
	 **/

	private $key;
	/**
	 * @var string $iv
	 **/
	private $iv;

	/**
	 * @var Konstata untuk Limiter Session
	 **/
	const LIMITER_PUBLIC	= 'public';
	const LIMITER_PRIVATE 	= 'private';
	const LIMITER_PRIVATE_NO= 'private_no_expire';
	const LIMITER_NO_CACHE	= 'nocache';

	/**
	 * @var Konstanta untuk status session
	 **/
	const STATUS_DISABLED 	= PHP_SESSION_DISABLED;
	const STATUS_NONE		= PHP_SESSION_NONE;
	const STATUS_ACTIVE		= PHP_SESSION_ACTIVE;

	/**
 	 * __construct
 	 * @param Kecik $app
 	 **/
	public function __construct() {
		$app = Kecik::getInstance();
		session_start();
		$config = $app->config;
		$this->status = $config->get('session.encrypt');
		if ( empty( $this->status ) )
			$this->status = FALSE;
		else {
			$key = $config->get('session.encrypt.key');
			if ( empty( $key ) )
				$this->key = pack('H*', $key);
			else
				$this->key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

			if (empty($_SESSION['eivk'.md5($app->url->baseUrl())]) || !ctype_print($_SESSION['eivk'.md5($app->url->baseUrl())]))
				unset($_COOKIE['eivk'.md5($app->url->baseUrl())]);

            if (empty($_SESSION['eivk'.md5($app->url->baseUrl())]) && empty($_COOKIE['eivk'.md5($app->url->baseUrl())])) {
				$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
	            $this->iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	            $this->iv = base64_encode($this->iv);
	            $_SESSION['eivk'.md5($app->url->baseUrl())] = $this->iv;
	            setcookie('eivk'.md5($app->url->baseUrl()), $this->iv, 0, '/');
        	} else {
        		if (!empty($_SESSION['eivk'.md5($app->url->baseUrl())])) {
            		$this->iv = $_SESSION['eivk'.md5($app->url->baseUrl())];
            		setcookie('eivk'.md5($app->url->baseUrl()), $this->iv, 0, '/');
        		} elseif (!empty($_COOKIE['eivk'.md5($app->url->baseUrl())])) {
        			$this->iv = $_COOKIE['eivk'.md5($app->url->baseUrl())];
            		$_SESSION['eivk'.md5($app->url->baseUrl())] = $this->iv;
        		}
        	}
		}

	}

	/**
	 * newIV
	 **/
	public function newIV() {
		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $this->iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $this->iv = base64_encode($this->iv);
        $_SESSION['eivk'.md5($app->url->baseUrl())] = $this->iv;
        setcookie('eivk'.md5($app->url->baseUrl()), $this->iv, 0, '/');
	}

	/**
	 * id
	 * @return session_id()
	 **/
	public function id() {
		return session_id();
	}

	/**
	 * newId
	 * @return session_regenerate_id()
	 **/
	public function newId() {
		return session_regenerate_id();
	}

	/**
	 * set
	 * @param string $name
	 * @param mixed $value
	 **/
	public function set($name, $value) {
		$_SESSION[$name] = $this->encrypt( $value );
	}

	/**
	 * get
	 * @param string $name
	 * @return mixed
	 **/
	public function get($name) {
		if (isset($_SESSION[$name]))
			return $this->decrypt( $_SESSION[$name] );
		else
			return NULL;
	}

	/**
	 * delete
	 * @param string $name
	 **/
	public function delete($name) {
		if (isset($_SESSION[$name]))
			unset($_SESSION[$name]);
	}

	/**
	 * limiter
	 * @param string $limiter
	 **/
	public function limiter($limiter) {
		session_cache_limiter($limiter);
	}

	/**
	 * setExpire
	 * @param int $minute
	 **/
	public function setExpire($minute) {
		session_cache_expire($minute);
	}

	/**
	 * getExpire
	 * @return int minute
	 **/
	public function getExpire() {
		return session_cache_expire();
	}

	/**
	 * commit
	 * Simpan semua perubahan session
	 **/
	public function commit() {
		session_commit();
		session_write_close();
	}

	/**
	 * abort
	 * Batalkan semua perubahan session
	 **/
	public function abort() {
		session_abort();
		session_reset();
	}

	/**
	 * encode
	 * Encode session
	 * @return string
	 **/
	public function encode() {
		return session_encode();
	}

	/**
	 * decode
	 * @param string $data
	 * @return array
	 **/
	public function decode($data) {
		return session_decode($data);
	}

	/**
	 * getCookieParams
	 * @return array
	 */
	public function getCookieParams() {
		return session_get_cookie_params();
	}

	/**
	 * setCookieParams
	 * @param int $lifetime
	 * @param string $path
	 * @param string $domain
	 * @param bool $secure
	 * @param bool $httponly
	 */
	public function setCookieParams($lifetime, $path='/', $domain='', $secure=FALSE, $httponly=FALSE) {
		return session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
	}

	/**
	 * status
	 * @return bool
	 **/
	public function status() {
		return session_status();
	}

	/**
	 * clear
	 * ID: Hapus semua session | EN: Delete all session
	 **/
	public function clear() {
		session_destroy();
	}

	/**
	 * encrypt
	 * ID: Enkripsi Session | EN: Session Encryption
	 * @param string $plaintext
	 * @return string
	 **/
	private function encrypt($plaintext) {
		if (is_array($plaintext))
			$ciphertext = json_encode($plaintext);
		else
			$ciphertext = $plaintext;

		if ($this->status) {
			$ciphertext = @mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $ciphertext, MCRYPT_MODE_CBC, base64_decode($this->iv));
		}

		return base64_encode($ciphertext);
	}

	/**
	 * decrypt
	 * ID: Dekripsi session | EN: Session Decryption
	 * @param string $ciphertext
	 * @return mixed
	 **/
	private function decrypt($ciphertext) {
		$plaintext = base64_decode($ciphertext);
		if ($this->status) {
			$plaintext = trim( @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, base64_decode($ciphertext), MCRYPT_MODE_CBC, base64_decode($this->iv)) );
			$plaintext_array = json_decode($plaintext, TRUE);
			if ($plaintext_array)
				$plaintext = $plaintext_array;
		}

		return $plaintext;
	}
}


<?php

namespace AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * Returns the DataTables i18n file
     *
     * @return Response
     *
     * @Route("/dataTables.{_format}" , requirements={ "_format" = "json" }, defaults={ "_format" = "json" })
     * @Method("GET")
     */
    public function getDataTablesI18nAction()
    {
        $locale = $this->get('request_stack')->getCurrentRequest()->getLocale();
        $format = $this->get('request_stack')->getCurrentRequest()->getRequestFormat();

        return $this->render(
            'AdminBundle:Default/DataTables_i18n:'.$locale.'.txt.'.$format
        );
    }

    /**
     * @Route("/admin/")
     * @Template()
     */
    public function indexAction()
    {
        if ($this->get('security.authorization_checker')->isGranted('ROLE_USER') ) {
            return $this->redirect($this->generateUrl('index'));
        }else{
            return $this->redirect($this->generateUrl('admin_default_dashboard'));
        }
        return $this->redirect($this->generateUrl('admin_login'));
    }

    /**
     * @Route("/admin/dashboard")
     * @Template("AdminBundle:Default:index.html.twig")
     */
    public function dashboardAction(Request $request)
    {
        return array();
    }

    /**
     * @Route("/admin/fileupload")
     * @Template("AdminBundle:Default:fileupload.html.twig")
     */
    public function fileuploadAction(Request $request)
    {
        return array();
    }

    /**
     * @Route("/admin/analytics/{id}")
     * @Template()
     */
    public function analyticsAction(Request $request, $id=null)
    {

        $client = $this->get('google.api.client');

        if ($request->query->get('code') && is_null($this->get('session')->get('access_token'))) {
            $client->authenticate($request->query->get('code'));
            $this->get('session')->set('access_token', $client->getAccessToken());
            header('Location: ' . filter_var($this->generateUrl('admin_default_analytics'), FILTER_SANITIZE_URL));
        }

        /************************************************
         Google Analitycs
         If we have an access token, we can make
         requests, else we generate an authentication URL.
        ************************************************/
        $authUrl = null;
        $mainResult = null;
        $reportResult = null;
        $reportDay = null;
        $startDate = null;
        $endDate = null;

        if ($this->get('session')->get('access_token')) {
            $client->setAccessToken($this->get('session')->get('access_token'));
            $analytics = $this->get('google.api.analytics');
            if($request->query->get('start') !='' && $request->query->get('end') != ''){
                $startDate = $request->query->get('start');
                $endDate = $request->query->get('end');
            }else{
                $now = new \DateTime();
                $startDate = '2012-01-01';
                $endDate = $now->format('Y-m-d');
            }

            if($analytics->hasAccount()){
                list($mainResult, $reportResult, $reportDay) = $analytics->getGoogleAnalitycsData($startDate, $endDate);

                return $this->render("AdminBundle:Analytics:analytics.html.twig", array(
                        'authUrl' => $authUrl,
                        'mainResult' => $mainResult,
                        'reportResult'=> $reportResult,
                        'reportDay' => $reportDay,
                        'startDate' => $startDate,
                        'endDate' => $endDate
                    ));
            }

            return $this->render("AdminBundle:Analytics:no.analytics.html.twig", array());

        } else {
          $authUrl = $client->createAuthUrl();
          return $this->render("AdminBundle:Analytics:auth.analytics.html.twig", array('authUrl' => $authUrl));
        }

    }
}


<?php

Web2All_Manager_Main::loadClass('Web2All_Table_SQLOperation');

/**
 * Web2All Table MultiValueOperator class
 *
 * Can be used for the following operators: IN, BETWEEN
 *
 * *NOTE* This class CANNOT be used for save operations (comparison only)
 *
 * This class handles the special mysql IN and BETWEEN operator.
 *
 * The IN operator expects a list of params which will be used in the
 * following way:
 * $tableobject->fieldname=$web2all->Web2All_Table_MultiValueOperator(array('param1','param2','param<n>'),'IN');
 * WHERE fieldname IN ('param1','param2','param<n>')
 *
 * The BETWEEN operator expects two params which will be used in the
 * following way:
 * $tableobject->fieldname=$web2all->Web2All_Table_MultiValueOperator(array('param1','param2'),'BETWEEN');
 * WHERE fieldname BETWEEN 'param1' AND 'param2'
 *
 * At the moment only these two operators are supported.
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2008 Web2All BV
 * @since 2008-12-08
 */
class Web2All_Table_MultiValueOperator extends Web2All_Table_SQLOperation {

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param array $params  nested operations not yet supported
   * @param string $operator
   */
  public function __construct(Web2All_Manager_Main $web2all,$params,$operator='IN')
  {

    // validate operator params
    $this->checkParams($params,$operator);

    parent::__construct($web2all,$params,$operator);

  }

  /**
   * Checks if params are correct and throws exception if not
   *
   * @param array $params
   * @param string $operator
   */
  protected function checkParams($params,$operator)
  {
    if (!is_array($params)) {
    	throw new Exception('Web2All_Table_MultiValueOperator: first param must be an array');
    }
    if ($operator=='IN') {
    	if (count($params)<1) {
    		throw new Exception('Web2All_Table_MultiValueOperator: IN operator requires at least one param');
    	}
    } elseif ($operator=='BETWEEN') {
    	if (count($params)!=2) {
    		throw new Exception('Web2All_Table_MultiValueOperator: BETWEEN operator requires exactly two params');
    	}
    }else{
      throw new Exception('Web2All_Table_MultiValueOperator: unsupported operator "'.$operator.'"');
    }
  }

  /**
   * This method is called by Web2All_Table_SaveObject when
   * inserting or updating an object with a Web2All_Table_SQLOperation
   * as value.
   *
   * @return string
   */
  public function toSQLString() {
    if ($this->operator=='IN') {
    	$sql = '(';
	    $komma = '';
	    for ($i=0;$i<count($this->operation);$i++)
	    {
	      $sql.= $komma.'?';
	      $komma = ',';
	    }
	    $sql.= ')';
	    return $sql;
    } elseif ($this->operator=='BETWEEN') {
    	return '? AND ?';
    }
  }

  public function __toString() {
    // This object shouldn't be converted to string, its not a meaningull value
    trigger_error('Web2All_Table_MultiValueOperator: illegal conversion to string',E_USER_WARNING);
    return $this->getOperator().'('.implode(',',$this->operation).')';
  }

  /**
   * Get an array with all placeholder values
   *
   * Every questionmark in the toSQLString() result must have
   * a corresponding placeholder value returned by this method.
   *
   * @return array  array of strings
   */
  public function getPlaceholderValues()
  {
    return $this->operation;
  }

  /**
   * Set the operator that has to be used when this SQLOperation
   * is used in the WHERE part of a query.
   *
   * @param string $operator  sql comparison operator (IN,BETWEEN)
   */
  public function setOperator($operator)
  {
    $this->checkParams($this->operation,$operator);
    $this->operator=$operator;
  }

}

?>


<?php
/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Predef;

use Skyline\Compiler\AbstractCompiler;
use Skyline\Compiler\CompilerContext;
use Skyline\Compiler\Context\Logger\LoggerInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Creates defined directories. If a directory exists, it will be removed.
 *
 * @package Skyline\Compiler\Predef
 */
class CreateDirectoriesCompiler extends AbstractCompiler
{
    /** @var string[] */
    private $directoryNames;

    /** @var Filesystem */
    private $fileSystem;

    /**
     * CreateDirectoriesCompiler constructor.
     * @param string[] $directoryNames
     */
    public function __construct(string $compilerID, array $directoryNames)
    {
        parent::__construct($compilerID);
        $this->directoryNames = $directoryNames;
    }

    /**
     * @inheritDoc
     */
    public function compile(CompilerContext $context)
    {
        $skylineAppData = $context->getSkylineAppDataDirectory();

        if(!file_exists($skylineAppData))
            $this->makeDir($skylineAppData, $context->getLogger());

        foreach($this->getDirectoryNames() as $dirName) {
            $dirName = "$skylineAppData/$dirName";

            if(file_exists($dirName) && !$this->removeDir($dirName, $context->getLogger())) {
                continue;
            }

            if(!file_exists($dirName)) {
                $this->makeDir($dirName, $context->getLogger());
            }
        }
    }

    /**
     * Makes the required directory. It does NOT exist!
     *
     * @param $dirName
     * @param LoggerInterface $logger
     */
    protected function makeDir($dirName, LoggerInterface $logger) {
        $dn = explode(getcwd(), $dirName)[1] ?? $dirName;

        if(@mkdir($dirName)) {
            $logger->logText("Created directory <fg=green>%s</>", LoggerInterface::VERBOSITY_NORMAL, NULL, $dn);
        } else {
            $logger->logWarning("Creating directory $dn failed");
        }
    }

    /**
     * @param $dir
     * @param LoggerInterface $logger
     * @return bool
     */
    protected function removeDir($dir, LoggerInterface $logger): bool {
        $dn = explode(getcwd(), $dir)[1] ?? $dir;

        try {
            if(!$this->fileSystem)
                $this->fileSystem = new Filesystem();
            $this->fileSystem->remove($dir);
            $logger->logText("Directory <fg=red>$dn</> removed", LoggerInterface::VERBOSITY_VERY_VERBOSE);
            return true;
        } catch (IOException $exception) {
            $logger->logWarning("Removing directory $dn failed");
            return false;
        }
    }

    /**
     * The names of directories to create
     * NOTE: The directories are created inside the Skyline CMS Application data directory. Use ../ to create directories outside (not recommended)
     * @return string[]
     */
    public function getDirectoryNames(): array
    {
        return $this->directoryNames;
    }

    /**
     * @param string[] $directoryNames
     */
    public function setDirectoryNames(array $directoryNames): void
    {
        $this->directoryNames = $directoryNames;
    }
}


<?php

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

namespace Chill\CustomFieldsBundle\Entity;

/**
 * CustomField
 */
class CustomField
{
    /**
     * @var integer
     */
    private $id;

    private $slug;

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

    /**
     * @var boolean
     */
    private $active = true;

    /**
     *
     * @var array
     */
    private $options = array();

    /**
     * @var array
     */
    private $name;

    /**
     * @var float
     */
    private $ordering;

    /**
     *
     * @var bolean
     */
    private $required = FALSE;

    const ONE_TO_ONE = 1;
    const ONE_TO_MANY = 2;

    /**
     * @var CustomFieldsGroup
     */
    private $customFieldGroup;

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

    function getSlug()
    {
        return $this->slug;
    }

    function getOptions()
    {
        return $this->options;
    }

    /**
     * Set type
     *
     * @param string $type
     *
     * @return CustomField
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set active
     *
     * @param boolean $active
     *
     * @return CustomField
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Returns true if the custom field is active
     *
     * @return boolean
     */
    public function isActive()
    {
        return $this->active;
    }

    /**
     * Get customFieldGroup
     *
     * @return CustomFieldsGroup
     */
    public function getCustomFieldsGroup()
    {
        return $this->customFieldGroup;
    }

    /**
     * Set customFieldGroup
     *
     * @param \Chill\CustomFieldsBundle\Entity\CustomFieldsGroup $customFieldGroup
     *
     * @return CustomField
     */
    public function setCustomFieldsGroup(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup $customFieldGroup = null)
    {
        $this->customFieldGroup = $customFieldGroup;

        return $this;
    }

    /**
     * Set name
     *
     * @param array $name
     *
     * @return CustomField
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return array
     */
    public function getName($locale = null)
    {
        if ($locale) {
          if (isset($this->name[$locale])) {
             return $this->name[$locale];
          } else {
             foreach ($this->name as $name) {
                if (!empty($name)) {
                   return $name;
                }
             }
          }

          return '';

       } else {
          return $this->name;
       };
    }

    /**
     * Set order
     *
     * @param float $order
     *
     * @return CustomField
     */
    public function setOrdering($order)
    {
        $this->ordering = $order;

        return $this;
    }

    /**
     * Get order
     *
     * @return float
     */
    public function getOrdering()
    {
        return $this->ordering;
    }

    /**
     * Set options
     *
     * @param array $options
     *
     * @return CustomField
     */
    public function setOptions(array $options)
    {
        $this->options = $options;

        return $this;
    }

    public function setSlug($slug)
    {
        $this->slug = $slug;
        return $this;
    }

    /**
     * alias for isRequired
     *
     * @return boolean
     */
    public function getRequired()
    {
        return $this->isRequired();
    }

    /**
     * return true if the field required
     *
     * @return boolean
     */
    public function isRequired()
    {
        return $this->required;
    }

    public function setRequired($required)
    {
        $this->required = $required;
        return $this;
    }

}


<?php declare(strict_types=1);
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

namespace Gears\Asset\Compilers;

use SplFileInfo;
use RuntimeException;
use Gears\String\Str;
use Gears\Asset\Contracts\Compiler;
use Gears\Asset\Contracts\Minifier;

class Base implements Compiler
{
    /**
     * We represent the source file that needs to be compiled.
     *
     * @var SplFileInfo
     */
    protected $file;

    /**
     * We represent the final destination asset file that will be created.
     *
     * @var SplFileInfo
     */
    protected $destination;

    /**
     * If the $file is indeed a file we will read it's contents into this
     * property. Remember it's possible that we are given a folder...
     *
     * @var string
     */
    protected $source = '';

    /**
     * This basically tells us if we are allowed to minify the compiled source.
     *
     * @var bool
     */
    protected $debug;

    /**
     * Only applies when building css assets.
     * Used in conjuction with: ```vladkens/autoprefixer-php```.
     *
     * @var bool
     */
    protected $autoprefix;

    public function __construct(SplFileInfo $file, SplFileInfo $destination, bool $debug, bool $autoprefix)
    {
        $this->file = $file;

        if (!$this->file->isDir())
        {
            $this->source = file_get_contents($this->file->getPathname());
        }

        $this->destination = $destination;

        $this->debug = $debug;

        $this->autoprefix = $autoprefix;
    }

    /**
     * @inheritDoc
     *
     * This implementation caters for both standard native Css and Js files
     * that don't need any compiling as such. The less and sass compilers
     * extend the css compiler.
     */
    public function compile(): string
    {
        if ($this->doWeNeedToMinify($this->file))
        {
            $src = $this->getMinifier($this->file, $this->source)->minify();

            // Remove any source mappings, they cause 404 errors.
            // One of the benefits of using this Robo Task is that it is super
            // easy to switch between a minifed asset and a non minified asset.
            $src = preg_replace('/^\/\/# sourceMappingURL.*$/m', '', $src);

            // TODO: generate our own source maps... sounds like a challenge :)
        }
        else
        {
            $src = $this->source;
        }

        return $src."\n\n";
    }

    /**
     * Creates the minfier object.
     *
     * @param  SplFileInfo $file   The original source file.
     * @param  string      $source The source code to minify.
     * @return Minifier            A minifier for the given destination type.
     */
    protected function getMinifier(SplFileInfo $file, string $source): Minifier
    {
        $minifier = '\Gears\Asset\Minifiers\\';
        $minifier .= ucfirst($this->destination->getExtension());

        if (!class_exists($minifier))
        {
            throw new RuntimeException
            (
                'Minification is not supported for type: '.
                $this->destination->getExtension()
            );
        }

        return new $minifier($file, $source);
    }

    /**
     * Based on if we are in debug mode and if the file is already minfied or
     * not, this tells us if we actually need to perform any minification.
     *
     * @param  SplFileInfo $file The original source file.
     * @return bool              If true we will run the minifier.
     */
    protected function doWeNeedToMinify(SplFileInfo $file): bool
    {
        return
        (
            !$this->debug &&
            !Str::s($file->getFilename())->contains('.min.')
        );
    }
}


<?php
namespace HtSettingsModule\Service;

use HtSettingsModule\Options\CacheOptionsInterface;

class CacheManager implements CacheManagerInterface
{
    /**
     * @var CacheOptionsInterface
     */
    protected $cacheOptions;

    use \Zend\ServiceManager\ServiceLocatorAwareTrait;

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

    /**
     * Gets cache adapter of a settings namespace
     *
     * @param  string                                    $namespace
     * @return \Zend\Cache\Storage\StorageInterface|null
     */
    public function getCacheAdapter($namespace)
    {
        // caching is not enabled for a namespace
        if (!$this->isCacheable($namespace)) {
            return null;
        }

        // user wants to implements different adapter for different namespaces
        if (is_array($this->cacheOptions->getAdapter())) {
            // checks if adapter of a namespace exists
            if (!isset($this->cacheOptions->getAdapter()[$namespace])) {
                return null;
            }
            $adapter =  $this->cacheOptions->getAdapter()[$namespace];
        } else {
            // user want to implements one adapter for all namespaces
            $adapter = $this->cacheOptions->getAdapter();
        }

        if (is_object($adapter)) {
            return $adapter;
        }
        if ($this->getServiceLocator()->has($adapter)) {
            return $this->getServiceLocator()->get($adapter);
        }

        return new $adapter;
    }

    /**
     * {@inheritDoc}
     */
    public function settingsExists($namespace)
    {
        $cacheAdapter = $this->getCacheAdapter($namespace);
        if ($cacheAdapter === null) {
            return false;
        }

        return $cacheAdapter->hasItem($namespace);
    }

    /**
     * {@inheritDoc}
     */
    public function get($namespace)
    {
        if (!$this->settingsExists($namespace)) {
            return null;
        }
        $cacheAdapter = $this->getCacheAdapter($namespace);

        return $cacheAdapter->getItem($namespace);
    }

    /**
     * {@inheritDoc}
     */
    public function create($namespace, $settings)
    {
       if (!$this->isCacheable($namespace)) {
           return;
       }

       $cacheAdapter = $this->getCacheAdapter($namespace);
       $cacheAdapter->addItem($namespace, $settings);
    }

    /**
     * Checks if settings of a namespace can be cached
     *
     * @param  string $namespace
     * @return bool
     */
    public function isCacheable($namespace)
    {
        if (!$this->cacheOptions->isEnabled()) {
            return false;
        }

        $namespaces = $this->cacheOptions->getNamespaces();
        // user has enabled caching but has not specified namespaces to cache,
        // so we cache all the namespaces
        if (empty($namespaces)) {
            return true;
        }

        // user has enabled caching but has specified certain namespaces to cache,
        // so we cache only the specified namespaces
        return in_array($namespace, $namespaces);
    }

    /**
     * {@inheritDoc}
     */
    public function delete($namespace)
    {
        if ($this->settingsExists($namespace)) {
            $cacheAdapter = $this->getCacheAdapter($namespace);
            $cacheAdapter->removeItem($namespace);
        }
    }
}


<?php

namespace PeterColes\Cluster;

class Config
{
    /**
     * @var array
     */
    protected $configs = [];

    /**
     * Initialise configs.
     *
     * @param array $configs
     */
    public function __construct(array $configs = [])
    {
        $this->configs = $configs;
    }

    /**
     * Get a setting.
     *
     * @param string $key
     * @param mixed  $default
     *
     * @return mixed config setting or default when not found
     */
    public function get($key, $default = null)
    {
        return array_key_exists($key, $this->configs) ? $this->configs[$key] : $default;
    }

    /**
     * Check existence of an item by key.
     *
     * @param string $key
     * @return bool
     */
    public function has($key)
    {
        return array_key_exists($key, $this->configs);
    }

    /**
     * Set a setting.
     *
     * @param string $key
     * @param mixed  $value
     * @return $this
     */
    public function set($key, $value)
    {
        $this->configs[$key] = $value;

        return $this;
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (isset($arguments[0]) && is_array($arguments[0])) {
            $arguments = $arguments[0];
        }

        parent::setArguments($arguments);
    }
}


<?php
/**
 * (c) Joffrey Demetz <joffrey.demetz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JDZ\Filesystem;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Exception;

/**
 * File Helper
 *
 * @author Joffrey Demetz <joffrey.demetz@gmail.com>
 */
abstract class File
{
  /**
   * Copies a file
   *
   * If the target file is older than the origin file, it's always overwritten
   * If the target file is newer, it is overwritten only when the
   * $overwriteNewerFiles option is set to true.
   *
   * @param   string  $originFile   The original filename
   * @param   string  $targetFile   The target filename
   * @param   bool    $force        If true, target files newer than origin files are overwritten
   * @throws  Exception  When src doesn't exist or When copy fails
   */
  public static function copy($src, $dest, $force=true)
  {
    $src  = Path::clean($src);
    $dest = Path::clean($dest);

    if ( !Folder::exists(dirname($dest)) ){
      Folder::create(dirname($dest));
    }

    $fs = new Filesystem();

    try {
      $fs->copy($src, $dest, $force);
    } catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('CANNOT_FIND_SOURCE').' '.$e->getPath());
    }

    return true;
  }

  /**
   * Checks the existence of files or directories
   *
   * @param   string    $path     Folder name relative to installation dir
   * @return  bool      true if the file exists, false otherwise
   */
  public static function exists($path)
  {
    $path = Path::clean($path);

    $fs = new Filesystem();
    return $fs->exists($path);
  }

  /**
   * Write contents to a file
   *
   * @param   string    $filename    The full file path
   * @param   string    $buffer      The buffer to write
   * @return   boolean   True on success
   * @throws   Exception
   */
  public static function write($filename, $buffer)
  {
    $fs = new Filesystem();

    try {
      $fs->dumpFile($filename, $buffer);
    }
    catch(IOExceptionInterface $e){
      throw new Exception($e->getMessage());
    }

    return true;
  }

  /**
   * Delete a file or array of files
   *
   * @param   string    $path  The file name
   * @return   boolean   True on success
   */
  public static function delete($path)
  {
    $path = Path::clean($path);

    $fs = new Filesystem();

    try {
      $fs->remove($path);
    }
    catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('FAILED_DELETING').' - ('.$e->getMessage().')');
    }

    return true;
  }

  /**
   * Moves a file
   *
   * @param   string    $src          The path to the source file
   * @param   string    $dest         The path to the destination file
   * @param   bool      $overwrite    Overwrite destination file
   * @return   boolean   True on success
   * @throws   Exception
   */
  public static function move($src, $dest, $overwrite=false)
  {
    $src  = Path::clean($src);
    $dest = Path::clean($dest);

    if ( !File::exists($src) ){
      throw new Exception(Helper::getTranslation('CANNOT_FIND_SOURCE').' : '.$src);
    }

    if ( File::exists($dest) && !$overwrite ){
      throw new Exception(Helper::getTranslation('ALREADY_EXISTS').' : '.$src);
    }

    try {
      $fs = new Filesystem();
      $fs->rename($src, $dest, $overwrite);
    }
    catch(IOExceptionInterface $e){
      throw new Exception(Helper::getTranslation('FAILED_RENAMING').' - ('.$e->getMessage().')');
    }

    return true;
  }

  /**
   * Read the contents of a file
   *
   * @param   string    $path       The full file path
   * @return   string    File contents
   * @throws   Exception
   */
  public static function read($path)
  {
    $path = Path::clean($path);
    if ( !File::exists($path) ){
      return '';
    }
    return file_get_contents($path);
  }

  public static function same(string $path1, string $path2){
    if ( false === ($fp1=fopen($path1, 'rb')) ){
      return false;
    }

    if ( false === ($fp2=fopen($path2, 'rb')) ){
        fclose($fp1);
        return false;
    }

    if ( mime_content_type($path1) !== mime_content_type($path2)
      || filetype($path1) !== filetype($path2)
      || filesize($path1) <> filesize($path2)
    ){
      fclose($fp1);
      fclose($fp2);
      return false;
    }

    if ( fread($fp1, filesize($path1)) !== fread($fp2, filesize($path2)) ){
      fclose($fp1);
      fclose($fp2);
      return false;
    }

    fclose($fp1);
    fclose($fp2);

    return true;
  }

  /**
   * Moves an uploaded file to a destination folder
   *
   * @param   string    $src          The name of the php (temporary) uploaded file
   * @param   string    $dest         The path (including filename) to move the uploaded file to
   * @return   boolean   True on success
   * @throws   Exception
   */
  public static function upload($src, $dest)
  {
    $dest = Path::clean($dest);
    $baseDir = dirname($dest);

    try {
      if ( !Folder::exists($baseDir) ){
        Folder::create($baseDir);
      }
    }
    catch(Exception $e){
      throw $e;
    }

    if ( is_writeable($baseDir) && move_uploaded_file($src, $dest) ){
      if ( Path::setPermissions($dest) ){
        return true;
      }

      throw new Exception(Helper::getTranslation('FAILED_CHMOD'));
    }

    throw new Exception(Helper::getTranslation('FAILED_MOVE_UPLOAD'));
  }

  /**
   * Gets the extension of a file name
   *
   * @param   string  $file  The file name
   * @return   string  The file extension
   */
  public static function getExt($file)
  {
    $dot = strrpos($file, '.') + 1;
    return substr($file, $dot);
  }

  /**
   * Strips the last extension off of a file name
   *
   * @param  string  $file  The file name
   * @return string  The file name without the extension
   */
  public static function stripExt($file)
  {
    return preg_replace('#\.[^.]*$#', '', $file);
  }

  /**
   * Returns the name, without any path.
   *
   * @param   string  $file  File path
   * @return   string  filename
   */
  public static function getName($file)
  {
    $file = str_replace('\\', '/', $file);
    $slash = strrpos($file, '/');
    if ( $slash !== false ){
      return substr($file, $slash + 1);
    }

    return $file;
  }

  /**
   * Returns the file path
   *
   * @param  string  $file
   * @return string
   */
  public static function getPath(string $file)
  {
    $parts = explode('/', $file);
    array_pop($parts);
    return implode('/', $parts);
  }

  /**
   * Returns the name, without any path nor extension
   *
   * @param  string  $file  File path
   * @return string  filename with no extension
   */
  public static function getStrippedName($file)
  {
    $name = self::getName($file);
    return self::stripExt($name);
  }

  /**
   * Makes file name safe to use
   *
   * @param  string  $file  The name of the file [not full path]
   * @return string  The sanitised string
   */
  public static function makeSafe($file)
  {
    $regex = [
      '#(\.){2,}#',
      '#[^A-Za-z0-9\.\_\- ]#', '#^\.#',
    ];

    $file = rtrim($file, '.');
    $clean = preg_replace($regex, ' ', $file);
    $clean = preg_replace("/[ \_]/", '-', $clean);
    $clean = preg_replace("/[\-]+/", '-', $clean);
    return $clean;
  }
}


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

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Mvc\Controller\RegistrationController,
    CmsUser\Options\ControllerOptionsInterface,
    CmsUser\Options\ModuleOptions;

class RegistrationControllerFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return RegistrationController
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        /* @var $options ControllerOptionsInterface */
        $options = $services->get(ModuleOptions::class);
        /* @var $formElementManager \Zend\Form\FormElementManager */
        $formElementManager = $services->get('FormElementManager');

        return new RegistrationController(
            $services->get('DomainServiceManager')->get($options->getUserEntityClass()),
            $options,
            $formElementManager->has('CmsAuthenticationIdentity')
                ? $formElementManager->get('CmsAuthenticationIdentity')
                : null,
            $formElementManager->has('CmsAuthenticationCredential')
                ? $formElementManager->get('CmsAuthenticationCredential')
                : null
        );
    }
}


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

namespace cascade\components\types;

use canis\helpers\ArrayHelper;
use Yii;

/**
 * Item [[@doctodo class_description:cascade\components\types\Item]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Item extends \canis\base\collector\Item
{
    /**
     * @var [[@doctodo var_type:_children]] [[@doctodo var_description:_children]]
     */
    protected $_children = [];
    /**
     * @var [[@doctodo var_type:_parents]] [[@doctodo var_description:_parents]]
     */
    protected $_parents = [];
    /**
     * @var [[@doctodo var_type:_sections]] [[@doctodo var_description:_sections]]
     */
    protected $_sections;
    /**
     * @var [[@doctodo var_type:_checked]] [[@doctodo var_description:_checked]]
     */
    protected $_checked;
    /**
     * @var [[@doctodo var_type:_init]] [[@doctodo var_description:_init]]
     */
    protected $_init = false;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->_init = true;
        $this->distributeRelationships();
    }

    /**
     * @inheritdoc
     */
    public function setObject($object)
    {
        parent::setObject($object);
        $this->distributeRelationships();

        return true;
    }

    /**
     * [[@doctodo method_description:distributeRelationships]].
     *
     * @return [[@doctodo return_type:distributeRelationships]] [[@doctodo return_description:distributeRelationships]]
     */
    protected function distributeRelationships()
    {
        if (!$this->_init || is_null($this->object)) {
            return;
        }

        foreach ($this->object->children() as $key => $child) {
            $options = [];
            if (is_string($key)) {
                $options = $child;
                $child = $key;
            }
            $this->collector->addRelationship($this->systemId, $child, $options);
        }
        foreach ($this->object->parents() as $key => $parent) {
            $options = [];
            if (is_string($key)) {
                $options = $parent;
                $parent = $key;
            }
            $this->collector->addRelationship($parent, $this->systemId, $options);
        }
    }

    /**
     * Get sections.
     *
     * @return unknown
     */
    public function getSections()
    {
        if (!is_null($this->_sections)) {
            return $this->_sections;
        }
        $this->_sections = [];
        foreach ($this->_children as $rel) {
            if (!$rel->active) {
                continue;
            }
            // if ($rel->isHasOne()) { continue; }
            $child = $rel->child;
            $instanceSettings = ['relationship' => $rel, 'queryRole' => 'children'];
            $items = Yii::$app->collectors['widgets']->getLocation('parent_objects', $child);
            foreach ($items as $item) {
                $widgetObject = $item->object;
                $item->settings = $instanceSettings;
                $section = $item->getSection($widgetObject, $instanceSettings);
                if (empty($section)) {
                    continue;
                }
                if (!isset($this->_sections[$item->section->systemId])) {
                    $this->_sections[$section->systemId] = $section;
                }
                $this->_sections[$section->systemId]->register($this, $item);
            }
        }

        foreach ($this->_parents as $rel) {
            if (!$rel->active) {
                continue;
            }
            if ($rel->isHasOne()) {
                continue;
            }
            $parent = $rel->parent;
            $instanceSettings = ['relationship' => $rel, 'queryRole' => 'parents'];
            $items = Yii::$app->collectors['widgets']->getLocation('child_objects', $parent);
            foreach ($items as $item) {
                $item->settings = $instanceSettings;
                $section = $item->getSection($this->object);
                if (empty($section)) {
                    continue;
                }
                if (!isset($this->_sections[$item->section->systemId])) {
                    $this->_sections[$section->systemId] = $section;
                }
                $this->_sections[$section->systemId]->register($this, $item);
            }
        }
        $items = Yii::$app->collectors['widgets']->getLocation('self',  $this->object);
        foreach ($items as $item) {
            $item->settings = $instanceSettings;
            $section = $item->getSection($this->object);
            if (empty($section)) {
                continue;
            }
            if (!isset($this->_sections[$item->section->systemId])) {
                $this->_sections[$section->systemId] = $section;
            }
            $this->_sections[$section->systemId]->register($this, $item);
        }

        ArrayHelper::multisort($this->_sections, ['priority', 'sectionTitle'], [SORT_ASC, SORT_ASC]);

        return $this->_sections;
    }

    /**
     * Get widgets.
     *
     * @return [[@doctodo return_type:getWidgets]] [[@doctodo return_description:getWidgets]]
     */
    public function getWidgets()
    {
        $sections = $this->sections;
        $widgets = [];
        foreach ($this->sections as $section) {
            foreach ($section->getAll() as $key => $widget) {
                $widgets[$key] = $widget;
            }
        }

        return $widgets;
    }
    /**
     * [[@doctodo method_description:addChild]].
     *
     * @param unknown $name
     * @param unknown $relationship
     *
     * @return unknown
     */
    public function addChild($name, $relationship)
    {
        $this->_children[$name] = $relationship;

        return true;
    }

    /**
     * [[@doctodo method_description:addParent]].
     *
     * @param unknown $name
     * @param unknown $relationship
     *
     * @return unknown
     */
    public function addParent($name, $relationship)
    {
        $this->_parents[$name] = $relationship;

        return true;
    }

    /**
     * Get child.
     *
     * @param unknown $type
     *
     * @return unknown
     */
    public function getChild($type)
    {
        if (isset($this->_children[$type])) {
            return $this->_children[$type];
        }

        return false;
    }

    /**
     * Get parent.
     *
     * @param unknown $type
     *
     * @return unknown
     */
    public function getParent($type)
    {
        if (isset($this->_parents[$type])) {
            return $this->_parents[$type];
        }

        return false;
    }

    /**
     * Get children.
     *
     * @return unknown
     */
    public function getChildren()
    {
        $children = [];
        foreach ($this->_children as $key => $child) {
            if (!$child->active) {
                continue;
            }
            $children[$key] = $child;
        }

        return $children;
    }

    /**
     * Get parents.
     *
     * @return unknown
     */
    public function getParents()
    {
        $parents = [];
        foreach ($this->_parents as $key => $parent) {
            if (!$parent->active) {
                continue;
            }
            $parents[$key] = $parent;
        }

        return $parents;
    }

    /**
     * Get active.
     *
     * @return unknown
     */
    public function getActive()
    {
        if (!is_null($this->hasObject()) && $this->checked) {
            return true;
        }

        return false;
    }

    /**
     * Get checked.
     *
     * @return unknown
     */
    public function getChecked()
    {
        if (is_null($this->object) || !$this->object) {
            return false;
        }
        if (is_null($this->_checked)) {
            $this->_checked = true;
            foreach ($this->object->dependencies() as $dep) {
                if (!$this->collector->has($dep, false)) {
                    $this->_checked = false;
                }
            }
        }

        return $this->_checked;
    }

    /**
     * Get taxonomies.
     *
     * @return [[@doctodo return_type:getTaxonomies]] [[@doctodo return_description:getTaxonomies]]
     */
    public function getTaxonomies()
    {
        $moduleClass = get_class($this->object);

        return Yii::$app->collectors['taxonomies']->getBucket('modules:' . $moduleClass::className())->toArray();
    }
}