<?php
/**
 * Copyright (c) 2018 Konstantin Deryabin
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Kod\BootstrapSlim;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Bootstrap
 */
class Bootstrap
{
    /**
     * @var object Slim App instance.
     */
    protected $app;

    /**
     * Bootstrap constructor.
     * @param string $slimClass Fully qualified Slim\App class name.
     * @param array $slimSettings Slim settings.
     */
    public function __construct(string $slimClass, $slimSettings = [])
    {
        $this->app = new $slimClass($slimSettings);
    }

    /**
     * Attach application middleware.
     * Override this method and declare your middlewares here.
     * The middleware definition order is important.
     * @return static
     * @example
     * public function addAppMiddleware()
     * {
     *      $this->addMiddleware(
     *          MyMiddleware::class,
     *          MyAnotherMiddleware::class
     *      );
     *      return $this;
     * }
     */
    public function addAppMiddleware()
    {
        return $this;
    }

    /**
     * Attach application routes.
     * Override this method and declare your route(s) here.
     * @return static
     * @example
     * public function addAppRoutes()
     * {
     *      $this->addRouteDefinitions(
     *          MyRoute::class,
     *          MyAnotherRoute::class
     *      );
     *      return $this;
     * }
     */
    public function addAppRoutes()
    {
        return $this;
    }

    /**
     * Inject application dependencies.
     * Override this method and declare your DI here.
     * @return static
     * @example
     * public function addAppDependencies()
     * {
     *      $container = $this->getContainer();
     *      // for pimple based container
     *      $container['session'] = $container->factory(function ($c) {
     *          return new Session($c['session_storage']);
     *      });
     *      return $this;
     * }
     */
    public function addAppDependencies()
    {
        return $this;
    }

    /**
     * Add application middleware
     * The only requirement: $middleware can be a callable or a string for a class name.
     * A $middleware may not be necessarily an instance of Kod\BootstrapSlim\Middleware.
     *
     * @param array ...$middleware
     * @return static
     * @throws \InvalidArgumentException
     */
    public function addMiddleware(...$middleware)
    {
        foreach ($middleware as $mw) {
            if (is_callable($mw)) {
                $this->app->add($mw);
            } elseif (is_string($mw)) {
                $class = $mw;
                $callable = new $class($this->getContainer());
                $this->app->add($callable);
            } else {
                throw new \InvalidArgumentException('Unsupported type for the middleware');
            }
        }

        return $this;
    }

    /**
     * Add application route(s).
     * The only requirement: $routes can be a callable or a string for a class name.
     * A $routes parameter may not be necessarily an instance of Kod\BootstrapSlim\RouteDefinitions.
     * @param $routes ...    Unlimited number of routes definitions.
     * @return static
     * @throws \InvalidArgumentException
     */
    public function addRouteDefinitions(...$routes)
    {
        foreach ($routes as $route) {
            if (is_callable($route)) {
                $route($this->app);
            } elseif (is_string($route)) {
                $callable = new $route();
                $callable($this->app);
            } else {
                throw new \InvalidArgumentException('Unsupported type for the route');
            }
        }

        return $this;
    }

    /**
     * Get Slim App instance.
     * @return object
     */
    public function getApp()
    {
        return $this->app;
    }

    /**
     * Get Slim container with app settings.
     * @return ContainerInterface
     */
    public function getContainer(): ContainerInterface
    {
        return $this->app->getContainer();
    }

    /**
     * Wrapper for Slim Ap::run() mrthod
     */
    /**
     * @param bool $silent
     * @return ResponseInterface
     */
    public function run(bool $silent = false)
    {
        return $this->app->run($silent);
    }

    /**
     * Shortcut for the URL generation of the named route
     * with the Slim application router’s pathFor() method
     * @param string $name
     * @param array $args
     * @return string
     */
    public function getPathFor(string $name, array $args): string
    {
        return $this->app->getContainer()->get('router')->pathFor($name, $args);
    }
}


<?php

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

/**
 * ShakeAround.php.
 *
 * @author    allen05ren <allen05ren@outlook.com>
 * @copyright 2016 overtrue <i@overtrue.me>
 *
 * @see       https://github.com/overtrue
 * @see       http://overtrue.me
 */

namespace EasyWeChat\ShakeAround;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class ShakeAround.
 */
class ShakeAround extends AbstractAPI
{
    const API_ACCOUNT_REGISTER = 'https://api.weixin.qq.com/shakearound/account/register';
    const API_ACCOUNT_AUDIT_STATUS = 'https://api.weixin.qq.com/shakearound/account/auditstatus';
    const API_GET_SHAKE_INFO = 'https://api.weixin.qq.com/shakearound/user/getshakeinfo';

    /**
     * Device instance.
     *
     * @var \EasyWeChat\ShakeAround\Device
     */
    protected $device = null;

    /**
     * Group instance.
     *
     * @var \EasyWeChat\ShakeAround\Group
     */
    protected $group = null;

    /**
     * Page instance.
     *
     * @var \EasyWeChat\ShakeAround\Page
     */
    protected $page = null;

    /**
     * Material instance.
     *
     * @var \EasyWeChat\ShakeAround\Material
     */
    protected $material = null;

    /**
     * Relation instance.
     *
     * @var \EasyWeChat\ShakeAround\Relation
     */
    protected $relation = null;

    /**
     * Stats instance.
     *
     * @var \EasyWeChat\ShakeAround\Stats
     */
    protected $stats = null;

    /**
     * Register shake around.
     *
     * @param string $name
     * @param string $tel
     * @param string $email
     * @param string $industryId
     * @param array  $certUrls
     * @param string $reason
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function register($name, $tel, $email, $industryId, array $certUrls, $reason = '')
    {
        $params = [
            'name' => $name,
            'phone_number' => strval($tel),
            'email' => $email,
            'industry_id' => $industryId,
            'qualification_cert_urls' => $certUrls,
        ];

        if ($reason !== '') {
            $params['apply_reason'] = $reason;
        }

        return $this->parseJSON('json', [self::API_ACCOUNT_REGISTER, $params]);
    }

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

    /**
     * Get shake info.
     *
     * @param string $ticket
     * @param int    $needPoi
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getShakeInfo($ticket, $needPoi = null)
    {
        $params = [
            'ticket' => $ticket,
        ];

        if ($needPoi !== null) {
            $params['need_poi'] = intval($needPoi);
        }

        return $this->parseJSON('json', [self::API_GET_SHAKE_INFO, $params]);
    }

    /**
     * Return the device instance.
     *
     * @return \EasyWeChat\ShakeAround\Device
     */
    public function device()
    {
        if (is_null($this->device)) {
            $this->device = new Device($this->accessToken);
        }

        return $this->device;
    }

    /**
     * Return the group instance.
     *
     * @return \EasyWeChat\ShakeAround\Group
     */
    public function group()
    {
        if (is_null($this->group)) {
            $this->group = new Group($this->accessToken);
        }

        return $this->group;
    }

    /**
     * Return the page instance.
     *
     * @return \EasyWeChat\ShakeAround\Page
     */
    public function page()
    {
        if (is_null($this->page)) {
            $this->page = new Page($this->accessToken);
        }

        return $this->page;
    }

    /**
     * Return the material instance.
     *
     * @return \EasyWeChat\ShakeAround\Material
     */
    public function material()
    {
        if (is_null($this->material)) {
            $this->material = new Material($this->accessToken);
        }

        return $this->material;
    }

    /**
     * Return the relation instance.
     *
     * @return \EasyWeChat\ShakeAround\Relation
     */
    public function relation()
    {
        if (is_null($this->relation)) {
            $this->relation = new Relation($this->accessToken);
        }

        return $this->relation;
    }

    /**
     * Return the stats instance.
     *
     * @return \EasyWeChat\ShakeAround\Stats
     */
    public function stats()
    {
        if (is_null($this->stats)) {
            $this->stats = new Stats($this->accessToken);
        }

        return $this->stats;
    }
}


<?php
/*
* Project:     SafeSQL: db access library extension
* File:        SafeSQL.class.php
* Author:      Monte Ohrt <monte at newdigitalgroup dot com>
*
* Version:     2.2 with modifications by Philip Kent
* Date:        March 27th, 2007, August 25th, 2013
* Copyright:   2001-2005 New Digital Group, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*/

class SafeSQL
{

    // values that determine dropping bracketed sections
    var $_drop_values = array('');

    /*======================================================================*\
    Function: SafeSQL
    Purpose:  constructor
    \*======================================================================*/
    function __construct() { }

    /*======================================================================*\
    Function: query
    Purpose:  process the query string
    \*======================================================================*/
    function query($query_string, $query_vars)
    {
        $app = \FelixOnline\Base\App::getInstance();
        $link_id = $app['db']->dbh;

        if(is_array($query_vars)) {

            $_var_count = count($query_vars);

            if($_var_count != preg_match_all('!%[sSiIfFcClLqQnN]!', $query_string, $_match)) {
                $this->_error_msg('unmatched number of vars and % placeholders: ' . $query_string);
            }

            // get string position for each element
            $_var_pos = array();
            $_curr_pos = 0;
            for( $_x = 0; $_x < $_var_count; $_x++ ) {
                $_var_pos[$_x] = strpos($query_string, $_match[0][$_x], $_curr_pos);
                $_curr_pos = $_var_pos[$_x] + 1;
            }
            // build query from passed in variables, escape them
            // start from end of query and work backwards so string
            // positions are not altered during replacement
            $_last_removed_pos = null;
            $_last_var_pos = null;
            for( $_x = $_var_count-1; $_x >= 0; $_x-- ) {
                if(isset($_last_removed_pos) && $_last_removed_pos < $_var_pos[$_x]) {
                    // already removed, skip
                    continue;
                }
                // escape string
                $query_vars[$_x] = $this->_sql_escape($link_id, $query_vars[$_x]);
                if(in_array($_match[0][$_x], array('%S','%I','%F','%C','%L','%Q','%N'))) {
                    // get positions of [ and ]
                    if(isset($_last_var_pos))
                    $_right_pos = strpos($query_string, ']', $_last_var_pos);
                    else
                    $_right_pos = strpos($query_string, ']', $_var_pos[$_x]);

                    // no way to get strpos from the right side starting in the middle
                    // of the string, so slice the first part out then find it
                    $_str_slice = substr($query_string, 0, $_var_pos[$_x]);
                    $_left_pos = strrpos($_str_slice, '[');

                    if($_right_pos === false || $_left_pos === false) {
                        $this->_error_msg('missing or unmatched brackets: ' . $query_string);
                    }
                    if(in_array($query_vars[$_x], $this->_drop_values, true)) {
                        $_last_removed_pos = $_left_pos;
                        // remove entire part of string
                        $query_string = substr_replace($query_string, '', $_left_pos, $_right_pos - $_left_pos + 1);
                        $_last_var_pos = null;
                    } else if ($_x > 0 && $_var_pos[$_x-1] > $_left_pos) {
                        // still variables left in brackets, leave them and just replace var
                        $_convert_var = $this->_convert_var($query_vars[$_x], $_match[0][$_x]);
                        $query_string = substr_replace($query_string, $_convert_var, $_var_pos[$_x], 2);
                        $_last_var_pos = $_var_pos[$_x] + strlen($_convert_var);
                    } else {
                        // remove the brackets only, and replace %S
                        $query_string = substr_replace($query_string, '', $_right_pos, 1);
                        $query_string = substr_replace($query_string, $this->_convert_var($query_vars[$_x], $_match[0][$_x]), $_var_pos[$_x], 2);
                        $query_string = substr_replace($query_string, '', $_left_pos, 1);
                        $_last_var_pos = null;
                    }
                } else {
                    $query_string = substr_replace($query_string, $this->_convert_var($query_vars[$_x], $_match[0][$_x]), $_var_pos[$_x], 2);
                }
            }
        }

        return $query_string;

    }

    /*======================================================================*\
    Function: _convert_var
    Purpose:  convert a variable to the given type
    Input:    $var - the variable
    $type - the type to convert to:
    %i, %I - cast to integer
    %f, %F - cast to float
    %c, %C - comma separate, cast each element to integer
    %l, %L - comma separate, no quotes, no casting
    %q, %Q - quote/comma separate
    %n, %N - wrap value in single quotes unless NULL
    \*======================================================================*/
    function _convert_var($var, $type) {
        switch($type) {
            case '%i':
            case '%I':
            // cast to integer
            settype($var, 'integer');
            break;
            case '%f':
            case '%F':
            // cast to float
            settype($var, 'float');
            break;
            case '%c':
            case '%C':
            // comma separate
            settype($var, 'array');
            for($_x = 0 , $_y = count($var); $_x < $_y; $_x++) {
                // cast to integers
                settype($var[$_x], 'integer');
            }
            $var = implode(',', $var);
            if($var == '') {
                // force 0, keep syntax from breaking
                $var = '0';
            }
            break;
            case '%l':
            case '%L':
            // comma separate
            settype($var, 'array');
            $var = implode(',', $var);
            break;
            case '%q':
            case '%Q':
            settype($var, 'array');
            // quote comma separate
            $var = "'" . implode("','", $var) . "'";
            break;
            case '%n':
            case '%N':
            if($var != 'NULL')
            $var = "'" . $var . "'";
            break;
        }
        return $var;
    }

    /*======================================================================*\
    Function: error
    Purpose:  handle error messages
    \*======================================================================*/
    function _error_msg($error_msg) {
        trigger_error('SafeSQL: ' . $error_msg);
    }

    /*======================================================================*\
    Function: SetDropValues
    Purpose:
    \*======================================================================*/
    function set_drop_values($drop_values) {
        if(is_array($drop_values)) {
            $this->_drop_values = $drop_values;
        } else {
            $this->_error_msg('drop values must be an array');
        }
    }

    /*======================================================================*\
    Function: GetDropValues
    Purpose:
    \*======================================================================*/
    function get_drop_values() {
        return $this->_drop_values;
    }

    /*======================================================================*\
    Function: _sql_escape
    Purpose:  method overridden by subclass
    \*======================================================================*/
    function _sql_escape($link_id, $var) { }

}

/*
* P. Kent
* August 2013
*/

class SafeSQL_MySQLi extends SafeSQL {

    /*======================================================================*\
    Function: SafeSQL_MySQL
    Purpose:  constructor
    \*======================================================================*/
    function __construct() {
    }

    /*======================================================================*\
    Function: _sql_escape
    Purpose:  recursively escape variables/arrays for SQL use
    \*======================================================================*/
    function _sql_escape($link_id, $var) {
        if(is_array($var)) {
            foreach($var as $_element) {
                $_newvar[] = $this->_sql_escape($link_id, $_element);
            }
            return $_newvar;
        }
        if(function_exists('mysqli_real_escape_string')) {
            return $link_id->real_escape_string($var);
        } else {
            return addslashes($var);
        }
    }
}

?>


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

namespace CmsUser\Factory\Form\Element;

use Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Form\Element\BirthdayVerify;

class BirthdayVerifyElementFactory extends BirthdayElementFactory
{
    /**
     * {@inheritDoc}
     *
     * @return BirthdayVerify
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        return $this->configureElement(new BirthdayVerify('birthdayVerify'), $services);
    }
}


<?php

namespace Chill\CustomFieldsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;

class CustomFieldsGroupType extends AbstractType
{

    private $customizableEntities; //TOOD : add comment about this variable

    /**
     *
     * @var \Symfony\Component\Translation\TranslatorInterface
     */
    private $translator;

    public function __construct(array $customizableEntities, TranslatorInterface $translator)
    {
        $this->customizableEntities = $customizableEntities;
        $this->translator = $translator;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    //TODO : details about the function
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        //prepare translation
        $entities = array();
        $customizableEntities = array(); //TODO : change name too close than $this->customizableEntities

        foreach($this->customizableEntities as $key => $definition) {
            $entities[$definition['class']] = $this->translator->trans($definition['name']);
            $customizableEntities[$definition['class']] = $definition;
        }

        $builder
            ->add('name', 'translatable_string')
            ->add('entity', 'choice', array(
                'choices' => $entities
            ))
        ;

        $builder->addEventListener(FormEvents::POST_SET_DATA,
                function(FormEvent $event) use ($customizableEntities, $builder){
                    $form = $event->getForm();
                    $group = $event->getData();

                    //stop the function if entity is not set
                    if ($group->getEntity() === NULL) {
                        return;
                    }

                    if (count($customizableEntities[$group->getEntity()]['options']) > 0) {
                        $optionBuilder = $builder
                                ->getFormFactory()
                                ->createBuilderForProperty(
                                        'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup',
                                        'options'
                                        )
                                ->create('options', null, array(
                                        'compound' => true,
                                        'auto_initialize' => false,
                                        'required' => false)
                                    );
                    }

                    foreach($customizableEntities[$group->getEntity()]['options'] as $key => $option) {
                                $optionBuilder
                                    ->add($key, $option['form_type'], $option['form_options'])
                            ;
                    }
                    if (isset($optionBuilder) && $optionBuilder->count() > 0) {
                        $form->add($optionBuilder->getForm());
                    }

                });
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'custom_fields_group';
    }
}


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

namespace cascade\models;

use Yii;

/**
 * ObjectType is the model class for table "object_type".
 *
 * @property string $name
 * @property double $system_version
 * @property string $created
 * @property string $modified
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class ObjectType extends \cascade\components\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function isAccessControlled()
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'Registry' => [
                'class' => 'canis\db\behaviors\Registry',
            ],
            'Roleable' => [
                'class' => 'cascade\components\db\behaviors\Roleable',
            ],
            'ActiveAccess' => [
                'class' => 'cascade\components\db\behaviors\ActiveAccess',
            ],
        ]);
    }

    /**
     * [[@doctodo method_description:determineAccessLevel]].
     *
     * @param [[@doctodo param_type:role]] $role [[@doctodo param_description:role]]
     * @param [[@doctodo param_type:aro]]  $aro  [[@doctodo param_description:aro]] [optional]
     *
     * @return [[@doctodo return_type:determineAccessLevel]] [[@doctodo return_description:determineAccessLevel]]
     */
    public function determineAccessLevel($role, $aro = null)
    {
        $objectTypeItem = Yii::$app->collectors['types']->getOne($this->name);
        if ($objectTypeItem && ($objectType = $objectTypeItem->object) && $objectType) {
            return $objectType->determineAccessLevel(null, $role, $aro);
        }

        return false;
    }

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'string', 'max' => 36],
            [['name'], 'required'],
            [['system_version'], 'number'],
            [['created', 'modified'], 'safe'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name',
            'system_version' => 'System Version',
            'created' => 'Created',
            'modified' => 'Modified',
        ];
    }
}


<?php

declare(strict_types = 1);

namespace OctoLab\Kilex\ServiceProvider;

use OctoLab\Common\Config\FileConfig;
use OctoLab\Common\Config\Loader\FileLoader;
use OctoLab\Common\Config\Loader\Parser\IniParser;
use OctoLab\Common\Config\Loader\Parser\JsonParser;
use OctoLab\Common\Config\Loader\Parser\ParserInterface;
use OctoLab\Common\Config\Loader\Parser\YamlParser;
use OctoLab\Common\Config\SimpleConfig;
use Symfony\Component\Config\FileLocator;

/**
 * @author Kamil Samigullin <kamil@samigullin.info>
 */
class ConfigServiceProvider
{
    /** @var string */
    protected $filename;
    /** @var array */
    protected $placeholders;

    /**
     * @param string $filename
     * @param array $placeholders
     *
     * @api
     */
    public function __construct(string $filename, array $placeholders = [])
    {
        \assert('is_readable($filename)');
        $this->filename = $filename;
        $this->placeholders = $placeholders;
    }

    /**
     * @param \Pimple $app
     *
     * @throws \InvalidArgumentException
     * @throws \Exception
     * @throws \DomainException
     *
     * @api
     */
    public function setup(\Pimple $app)
    {
        $app['config'] = $app::share(function () : SimpleConfig {
            $ext = strtolower(pathinfo($this->filename, PATHINFO_EXTENSION));
            if (\in_array($ext, ['ini', 'json', 'yml', 'yaml'], true)) {
                $loader = new FileLoader(new FileLocator(), $this->getParser($ext));
                $config = (new FileConfig($loader))->load($this->filename, $this->placeholders);
            } elseif ($ext === 'php') {
                $config = (new SimpleConfig(require $this->filename, $this->placeholders));
            } else {
                throw new \DomainException(sprintf('The file "%s" is not supported.', $this->filename));
            }
            return $config;
        });
    }

    /**
     * @param string $extension
     *
     * @return ParserInterface
     */
    private function getParser(string $extension): ParserInterface
    {
        switch (true) {
            case $extension === 'json':
                return new JsonParser();
            case $extension[0] === 'i':
                return new IniParser();
            default:
                return new YamlParser();
        }
    }
}


<?php

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

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

namespace EasyWeChat\Comment;

use EasyWeChat\Core\AbstractAPI;

class Comment extends AbstractAPI
{
    const API_OPEN_COMMENT = 'https://api.weixin.qq.com/cgi-bin/comment/open';
    const API_CLOSE_COMMENT = 'https://api.weixin.qq.com/cgi-bin/comment/close';
    const API_LIST_COMMENT = 'https://api.weixin.qq.com/cgi-bin/comment/list';
    const API_MARK_ELECT = 'https://api.weixin.qq.com/cgi-bin/comment/markelect';
    const API_UNMARK_ELECT = 'https://api.weixin.qq.com/cgi-bin/comment/unmarkelect';
    const API_DELETE_COMMENT = 'https://api.weixin.qq.com/cgi-bin/comment/delete';
    const API_REPLY_COMMENT = 'https://api.weixin.qq.com/cgi-bin/comment/reply/add';
    const API_DELETE_REPLY = 'https://api.weixin.qq.com/cgi-bin/comment/reply/delete';

    /**
     * Open article comment.
     *
     * @param string $msgId
     * @param int    $index
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function open($msgId, $index)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
        ];

        return $this->parseJSON('json', [self::API_OPEN_COMMENT, $params]);
    }

    /**
     * Close comment.
     *
     * @param string $msgId
     * @param int    $index
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function close($msgId, $index)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
        ];

        return $this->parseJSON('json', [self::API_CLOSE_COMMENT, $params]);
    }

    /**
     * Get article comments.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $begin
     * @param int    $count
     * @param int    $type
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists($msgId, $index, $begin, $count, $type = 0)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'begin' => $begin,
            'count' => $count,
            'type' => $type,
        ];

        return $this->parseJSON('json', [self::API_LIST_COMMENT, $params]);
    }

    /**
     * Mark elect comment.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $commentId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function markElect($msgId, $index, $commentId)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'user_comment_id' => $commentId,
        ];

        return $this->parseJSON('json', [self::API_MARK_ELECT, $params]);
    }

    /**
     * Unmark elect comment.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $commentId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function unmarkElect($msgId, $index, $commentId)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'user_comment_id' => $commentId,
        ];

        return $this->parseJSON('json', [self::API_UNMARK_ELECT, $params]);
    }

    /**
     * Delete comment.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $commentId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($msgId, $index, $commentId)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'user_comment_id' => $commentId,
        ];

        return $this->parseJSON('json', [self::API_DELETE_COMMENT, $params]);
    }

    /**
     * Reply to a comment.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $commentId
     * @param string $content
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function reply($msgId, $index, $commentId, $content)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'user_comment_id' => $commentId,
            'content' => $content,
        ];

        return $this->parseJSON('json', [self::API_REPLY_COMMENT, $params]);
    }

    /**
     * Delete a reply.
     *
     * @param string $msgId
     * @param int    $index
     * @param int    $commentId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function deleteReply($msgId, $index, $commentId)
    {
        $params = [
            'msg_data_id' => $msgId,
            'index' => $index,
            'user_comment_id' => $commentId,
        ];

        return $this->parseJSON('json', [self::API_DELETE_REPLY, $params]);
    }
}


<?php

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

namespace Pipeware\Pipeline;

use Pipeware\Pipeline\Exception\InvalidMiddlewareArgument;
use Pipeware\Stage\Lambda;
use Pipeware\Stage\RequestHandler;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

trait IsPipeline
{
	/**
	 * Replaces the first occurrence of the stage in the pipeline
	 *
	 * If no replacement is made the original pipeline is returned
	 *
	 * @param string $needle The class name to replace
	 * @param        $replacement
	 * @return Pipeline
	 */
	public function replace($needle, $replacement): Pipeline
	{
		$stages = [];
		$found  = false;
		foreach ($this->stages as $stage) {
			if ($this->matches($stage, $needle)) {
				$stages[] = $replacement;
				$found    = true;
				continue;
			}

			$stages[] = $stage;
		}

		if ($found) {
			$pipeline         = clone $this;
			$pipeline->stages = $stages;

			return $pipeline;
		}

		unset($stages);

		return $this;
	}

	/**
	 * Placeholder since pipeline don't extend a common base
	 *
	 * @param $stage
	 * @param $needle
	 * @return bool
	 */
	protected function matches($stage, $needle): bool
	{
		throw new \RuntimeException("Please implement " . get_class($this) . '::matches');
	}

	/**
	 * Handles merging or converting the stage to a callback
	 *
	 * @param array                    $stages
	 * @param Pipeline|MiddlewareInterface|RequestHandlerInterface|string|callable $stage
	 */
	protected function handleStage(&$stages, $stage)
	{
		if ($stage instanceof Pipeline) {
			$stages = array_merge($stages, $stage->stages());
		}
		elseif ($stage instanceof MiddlewareInterface) {
			$stages[] = $stage;
		}
		elseif ($stage instanceof RequestHandlerInterface) {
			$stages[] = new RequestHandler($stage);
		}
		elseif (is_callable($stage)) {
			$stages[] = new Lambda($stage);
		}
		else {
			throw new InvalidMiddlewareArgument(is_string($stage) ? $stage : get_class($stage));
		}
	}
}


<?php

namespace Versatile\Search;

use Versatile\Search\Contracts\Filter as FilterContract;
use Versatile\Search\Contracts\Expression as ExpressionContract;
use Versatile\Search\Contracts\Queryable;

use ArrayIterator;
use OutOfBoundsException;

class Filter implements FilterContract
{

    /**
     * The added expressions
     *
     * @var array
     **/
    protected $expressions = [];

    /**
     * @var \Versatile\Search\Contracts\Expression
     **/
    protected $expressionPrototype;

    public function __construct(ExpressionContract $expressionPrototype=null)
    {
        $this->expressionPrototype = $expressionPrototype ?: new Expression;
    }

    /**
     * Add an expression to this filter
     *
     * @param \Versatile\Search\Contracts\Expression $expression
     * @return self
     **/
    public function add(ExpressionContract $e)
    {
        $this->expressions[] = $e;
        return $this;
    }

    /**
     * Remove an expression to this filter
     *
     * @param \Versatile\Search\Contracts\Expression $expression
     * @return self
     * @throws \OutOfBoundsException
     **/
    public function remove(ExpressionContract $e)
    {
        unset($this->expressions[$this->indexOf($e)]);
        $this->expressions = array_values($this->expressions);
        return $this;
    }

    /**
     * Finds the index of expression or column name
     *
     * @param \Versatile\Search\Contracts\Expression|string
     * @return int
     * @throws \OutOfBoundsException
     **/
    public function indexOf($expressionOrColumn)
    {
        if ($expressionOrColumn instanceof ExpressionContract) {
            return $this->indexOfExpression($expressionOrColumn);
        }
        return $this->indexOfColumn($expressionOrColumn);
    }

    /**
     * Removes all expressions from this filter
     *
     * @return self
     **/
    public function clear()
    {
        $this->expressions = [];
    }

    /**
     * Returns the amount of added expressions
     *
     * @return int
     **/
    public function count()
    {
        return count($this->expressions);
    }

    /**
     * Allows simple walking through foreach
     *
     * @return \ArrayIterator
     **/
    public function getIterator()
    {
        return new ArrayIterator($this->expressions);
    }

    /**
     * Checks if an expression exists at position $indexOrColumn or if an
     * expression was added vor column $indexOrColumn
     *
     * @param string|int $indexOrColumn
     * @return bool
     **/
    public function offsetExists($indexOrColumn)
    {

        if (is_numeric($indexOrColumn)) {
            return isset($this->expressions[(int)$indexOrColumn]);
        }

        try {
            return is_int($this->indexOfColumn($indexOrColumn));
        } catch (OutOfBoundsException $e) {
            return false;
        }
    }

    public function offsetGet($indexOrColumn)
    {

        if (is_numeric($indexOrColumn) && isset($this->expressions[(int)$indexOrColumn])) {
            return $this->expressions[(int)$indexOrColumn];
        }

        return $this->expressions[$this->indexOf($indexOrColumn)];
    }

    public function offsetSet($indexOrColumn, $value)
    {
        if (is_numeric($indexOrColumn)) {
            $this->expressions[(int)$indexOrColumn] = $value;
        }

        try {
            $this->expressions[$this->indexOf($indexOrColumn)] = $value;
        } catch (OutOfBoundsException $e) {
            $this->add($value);
        }
    }

    public function offsetUnset($indexOrColumn)
    {
        if (is_numeric($indexOrColumn)) {
            unset($this->expressions[(int)$indexOrColumn]);
            $this->expressions = array_values($this->expressions);
        }

        try {
            unset($this->expressions[$this->indexOf($indexOrColumn)]);
        } catch (OutOfBoundsException $e) {}

    }

    protected function indexOfExpression(ExpressionContract $e)
    {

        $index = array_search($e, $this->expressions, true);

        if ($index === false) {
            throw new OutOfBoundsException('Expression not found');
        }

        return $index;

    }

    public function indexOfColumn($column)
    {
        foreach ($this->expressions as $index=>$expression) {
            if ($expression->key() == $column) {
                return $index;
            }
        }
        throw new OutOfBoundsException("Column $column not found in filter");
    }

    /**
     * {@inheritdoc} Adds a new expression and returns itself
     *
     * @param string $key
     * @param string $operator
     * @param mixed $value
     * @param string $boolean
     * @return self
     **/
    public function where($key, $operator, $value=null, $boolean=Queryable::AND_)
    {
        return $this->add($this->newExpression($key, $operator, $value, $boolean));
    }

    protected function newExpression($key, $operator, $value, $boolean)
    {
        $expression = clone $this->expressionPrototype;
        return $expression->where($key, $operator, $value, $boolean);
    }

}


<?php

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

namespace Predis\Connection\Replication;

use Predis\Command\CommandInterface;
use Predis\Command\RawCommand;
use Predis\CommunicationException;
use Predis\Connection\ConnectionException;
use Predis\Connection\FactoryInterface as ConnectionFactoryInterface;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\Parameters;
use Predis\Replication\ReplicationStrategy;
use Predis\Replication\RoleException;
use Predis\Response\ErrorInterface as ErrorResponseInterface;
use Predis\Response\ServerException;

/**
 * @author Daniele Alessandri <suppakilla@gmail.com>
 * @author Ville Mattila <ville@eventio.fi>
 */
class SentinelReplication implements ReplicationInterface
{
    /**
     * @var NodeConnectionInterface
     */
    protected $master;

    /**
     * @var NodeConnectionInterface[]
     */
    protected $slaves = array();

    /**
     * @var NodeConnectionInterface[]
     */
    protected $pool = array();

    /**
     * @var NodeConnectionInterface
     */
    protected $current;

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

    /**
     * @var ConnectionFactoryInterface
     */
    protected $connectionFactory;

    /**
     * @var ReplicationStrategy
     */
    protected $strategy;

    /**
     * @var NodeConnectionInterface[]
     */
    protected $sentinels = array();

    /**
     * @var NodeConnectionInterface
     */
    protected $sentinelConnection;

    /**
     * @var float
     */
    protected $sentinelTimeout = 0.100;

    /**
     * Max number of automatic retries of commands upon server failure.
     *
     * -1 = unlimited retry attempts
     *  0 = no retry attempts (fails immediatly)
     *  n = fail only after n retry attempts
     *
     * @var int
     */
    protected $retryLimit = 20;

    /**
     * Time to wait in milliseconds before fetching a new configuration from one
     * of the sentinel servers.
     *
     * @var int
     */
    protected $retryWait = 1000;

    /**
     * Flag for automatic fetching of available sentinels.
     *
     * @var bool
     */
    protected $updateSentinels = false;

    /**
     * @param string                     $service           Name of the service for autodiscovery.
     * @param array                      $sentinels         Sentinel servers connection parameters.
     * @param ConnectionFactoryInterface $connectionFactory Connection factory instance.
     * @param ReplicationStrategy        $strategy          Replication strategy instance.
     */
    public function __construct(
        $service,
        array $sentinels,
        ConnectionFactoryInterface $connectionFactory,
        ReplicationStrategy $strategy = null
    ) {
        $this->sentinels = $sentinels;
        $this->service = $service;
        $this->connectionFactory = $connectionFactory;
        $this->strategy = $strategy ?: new ReplicationStrategy();
    }

    /**
     * Sets a default timeout for connections to sentinels.
     *
     * When "timeout" is present in the connection parameters of sentinels, its
     * value overrides the default sentinel timeout.
     *
     * @param float $timeout Timeout value.
     */
    public function setSentinelTimeout($timeout)
    {
        $this->sentinelTimeout = (float) $timeout;
    }

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

    /**
     * Sets the time to wait (in seconds) before fetching a new configuration
     * from one of the sentinels.
     *
     * @param float $seconds Time to wait before the next attempt.
     */
    public function setRetryWait($seconds)
    {
        $this->retryWait = (float) $seconds;
    }

    /**
     * Set automatic fetching of available sentinels.
     *
     * @param bool $update Enable or disable automatic updates.
     */
    public function setUpdateSentinels($update)
    {
        $this->updateSentinels = (bool) $update;
    }

    /**
     * Resets the current connection.
     */
    protected function reset()
    {
        $this->current = null;
    }

    /**
     * Wipes the current list of master and slaves nodes.
     */
    protected function wipeServerList()
    {
        $this->reset();

        $this->master = null;
        $this->slaves = array();
        $this->pool = array();
    }

    /**
     * {@inheritdoc}
     */
    public function add(NodeConnectionInterface $connection)
    {
        $parameters = $connection->getParameters();

        if ('master' === $role = $parameters->role) {
            $this->master = $connection;
        } elseif ('sentinel' === $role) {
            $this->sentinels[] = $connection;
            // sentinels are not considered part of the pool.
            return;
        } else {
            // everything else is considered a slave.
            $this->slaves[] = $connection;
        }

        $this->pool[(string) $connection] = $connection;

        $this->reset();
    }

    /**
     * {@inheritdoc}
     */
    public function remove(NodeConnectionInterface $connection)
    {
        if ($connection === $this->master) {
            $this->master = null;
        } elseif (false !== $id = array_search($connection, $this->slaves, true)) {
            unset($this->slaves[$id]);
        } elseif (false !== $id = array_search($connection, $this->sentinels, true)) {
            unset($this->sentinels[$id]);

            return true;
        } else {
            return false;
        }

        unset($this->pool[(string) $connection]);

        $this->reset();

        return true;
    }

    /**
     * Creates a new connection to a sentinel server.
     *
     * @return NodeConnectionInterface
     */
    protected function createSentinelConnection($parameters)
    {
        if ($parameters instanceof NodeConnectionInterface) {
            return $parameters;
        }

        if (is_string($parameters)) {
            $parameters = Parameters::parse($parameters);
        }

        if (is_array($parameters)) {
            // We explicitly set "database" and "password" to null,
            // so that no AUTH and SELECT command is send to the sentinels.
            $parameters['database'] = null;
            $parameters['password'] = null;

            if (!isset($parameters['timeout'])) {
                $parameters['timeout'] = $this->sentinelTimeout;
            }
        }

        $connection = $this->connectionFactory->create($parameters);

        return $connection;
    }

    /**
     * Returns the current sentinel connection.
     *
     * If there is no active sentinel connection, a new connection is created.
     *
     * @return NodeConnectionInterface
     */
    public function getSentinelConnection()
    {
        if (!$this->sentinelConnection) {
            if (!$this->sentinels) {
                throw new \Predis\ClientException('No sentinel server available for autodiscovery.');
            }

            $sentinel = array_shift($this->sentinels);
            $this->sentinelConnection = $this->createSentinelConnection($sentinel);
        }

        return $this->sentinelConnection;
    }

    /**
     * Fetches an updated list of sentinels from a sentinel.
     */
    public function updateSentinels()
    {
        SENTINEL_QUERY: {
            $sentinel = $this->getSentinelConnection();

            try {
                $payload = $sentinel->executeCommand(
                    RawCommand::create('SENTINEL', 'sentinels', $this->service)
                );

                $this->sentinels = array();
                // NOTE: sentinel server does not return itself, so we add it back.
                $this->sentinels[] = $sentinel->getParameters()->toArray();

                foreach ($payload as $sentinel) {
                    $this->sentinels[] = array(
                        'host' => $sentinel[3],
                        'port' => $sentinel[5],
                        'role' => 'sentinel',
                    );
                }
            } catch (ConnectionException $exception) {
                $this->sentinelConnection = null;

                goto SENTINEL_QUERY;
            }
        }
    }

    /**
     * Fetches the details for the master and slave servers from a sentinel.
     */
    public function querySentinel()
    {
        $this->wipeServerList();

        $this->updateSentinels();
        $this->getMaster();
        $this->getSlaves();
    }

    /**
     * Handles error responses returned by redis-sentinel.
     *
     * @param NodeConnectionInterface $sentinel Connection to a sentinel server.
     * @param ErrorResponseInterface  $error    Error response.
     */
    private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error)
    {
        if ($error->getErrorType() === 'IDONTKNOW') {
            throw new ConnectionException($sentinel, $error->getMessage());
        } else {
            throw new ServerException($error->getMessage());
        }
    }

    /**
     * Fetches the details for the master server from a sentinel.
     *
     * @param NodeConnectionInterface $sentinel Connection to a sentinel server.
     * @param string                  $service  Name of the service.
     *
     * @return array
     */
    protected function querySentinelForMaster(NodeConnectionInterface $sentinel, $service)
    {
        $payload = $sentinel->executeCommand(
            RawCommand::create('SENTINEL', 'get-master-addr-by-name', $service)
        );

        if ($payload === null) {
            throw new ServerException('ERR No such master with that name');
        }

        if ($payload instanceof ErrorResponseInterface) {
            $this->handleSentinelErrorResponse($sentinel, $payload);
        }

        return array(
            'host' => $payload[0],
            'port' => $payload[1],
            'role' => 'master',
        );
    }

    /**
     * Fetches the details for the slave servers from a sentinel.
     *
     * @param NodeConnectionInterface $sentinel Connection to a sentinel server.
     * @param string                  $service  Name of the service.
     *
     * @return array
     */
    protected function querySentinelForSlaves(NodeConnectionInterface $sentinel, $service)
    {
        $slaves = array();

        $payload = $sentinel->executeCommand(
            RawCommand::create('SENTINEL', 'slaves', $service)
        );

        if ($payload instanceof ErrorResponseInterface) {
            $this->handleSentinelErrorResponse($sentinel, $payload);
        }

        foreach ($payload as $slave) {
            $flags = explode(',', $slave[9]);

            if (array_intersect($flags, array('s_down', 'o_down', 'disconnected'))) {
                continue;
            }

            $slaves[] = array(
                'host' => $slave[3],
                'port' => $slave[5],
                'role' => 'slave',
            );
        }

        return $slaves;
    }

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

    /**
     * {@inheritdoc}
     */
    public function getMaster()
    {
        if ($this->master) {
            return $this->master;
        }

        if ($this->updateSentinels) {
            $this->updateSentinels();
        }

        SENTINEL_QUERY: {
            $sentinel = $this->getSentinelConnection();

            try {
                $masterParameters = $this->querySentinelForMaster($sentinel, $this->service);
                $masterConnection = $this->connectionFactory->create($masterParameters);

                $this->add($masterConnection);
            } catch (ConnectionException $exception) {
                $this->sentinelConnection = null;

                goto SENTINEL_QUERY;
            }
        }

        return $masterConnection;
    }

    /**
     * {@inheritdoc}
     */
    public function getSlaves()
    {
        if ($this->slaves) {
            return array_values($this->slaves);
        }

        if ($this->updateSentinels) {
            $this->updateSentinels();
        }

        SENTINEL_QUERY: {
            $sentinel = $this->getSentinelConnection();

            try {
                $slavesParameters = $this->querySentinelForSlaves($sentinel, $this->service);

                foreach ($slavesParameters as $slaveParameters) {
                    $this->add($this->connectionFactory->create($slaveParameters));
                }
            } catch (ConnectionException $exception) {
                $this->sentinelConnection = null;

                goto SENTINEL_QUERY;
            }
        }

        return array_values($this->slaves);
    }

    /**
     * Returns a random slave.
     *
     * @return NodeConnectionInterface
     */
    protected function pickSlave()
    {
        if ($slaves = $this->getSlaves()) {
            return $slaves[rand(1, count($slaves)) - 1];
        }
    }

    /**
     * Returns the connection instance in charge for the given command.
     *
     * @param CommandInterface $command Command instance.
     *
     * @return NodeConnectionInterface
     */
    private function getConnectionInternal(CommandInterface $command)
    {
        if (!$this->current) {
            if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) {
                $this->current = $slave;
            } else {
                $this->current = $this->getMaster();
            }

            return $this->current;
        }

        if ($this->current === $this->master) {
            return $this->current;
        }

        if (!$this->strategy->isReadOperation($command)) {
            $this->current = $this->getMaster();
        }

        return $this->current;
    }

    /**
     * Asserts that the specified connection matches an expected role.
     *
     * @param NodeConnectionInterface $connection Connection to a redis server.
     * @param string                  $role       Expected role of the server ("master", "slave" or "sentinel").
     *
     * @throws RoleException
     */
    protected function assertConnectionRole(NodeConnectionInterface $connection, $role)
    {
        $role = strtolower($role);
        $actualRole = $connection->executeCommand(RawCommand::create('ROLE'));

        if ($role !== $actualRole[0]) {
            throw new RoleException($connection, "Expected $role but got $actualRole[0] [$connection]");
        }
    }

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

        if (!$connection->isConnected()) {
            // When we do not have any available slave in the pool we can expect
            // read-only operations to hit the master server.
            $expectedRole = $this->strategy->isReadOperation($command) && $this->slaves ? 'slave' : 'master';
            $this->assertConnectionRole($connection, $expectedRole);
        }

        return $connection;
    }

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

    /**
     * Returns a connection by its role.
     *
     * @param string $role Connection role (`master`, `slave` or `sentinel`)
     *
     * @return NodeConnectionInterface|null
     */
    public function getConnectionByRole($role)
    {
        if ($role === 'master') {
            return $this->getMaster();
        } elseif ($role === 'slave') {
            return $this->pickSlave();
        } elseif ($role === 'sentinel') {
            return $this->getSentinelConnection();
        }
    }

    /**
     * Switches the internal connection in use by the backend.
     *
     * Sentinel connections are not considered as part of the pool, meaning that
     * trying to switch to a sentinel will throw an exception.
     *
     * @param NodeConnectionInterface $connection Connection instance in the pool.
     */
    public function switchTo(NodeConnectionInterface $connection)
    {
        if ($connection && $connection === $this->current) {
            return;
        }

        if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) {
            throw new \InvalidArgumentException('Invalid connection or connection not found.');
        }

        $connection->connect();

        if ($this->current) {
            $this->current->disconnect();
        }

        $this->current = $connection;
    }

    /**
     * {@inheritdoc}
     */
    public function switchToMaster()
    {
        $connection = $this->getConnectionByRole('master');
        $this->switchTo($connection);
    }

    /**
     * {@inheritdoc}
     */
    public function switchToSlave()
    {
        $connection = $this->getConnectionByRole('slave');
        $this->switchTo($connection);
    }

    /**
     * {@inheritdoc}
     */
    public function isConnected()
    {
        return $this->current ? $this->current->isConnected() : false;
    }

    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        if (!$this->current) {
            if (!$this->current = $this->pickSlave()) {
                $this->current = $this->getMaster();
            }
        }

        $this->current->connect();
    }

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

    /**
     * Retries the execution of a command upon server failure after asking a new
     * configuration to one of the sentinels.
     *
     * @param CommandInterface $command Command instance.
     * @param string           $method  Actual method.
     *
     * @return mixed
     */
    private function retryCommandOnFailure(CommandInterface $command, $method)
    {
        $retries = 0;

        SENTINEL_RETRY: {
            try {
                $response = $this->getConnectionByCommand($command)->$method($command);
            } catch (CommunicationException $exception) {
                $this->wipeServerList();
                $exception->getConnection()->disconnect();

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

                usleep($this->retryWait * 1000);

                ++$retries;
                goto SENTINEL_RETRY;
            }
        }

        return $response;
    }

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

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

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

    /**
     * Returns the underlying replication strategy.
     *
     * @return ReplicationStrategy
     */
    public function getReplicationStrategy()
    {
        return $this->strategy;
    }

    /**
     * {@inheritdoc}
     */
    public function __sleep()
    {
        return array(
            'master', 'slaves', 'pool', 'service', 'sentinels', 'connectionFactory', 'strategy',
        );
    }
}


<?php
/**
 * Модель статьи
 *
 * @version ${product.version}
 *
 * @copyright 2013, ООО "Два слона", http://dvaslona.ru/
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <mk@dvaslona.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 */

/**
 * Модель статьи
 *
 * @property       int      $id         идентификатор
 * @property       int      $section    идентификатор раздела
 * @property       bool     $active     вкл/выкл
 * @property       int      $position   порядковый номер
 * @property       DateTime $posted     дата публикации
 * @property       bool     $block      показывать в блоке
 * @property       string   $caption    заголовок
 * @property       string   $preview    краткий текст
 * @property       string   $text       полный текст
 * @property-write string   $image      задаёт картинку по имени элемента массива $_FILES
 * @property-read  string   $imageUrl   адрес картинки
 * @property-read  string   $thumbUrl   адрес миниатюры
 * @property-read  string   $clientUrl  адрес статьи
 *
 * @since 3.01
 */
class Articles_Entity_Article extends ORM_Entity implements ArrayAccess
{
    /**
     * Временный файл для добавляемой картинки
     * @var null|string
     * @since 3.01
     */
    private $tmpFile = null;

    /**
     * Действия перед сохранением объекта в БД
     *
     * @param ezcQuery $query
     *
     * @return ezcQuery
     *
     * @since 3.01
     */
    public function beforeSave(ezcQuery $query)
    {
        $query = parent::beforeSave($query);

        /*
         * Если это новая статья — вычисляем новый порядковый номер
         */
        if ($query instanceof ezcQueryInsert)
        {
            $q = $this->getTable()->createSelectQuery(false);
            $q->select('*');
            $e = $q->expr;
            $q->where($e->eq('section', $q->bindValue($this->section, null, PDO::PARAM_INT)));
            $q->orderBy('position', $q::DESC);
            /** @var self $max */
            $max = $this->getTable()->loadOneFromQuery($q);
            $query->set('position',
                $query->bindValue($max->position + 1, ":position", PDO::PARAM_INT));
            /*
             * Обновляем краткое описание, если надо
             */
            if (!$this->preview)
            {
                $this->createPreviewFromText();
                /** @var ezcQueryInsert|ezcQueryUpdate $query */
                $query->set('preview', $query->bindValue($this->preview, ':preview'));
            }
        }

        return $query;
    }

    /**
     * Действия после сохранения объекта в БД
     *
     * @since 3.01
     */
    public function afterSave()
    {
        if ($this->tmpFile)
        /* Если был загружен новый файл… */
        {
            /** @var Articles $plugin */
            $plugin = $this->getTable()->getPlugin();
            $filename = Eresus_Kernel::app()->getFsRoot() . '/data/' . $plugin->getName() . '/'
                . $this->id;
            $settings = $plugin->settings;
            thumbnail($this->tmpFile, $filename . '.jpg', $settings['imageWidth'],
                $settings['imageHeight'], $settings['imageColor']);
            thumbnail($this->tmpFile, $filename . '-thmb.jpg',
                $settings['THimageWidth'], $settings['THimageHeight'],
                $settings['imageColor']);
            unlink($this->tmpFile);
        }
    }

    /**
     * Дополнительные действия при удалении
     *
     * @since 3.01
     */
    public function afterDelete()
    {
        /** @var Articles $plugin */
        $plugin = $this->getTable()->getPlugin();
        $basename = Eresus_Kernel::app()->getFsRoot() . '/data/' . $plugin->getName() .
            '/' . $this->id;
        $filename = $basename . '.jpg';
        if (file_exists($filename))
        {
            unlink($filename);
        }
        $filename = $basename . '-thmb.jpg';
        if (file_exists($filename))
        {
            unlink($filename);
        }
    }

    /**
     * Автоматически заполняет свойство $preview на основе свойства $text
     *
     * @since 3.01
     */
    public function createPreviewFromText()
    {
        $preview = $this->text;
        $preview = trim(preg_replace('/<.+>/Us', ' ', $preview));
        $preview = str_replace(array("\n", "\r"), ' ', $preview);
        $preview = preg_replace('/\s{2,}/U', ' ', $preview);

        /** @var Articles $plugin */
        $plugin = $this->getTable()->getPlugin();
        $settings = $plugin->settings;
        if (!$settings['previewMaxSize'])
        {
            $settings['previewMaxSize'] = 500;
        }

        if ($settings['previewSmartSplit'])
        {
            preg_match("/\A(.{1," . $settings['previewMaxSize'] .
                "})(\.\s|\.|\Z)/Us", $preview, $result);
            $preview = $result[1];
        }
        else
        {
            $preview = mb_substr($preview, 0, $settings['previewMaxSize']);
        }
        if (mb_strlen($preview) < mb_strlen($this->text))
        {
            $preview .= '…';
        }
        $this->preview = strval($preview);
    }

    /**
     * @see {@link ArrayAccess}
     * @since 3.01
     */
    public function offsetExists($offset)
    {
        return $this->__get($offset) !== null;
    }

    /**
     * @see {@link ArrayAccess}
     * @since 3.01
     */
    public function offsetGet($offset)
    {
        $value = $this->{$offset};
        if ($value instanceof DateTime)
        {
            $value = $value->format('Y-m-d H:i:s');
        }
        return $value;
    }

    /**
     * @see {@link ArrayAccess}
     * @since 3.01
     */
    public function offsetSet($offset, $value)
    {
        $this->{$offset} = $value;
    }

    /**
     * @see {@link ArrayAccess}
     * @since 3.01
     */
    public function offsetUnset($offset)
    {
        $this->{$offset} = null;
    }

    /**
     * Отрисовывает статью, используя шаблон
     *
     * @param string $template
     *
     * @return string  HTML
     *
     * @since 3.01
     * @todo удалить после перехода на Dwoo
     */
    public function render($template)
    {
        $html = str_replace(
            array(
                '$(caption)',
                '$(preview)',
                '$(text)',
                '$(posted)',
                '$(clientUrl)',
                '$(imageUrl)',
                '$(thumbUrl)',
            ),
            array(
                $this->caption,
                $this->preview,
                $this->text,
                $this->posted->format('d.m.y'),
                $this->clientUrl,
                $this->imageUrl,
                $this->thumbUrl,
            ),
            $template
        );
        return $html;
    }

    /**
     * Задаёт заголовок статьи
     *
     * @param string $caption
     * @since 3.01
     */
    protected function setCaption($caption)
    {
        $this->setPdoValue('caption', strip_tags(htmlspecialchars($caption)));
    }

    /**
     * Задаёт изображение
     *
     * Если $value — null, изображение будет удалено
     *
     * @param string|null $value
     *
     * @since 3.01
     */
    protected function setImage($value)
    {
        /** @var Articles $plugin */
        $plugin = $this->getTable()->getPlugin();
        if (null === $value && $this->imageUrl)
        {
            $root = Eresus_Kernel::app()->getLegacyKernel()->fdata;
            @unlink($root . $plugin->getName() . '/' . $this->id . '.jpg');
            @unlink($root . $plugin->getName() . '/' . $this->id . '-thmb.jpg');
        }
        elseif (is_uploaded_file($_FILES[$value]['tmp_name']))
        {
            $this->tmpFile = upload('image',
                tempnam(Eresus_Kernel::app()->getFsRoot() . 'var', $plugin->getName()));
        }
    }

    /**
     * Возвращает адрес картинки
     *
     * @return string|null
     *
     * @since 3.01
     */
    protected function getImageUrl()
    {
        /** @var Articles $plugin */
        $plugin = $this->getTable()->getPlugin();
        $localPart = $plugin->getName() . '/' . $this->id . '.jpg';
        if (file_exists(Eresus_Kernel::app()->getLegacyKernel()->fdata . $localPart))
        {
            return Eresus_Kernel::app()->getLegacyKernel()->data . $localPart;
        }
        return null;
    }

    /**
     * Возвращает адрес миниатюры
     *
     * @return string|null
     *
     * @since 3.01
     */
    protected function getThumbUrl()
    {
        /** @var Articles $plugin */
        $plugin = $this->getTable()->getPlugin();
        $localPart = $plugin->getName() . '/' . $this->id . '-thmb.jpg';
        if (file_exists(Eresus_Kernel::app()->getLegacyKernel()->fdata . $localPart))
        {
            return Eresus_Kernel::app()->getLegacyKernel()->data . $localPart;
        }
        return null;
    }

    /**
     * Возвращает адрес статьи
     *
     * @return string
     *
     * @since 3.01
     */
    protected function getClientUrl()
    {
        return Eresus_Kernel::app()->getPage()->clientURL($this->section) . $this->id . '/';
    }
}


<?php
namespace eMacros\Runtime\Collection;

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

class ArraySort implements Applicable {
	/**
	 * Callback to invoke
	 * @var callable
	 */
	public $callback;

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

	/**
	 * Array sort wrapper callback
	 * Usage: (Array::sort _array) (Array::arsort _arr)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("ArraySort: No array specified.");
		$target = $arguments[0];
		if (!($target instanceof Symbol))
			throw new \InvalidArgumentException(sprintf("ArraySort: Expected symbol as first argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[0]), '\\')), 1)));
		$ref = $target->symbol;

		if (is_array($scope->symbols[$ref])) {
			$func = $this->callback;
			if (count($arguments) > 1)
				return $func($scope->symbols[$ref], $arguments[1]->evaluate($scope));
			return $func($scope->symbols[$ref]);
		}

		throw new \InvalidArgumentException(sprintf("ArraySort: Expected array as first argument but %s was found instead.", gettype($scope->symbols[$ref])));
	}
}
?>


<?php

namespace OpenOrchestra\ModelBundle\Form\DataTransformer;

use OpenOrchestra\ModelInterface\Model\SiteInterface;
use OpenOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

/**
 * Class EmbedSiteToSiteTransformer
 */
class EmbedSiteToSiteTransformer implements DataTransformerInterface
{
    protected $siteRepositoy;

    /**
     * @param SiteRepositoryInterface $siteRepository
     */
    public function __construct(SiteRepositoryInterface $siteRepository)
    {
        $this->siteRepositoy = $siteRepository;
    }

    /**
     * @param array $value
     *
     * @return SiteInterface
     *
     * @throws TransformationFailedException When the transformation fails.
     */
    public function transform($value)
    {
        $sites = array();

        if (!empty($value)) {
            foreach ($value as $associatedSite) {
                $sites[] = $this->siteRepositoy->findOneBySiteId($associatedSite['siteId']);
            }
        }

        return $sites;
    }

    /**
     * @param SiteInterface $value
     *
     * @return string
     *
     * @throws TransformationFailedException When the transformation fails.
     */
    public function reverseTransform($value)
    {
        $sites = array();

        foreach ($value as $site) {
            $sites[] = array('siteId' => $site->getSiteId());
        }

        return $sites;
    }
}


<?php

namespace Bridge\HttpApi\Serializer;

use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

class PathDenormalizer implements DenormalizerInterface, SerializerAwareInterface
{
    /**
     * @var string
     */
    private $path;

    /**
     * @var SerializerInterface|DenormalizerInterface
     */
    private $serializer;

    /**
     * @var PropertyAccessor
     */
    private $accessor;

    /**
     * @param string $path Property path
     */
    public function __construct($path)
    {
        $this->path = $path;

        $this->accessor = PropertyAccess::createPropertyAccessor();
    }

    /**
     * {@inheritdoc}
     */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
        return $this->serializer->denormalize($this->accessor->getValue($data, $this->path), $class, $format, $context);
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null)
    {
        return
            $this->accessor->isReadable($data, $this->path) &&
            $this->accessor->getValue($data, $this->path) !== null;
    }

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        if (!$serializer instanceof DenormalizerInterface) {
            throw new InvalidArgumentException('Expected a serializer that also implements DenormalizerInterface.');
        }

        $this->serializer = $serializer;
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus\Team;

use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Data\Bonus as DBonus;
use Praxigento\Downline\Repo\Data\Customer as ECustomer;

/**
 * Calculate Team bonus according to DEFAULT scheme.
 */
class CalcDef
{
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Level */
    private $daoLevel;
    /** @var \Praxigento\Core\Api\Helper\Format */
    private $hlpFormat;
    /** @var  \Praxigento\BonusHybrid\Api\Helper\Scheme */
    private $hlpScheme;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpTree;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Downline\Repo\Dao\Customer $daoDwnl,
        \Praxigento\BonusBase\Repo\Dao\Level $daoLevel,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\Core\Api\Helper\Format $hlpFormat,
        \Praxigento\Downline\Api\Helper\Tree $hlpTree,
        \Praxigento\BonusHybrid\Api\Helper\Scheme $hlpScheme
    )
    {
        $this->logger = $logger;
        $this->daoDwnl = $daoDwnl;
        $this->daoLevel = $daoLevel;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->hlpFormat = $hlpFormat;
        $this->hlpTree = $hlpTree;
        $this->hlpScheme = $hlpScheme;
    }

    /**
     * Walk trough the compressed downline & calculate team bonus for DEFAULT scheme.
     *
     * @param int $calcId ID of the compression calculation to get downline.
     * @return Data[]
     * @throws \Exception
     */
    public function exec($calcId)
    {
        $result = [];
        /* collect additional data */
        $levelsPersonal = $this->daoLevel->getByCalcTypeCode(Cfg::CODE_TYPE_CALC_BONUS_PERSONAL);
        $levelsTeam = $this->daoLevel->getByCalcTypeCode(Cfg::CODE_TYPE_CALC_BONUS_TEAM_DEF);
        $dwnlCompress = $this->daoBonDwnl->getByCalcId($calcId);
        $dwnlCurrent = $this->daoDwnl->get();
        $pctPbMax = $this->getMaxPercentForPersonalBonus($levelsPersonal);
        $courtesyPct = \Praxigento\BonusHybrid\Config::COURTESY_BONUS_PERCENT;
        /* create maps to access data */
        $mapDwnlById = $this->hlpTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF);
        $mapTeams = $this->hlpTree->mapByTeams($dwnlCompress, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF);
        $mapCustById = $this->hlpTree->mapById($dwnlCurrent, ECustomer::A_CUSTOMER_REF);
        /**
         * Go through all customers from compressed tree and calculate bonus.
         *
         * @var int $custId
         * @var EBonDwnl $custDwnl
         */
        foreach ($mapDwnlById as $custId => $custDwnl) {
            /** @var ECustomer $custData */
            $custData = $mapCustById[$custId];
            $custMlmId = $custData->getMlmId();
            $scheme = $this->hlpScheme->getSchemeByCustomer($custData);
            /* only DEFAULT-schema customers may apply to Team Bonus */
            $pv = $custDwnl->getPv();
            /* customer has PV to calculate bonus */
            if ($pv > Cfg::DEF_ZERO) {
                /* personal % for this customer */
                $pctPb = $this->getLevelPercent($pv, $levelsPersonal);
                /* check courtesy bonus (if %PB=MAX, 5% to the first parent) */
                if (abs($pctPbMax - $pctPb) < Cfg::DEF_ZERO) {
                    /* there is no team bonus */
                    continue;
                }
                /* traverse up to tree root to calculate team bonus values */
                $path = $custDwnl->getPath();
                $parents = $this->hlpTree->getParentsFromPathReversed($path);
                /* init undistributed delta: 20% - 5% */
                $pctPbLeft = $pctPbMax - $pctPb;
                /* ... and distributed amount: 5% */
                $pctPbDone = $pctPb;
                $this->logger->debug("TB: Customer #$custId(ref. #$custMlmId) has $pv PV and %PB=$pctPb, "
                    . "%left=$pctPbLeft, %done=$pctPbDone");
                /* set "isFather" flag for courtesy bonus */
                $isFather = true;
                foreach ($parents as $parentId) {
                    /* current customer has not MAX PB% or there is undistributed delta yet */
                    if ($pctPbLeft > Cfg::DEF_ZERO) {
                        /* get team qualification percent for parent */
                        /** @var EBonDwnl $parentDwnl */
                        $parentDwnl = $mapDwnlById[$parentId];
                        /** @var ECustomer $parentData */
                        $parentData = $mapCustById[$parentId];
                        $parentMlmId = $parentData->getMlmId();
                        $parentScheme = $this->hlpScheme->getSchemeByCustomer($parentData);
                        $tv = $parentDwnl->getTv();
                        $tvForced = $this->hlpScheme->getForcedTv($parentId, $scheme, $tv);
                        if ($tvForced > $tv) {
                            $this->logger->debug("TB: Customer #$parentId (ref. #$parentMlmId ) has forced qualification with TV=$tvForced.");
                            $tv = $tvForced;
                        }
                        /* get TB% for current parent and calc available % for current parent */
                        $pctTb = $this->getLevelPercent($tv, $levelsTeam);
                        $pctTbAvlbDelta = $pctTb - $pctPbDone;
                        if ($pctTbAvlbDelta > Cfg::DEF_ZERO) {
                            /* parent's TV % should be more then customer's PV % */

                            /* EU parent should not get more then courtesy % */
                            if ($parentScheme != Cfg::SCHEMA_DEFAULT) {
                                if ($isFather) {
                                    /* Courtesy bonus will calculate in other process, just decrease % left */
                                    $pctPbLeft = $this->hlpFormat->toNumber($pctPbLeft - $courtesyPct);
                                    $pctPbDone = $this->hlpFormat->toNumber($pctPbDone + $courtesyPct);
                                    $this->logger->debug("TB: Customer #$parentId (ref. #$parentMlmId) has "
                                        . "scheme=$parentScheme and is 'father' for #$custId ($custMlmId). "
                                        . "Decrease %TB on %courtesy=$courtesyPct to %left=$pctPbLeft, %done=$pctPbDone.");
                                }
                            }

                            if (
                                ($pctTbAvlbDelta > $pctPbLeft) ||
                                abs($pctTbAvlbDelta - $pctPbLeft) < Cfg::DEF_ZERO // this is ">="
                            ) {
                                /* there is undistributed PB% */
                                /* parent's TV allows him to get all team bonus from this customer */
                                if ($parentScheme == Cfg::SCHEMA_DEFAULT) {
                                    $bonus = $this->hlpFormat->roundBonus($pv * $pctPbLeft);
                                    $entry = new DBonus();
                                    $entry->setCustomerRef($parentId);
                                    $entry->setDonatorRef($custId);
                                    $entry->setValue($bonus);
                                    $result[] = $entry;
                                    $this->logger->debug("TB: Customer #$parentId ($parentMlmId) has TV=$tv, %TB=$pctTb,"
                                        . " and get '$bonus' ($pctPbLeft%) as DEFAULT Team Bonus from "
                                        . "downline customer #$custId ($custMlmId) with PV=$pv and "
                                        . "%PB=$pctPb");
                                } else {
                                    $this->logger->debug("TB: Customer #$parentId ($parentMlmId) has TV=$tv, %TB=$pctTb,"
                                        . " but cannot get DEFAULT Team Bonus from "
                                        . "downline customer #$custId ($custMlmId) with PV=$pv and "
                                        . "%PB=$pctPb because he is not from DEFAULT scheme.");
                                }
                                $pctPbLeft = $this->hlpFormat->toNumber($pctPbLeft - $pctTbAvlbDelta);
                                $pctPbDone = $this->hlpFormat->toNumber($pctPbDone + $pctTbAvlbDelta);
                                $this->logger->debug("TB: All bonus is distributed (%left=$pctPbLeft, %done=$pctPbDone).");
                                break;
                            } else {
                                /* parent's TV allows him to get only part of the team bonus from this customer */
                                if ($parentScheme == Cfg::SCHEMA_DEFAULT) {
                                    $bonus = $this->hlpFormat->roundBonus($pv * $pctTbAvlbDelta);
                                    $entry = new DBonus();
                                    $entry->setCustomerRef($parentId);
                                    $entry->setDonatorRef($custId);
                                    $entry->setValue($bonus);
                                    $result[] = $entry;
                                    $pctPbLeft = $this->hlpFormat->toNumber($pctPbLeft - $pctTbAvlbDelta);
                                    $pctPbDone = $this->hlpFormat->toNumber($pctPbDone + $pctTbAvlbDelta);
                                    $this->logger->debug("TB: Customer #$parentId ($parentMlmId) has TV=$tv, %TB=$pctTb,"
                                        . " and get '$bonus' ($pctTbAvlbDelta%) as DEFAULT Team Bonus from "
                                        . "downline customer #$custId ($custMlmId) with PV=$pv and "
                                        . "%PB=$pctPb, %left=$pctPbLeft%, %done=$pctPbDone.");
                                } else {
                                    $pctPbLeft = $this->hlpFormat->toNumber($pctPbLeft - $pctTbAvlbDelta);
                                    $pctPbDone = $this->hlpFormat->toNumber($pctPbDone + $pctTbAvlbDelta);
                                    $this->logger->debug("TB: Customer #$parentId ($parentMlmId) has TV=$tv, %TB=$pctTb,"
                                        . " but cannot get DEFAULT Team Bonus from "
                                        . "downline customer #$custId ($custMlmId) with PV=$pv and "
                                        . "%PB=$pctPb because he is not from DEFAULT scheme."
                                        . " Available: %left=$pctPbLeft%, %done=$pctPbDone.");
                                }

                            }
                        } else {
                            /* this parent has %TB less then distributed %PB and should not be granted  */
                            $this->logger->debug("TB: Customer #$parentId (ref. #$parentMlmId) has TV=$tv, "
                                . "%TB=$pctTb is not more then %done=$pctPbDone and should not "
                                . "get Team Bonus from #$custId ($custMlmId).");
                            if ($isFather) {
                                /* reduce delta to courtesy bonus percent if parent is not "father" */
                                $pctPbLeft = $this->hlpFormat->toNumber($pctPbLeft - $courtesyPct);
                                $pctPbDone = $this->hlpFormat->toNumber($pctPbDone + $courtesyPct);
                                $this->logger->debug("Customer #$parentId ($parentMlmId) is 'father' for the "
                                    . "customer #$custId ($custMlmId) %left is decreased on "
                                    . "Courtesy Bonus percent (new value: $pctPbLeft, %done=$pctPbDone).");
                            }
                        }
                    } else {
                        /* this customer has max Personal Bonus percent, no Team Bonus is possible */
                        $this->logger->debug("TB: Customer #$custId (ref. #$custMlmId ) has maximal Personal Bonus %.");
                        break;
                    }
                    /* next parent is not father */
                    $isFather = false;
                }
            } else {
                $this->logger->debug("TB: Customer #$custId (ref. #$custMlmId ) has no PV ($pv PV) and could not participate in DEFAULT Team Bonus.");
            }
        }
        unset($mapCustById);
        unset($mapTeams);
        unset($mapDwnlById);
        return $result;
    }

    /**
     * Get percent for the first level that is greater then given $value.
     *
     * @param int $value PV/TV/... value to get level's percent
     * @param array $levels asc ordered array with levels & percents ([$level => $percent])
     *
     * @return number
     */
    private function getLevelPercent($value, $levels)
    {
        $result = 0;
        foreach ($levels as $level => $percent) {
            if ($value < $level) {
                break;
            }
            $result = $percent;
        }
        return $result;
    }

    /**
     * Look up for the level with the max bonus percent.
     *
     * @param array $levels set of the levels with percents ([$level => $percent])
     * @return int
     */
    private function getMaxPercentForPersonalBonus($levels)
    {
        $result = 0;
        foreach ($levels as $percent) {
            if ($percent > $result) {
                $result = $percent;
            }
        }
        return $result;
    }
}


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli\Question;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Cli Question.
 */
abstract class CliQuestion
{
    /**
     * The running command.
     *
     * @var In2pire\Cli\Command\CliCommand
     */
    protected $command = null;

    /**
     * The question helper.
     *
     * @var Symfony\Component\Console\Helper\QuestionHelper
     */
    protected $helper = null;

    /**
     * Constructor.
     *
     * @return In2pire\Cli\Command\CliCommand
     *   The running command.
     */
    public function __construct($command)
    {
        $this->command = $command;
    }

    /**
     * Get running command.
     *
     * @return In2pire\Cli\Command\CliCommand
     *   The running command.
     */
    public function getCommand()
    {
        return $this->command;
    }

    /**
     * Get question helper.
     *
     * @return Symfony\Component\Console\Helper\QuestionHelper
     *   Question helper.
     */
    public function getHelper()
    {
        if ($this->helper === null) {
            $this->helper = $this->command->getHelper('question');
        }

        return $this->helper;
    }

    /**
     * Ask.
     *
     * @param InputInterface $input
     *   Data input.
     * @param OutputInterface $output
     *   Data output.
     *
     * @return boolean
     *   True if passes the question. Otherwise false.
     */
    abstract public function ask(InputInterface $input, OutputInterface $output);
}


<?php
namespace eMacros\Runtime\Filter;

use eMacros\Runtime\GenericFunction;

class FilterHasVar extends GenericFunction {
	/**
	 * Filter types
	 * @var array
	 */
	public static $filter_types = [INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV, INPUT_SESSION];

	/**
	 * Checks whether a given index is defined on a global array
	 * Usage: (has-var POST 'message')
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException("FilterHasVar: No parameters found.");
		if (!isset($arguments[1])) throw new \BadFunctionCallException("FilterHasVar: No filter has been defined.");
		if (!in_array($arguments[0], self::$filter_types))
			throw new \InvalidArgumentException(sprintf("FilterHasVar: Filter type '%s' ", strval($arguments[0])));
		return filter_has_var(self::$filter_types[$arguments[0]], $arguments[1]);
	}
}
?>


<?php

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

namespace Chill\CustomFieldsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;

/**
 * This type create a Choice field with custom fields as choices.
 *
 * This type can only be associated with a customFieldsGroup type. The field
 * is populated when the data (a customFieldsGroup entity) is associated with
 * the form
 *
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 */
class LinkedCustomFieldsType extends AbstractType
{
    /**
     *
     * @var TranslatableStringHelper
     */
    private $translatableStringHelper;

    /**
     * The name for the choice field
     *
     * Extracted from builder::getName
     *
     * @var string
     */
    private $choiceName = 'choice';

    /**
     * the option of the form.
     *
     * @internal options are stored at the class level to be reused by appendChoice, after data are setted
     * @var array
     */
    private $options = array();

    public function __construct(TranslatableStringHelper $helper)
    {
        $this->translatableStringHelper = $helper;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->choiceName = $builder->getName();
        $this->options = $options;

        $builder->addEventListener(FormEvents::POST_SET_DATA,
                array($this, 'appendChoice'))
            ;
    }

    public function getParent()
    {
        return 'choice';
    }

    /**
     * append Choice on POST_SET_DATA event
     *
     * Choices are extracted from custom_field_group (the data associated
     * with the root form)
     *
     * @param FormEvent $event
     * @return void
     */
    public function appendChoice(FormEvent $event)
    {
        $rootForm = $this->getRootForm($event->getForm());
        $group = $rootForm->getData();

        if ($group === NULL) {
            return;
        }

        $choices = array();
        foreach($group->getCustomFields() as $customFields) {
            $choices[$customFields->getSlug()] =
                    $this->translatableStringHelper
                        ->localize($customFields->getName());
        }

        $options = array_merge($this->options, array(
                'choice_list' => new SimpleChoiceList($choices),
            ));

        $event->getForm()->getParent()->add($this->choiceName, 'choice',
                $options);
    }

    /**
     * Return the root form (i.e. produced from CustomFieldsGroupType::getForm)
     *
     * @param FormInterface $form
     * @return FormInterface
     */
    private function getRootForm(FormInterface $form)
    {
        if ($form->getParent() === NULL) {
            return $form;
        } else {
            return $this->getRootForm($form->getParent());
        }
    }

    public function getName()
    {
        return 'custom_fields_group_linked_custom_fields';
    }

}


<?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\Configuration\Option;

use Predis\Cluster\RedisStrategy;
use Predis\Configuration\OptionsInterface;
use Predis\Connection\Cluster\PredisCluster;
use Predis\Connection\Cluster\RedisCluster;

/**
 * Configures an aggregate connection used for clustering
 * multiple Redis nodes using various implementations with
 * different algorithms or strategies.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Cluster extends Aggregate
{
    /**
     * Returns a connection initializer from a descriptive name.
     *
     * @param OptionsInterface $options     Client options.
     * @param string           $description Identifier of a cluster backend (`predis`, `redis`)
     *
     * @return callable
     */
    protected function getConnectionInitializerByDescription(OptionsInterface $options, $description)
    {
        if ($description === 'predis') {
            $callback = $this->getDefault($options);
        } elseif ($description === 'redis') {
            $callback = function ($options) {
                return new RedisCluster($options->connections, new RedisStrategy($options->crc16));
            };
        } else {
            throw new \InvalidArgumentException(
                'String value for the cluster option must be either `predis` or `redis`'
            );
        }

        return $this->getConnectionInitializer($options, $callback);
    }

    /**
     * {@inheritdoc}
     */
    public function filter(OptionsInterface $options, $value)
    {
        if (is_string($value)) {
            return $this->getConnectionInitializerByDescription($options, $value);
        } else {
            return $this->getConnectionInitializer($options, $value);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefault(OptionsInterface $options)
    {
        return function ($options) {
            return new PredisCluster();
        };
    }
}


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

namespace Controller\Theme;

use RedKiteCms\Rendering\Controller\Theme\StartFromThemeController as BaseStartFromThemeController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to start a site from scratch
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Theme
 */
class StartFromThemeController extends BaseStartFromThemeController
{
    /**
     * Start a site from scratch action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function startAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "configuration_handler" => $app["red_kite_cms.configuration_handler"],
        );

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