<?php
declare(strict_types=1);

namespace icePHP;

/**
 * 调试类,用于控制调试信息的显示,通常不被直接使用1
 * 需要使用调试功能,请调用 debug方法
 */
final class Debug
{
    /**
     * 禁止实例化
     */
    private function __construct()
    {
    }

    // 程序开始执行时间
    private static $begin;

    // 程序结束时的消耗时间
    private static $persist;

    // 所有调试信息
    private static $msgs = [];

    /**
     * 重新计时,主要处理fragment的重入问题
     */
    static public function clear(): void
    {
        self::start();
    }

    /**
     * 记录开始时间
     */
    static public function start(): void
    {
        self::$begin = self::timeLog();
    }

    /**
     * 页面处理结束,在页面正文显示调试信息
     * @param $ret mixed 原来要处理的数据
     * @return string|array
     */
    static public function end($ret = null)
    {
        // 非调试状态,不处理
        if (!self::isDebug()) {
            return $ret;
        }

        //分别统计三种操作的总耗时
        $counts = $sums = ['sql' => 0, 'net' => 0, 'debug' => 0, 'cache' => 0];
        $others = [];

        $sqls = [['方法', '用时', '堆栈', 'SQL语句']];
        $caches = [['类型', '操作', '堆栈', '键', '值']];
        $nets = [['用时', '地址', '数据']];

        foreach (self::$msgs as $key => $msg) {
            if (!is_array($msg)) {
                continue;
            }

            $type = $msg['type'];

            $sums[$type] += floatval(isset($msg['time']) ? $msg['time'] : 0);
            $counts[$type]++;

            if ($type == 'sql') {
                $sqls[] = [$msg['method'], $msg['time'] . ' ms', $msg['trace'], $msg['sql']];
            } elseif ($type == 'cache') {
                $caches[] = [$msg['server'], $msg['method'], $msg['info'], $msg['key'], $msg['value']];
            } elseif ($type == 'net') {
                $nets[] = [$msg['time'] . ' ms', $msg['url'], $msg['return']];
            } elseif (!is_string($msg)) {
                $others[] = json($msg);
            }
        }

        // 如果有数据库访问调试信息并且要求记录
        if (self::isDebug('sql') and $counts['sql']) {
            $sqls[] = ['全部 ' . $counts['sql'], round($sums['sql'], 3) . ' ms', '', ''];
        }

        //如果有网络调试信息,并要求记录
        if (self::isDebug('net') and $counts['net']) {
            $nets[] = ['全部 ' . $counts['net'], round($sums['net'], 3) . ' ms', ''];
        }

        // 否则是按模板输出
        $debug = [
            'persist' => self::getPersist(),
            'msgs' => [$sqls, $caches, $nets],
            'others' => $others
        ];

        // Ajax模式
        if (isAjax() or isset($_REQUEST['callback']) or is_array($ret)) {
            $ret['debug'] = $debug;
            return $ret;
        }

        // 如果是命令行模式,直接输出显示
        if (isCliMode()) {
            foreach ($debug['msgs'] as $info) {
                echo "\r\n";
                foreach ($info as $row) {
                    echo "\r\n";
                    foreach ($row as $item) {
                        echo $item . "\t\t";
                    }
                }
            }
            echo 'Persist:' . $debug['persist'] . "\r\n\r\n";
            return dump($debug, 'DEBUG', true);
        }

        // 显示输出模块
        {
            $persist = $debug['persist'];
            $usage = kmgt(memory_get_peak_usage());
            $msgs = $debug['msgs'];
            require __DIR__ . '/template.php';
        }

        return '';
    }

    /**
     * 获取本次Web访问的持续时间
     * @return float ms
     */
    static public function getPersist(): float
    {
        self::$persist = self::timeLog(self::$begin);
        return self::$persist;
    }

    /**
     * 添加一条调试信息
     * @param array|string $msg 调试信息
     * @param string $type 调试信息类别:file,sql,net,other
     */
    static public function set($msg, string $type = 'other'): void
    {
        if (is_array($msg)) {
            $msg['type'] = $type;
        }
        self::$msgs[] = $msg;
    }

    /**
     * 获取调用规模中的开发 代码信息
     * @return array [类名,调用点信息]
     */
    static private function info()
    {
        //检查调用堆栈
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        $lastLine = 0;

        $line = null;
        foreach ($trace as $line) {
            if (!isset($line['class'])) {
                $line['class'] = '';
            }

            //找到最后一次调用,且不是 框架调用的
            if (substr($line['class'], 0, 6) != 'SFrame' and substr($line['class'], 0, 7) != 'icePHP\\') break;
            $lastLine = $line['line'] ?? 0;
        }
        $from = $line;

        $info = $from['class'] . (isset($from['type']) ? $from['type'] : '') . $from['function'] . '::' . $lastLine;
        return [$from['class'], $info];
    }

    /**
     * 记录一次数据库访问的调试信息
     *
     * @param string $method 执行方式:Query/Execute/QueryHandle/
     * @param string $prepare
     * @param  $time  float 花费的时间(毫秒)
     * @param $params array|string|null
     * @param $sql string
     */
    static public function setSql(string $method, string $prepare, float $time, $params = null, string $sql = ''): void
    {
        [$class, $info] = self::info();

        //不记录MLog里的SQL,这里都是日志
        if ($class == 'SLogTable' and $method != 'Connect') {
            return;
        }
        self::set([
            'method' => $method,
            'sql' => $sql,
            'time' => round($time, 2),
            'prepare' => $prepare,
            'params' => $params,
            'trace' => $info
        ], 'sql');
    }

    /**
     * 记录缓存相关的调试信息
     * @param string $type 缓存类型:mem/redis/file/...
     * @param string $method get/set/clear/...
     * @param string $key 键
     * @param string $value 值
     */
    static public function setCache(string $type, string $method, string $key, $value = ''): void
    {
        [, $info] = self::info();
        self::set([
            'server' => $type,
            'method' => $method,
            'key' => $key,
            'value' => mb_strlen($value) > 100 ? (mb_substr($value, 0, 100) . '...[' . mb_strlen($value) . ']') : $value,
            'info' => $info
        ], 'cache');
    }

    /**
     * 记录一次网络请求的调试信息
     * @param $url string 请求地址
     * @param $data mixed 请求参数
     * @param $return string 返回信息
     * @param $time float 用时(秒)
     */
    static public function setNet(string $url, $data, string $return, float $time): void
    {
        self::set([
            'url' => $url,
            'data' => $data,
            'return' => strlen($return) . ' bytes',
            'time' => $time
        ], 'net');
    }

    /**
     * 判断是否调试状态 ,可被临时关闭
     * 或者配置文件中指定了调试状态,或者当前请求中指定了调试状态,或者长效指定了调试状态
     * @param string $name
     * @return boolean
     */
    static public function isDebug(string $name = ''): bool
    {
        // 记录临时禁止标识
        static $closed = false;

        // 如果已经关闭了调试
        if ($closed) {
            return false;
        }

        // 如果是要求临时关闭调试
        if ($name == 'close debug') {
            $closed = true;
            return false;
        }

        // 如果请求参数中要求关闭调试
        if (isset($_REQUEST['debug']) and !$name and in_array($_REQUEST['debug'], ['close', 'off', '0', 'disabled', 'no'])) {
            return false;
        }

        // 如果配置文件中指明了调试,或者直接链接中有DEBUG,则是调试模式
        if (Config::isDebug()) {
            return true;
        }

        // 请求参数中指定了调试状态
        if (isset($_REQUEST['debug']) and (!$name or $_REQUEST['debug'] == $name)) {
            return true;
        }

        // 如果COOKIE调试指定了长效调试状态
        $key = configDefault(false, 'system', 'cookieDebug');
        if (isset($_COOKIE[$key]) and (!$name or $_COOKIE[$key] == $name)) {
            return true;
        }

        return false;
    }

    /**
     * 时间记录及计算
     * SFrame中有同名方法,为减少依赖,此处重复实现
     * @param $begin float 开始时间
     * @return float 开始时间(如果未指明开始时间)/时间间隔(如果指明时间间隔)
     */
    static private function timeLog(float $begin = null): float
    {
        // 不带参数则返回当前时间
        if (!$begin) {
            return microtime(true);
        }

        // 带参数(开始时间),则返回当前时间与开始时间的差
        return round(microtime(true) - $begin, 6);
    }

    //清除调试信息
    public static function clearMsgs(): void
    {
        self::$msgs = [];
    }
}


<?php
/**
 * Phergie plugin for returning randomly generated numbers in response to dice rolling requests
 *
 * @link https://github.com/chrismou/phergie-irc-plugin-react-dice for the canonical source repository
 * @copyright Copyright (c) 2016 Chris Chrisostomou (https://mou.me)
 * @license http://phergie.org/license New BSD License
 * @package Chrismou\Phergie\Plugin\Dice
 */

namespace Chrismou\Phergie\Plugin\Dice;

use Phergie\Irc\Bot\React\AbstractPlugin;
use Phergie\Irc\Bot\React\EventQueueInterface as Queue;
use Phergie\Irc\Plugin\React\Command\CommandEvent as Event;

/**
 * Plugin class
 *
 * @category Chrismou
 * @package Chrismou\Phergie\Plugin\Dice
 */
class Plugin extends AbstractPlugin
{
    /**
     * @var int
     */
    protected $defaultDieSides = 6;

    /**
     * @var int
     */
    protected $maxDieSides = 1000;

    /**
     * @var int
     */
    protected $maxDieRolls = 50;

    /**
     * @var bool
     */
    protected $showSums = true;

    /**
     * Accepts plugin configuration
     *
     * @param array $config
     */
    public function __construct(array $config = array())
    {
        if (isset($config['defaultSides']) && is_numeric($config['defaultSides'])) {
            $this->defaultDieSides = (int) $config['defaultSides'];
        }

        if (isset($config['maxSides']) && is_numeric($config['maxSides'])) {
            $this->maxDieSides = (int) $config['maxSides'];
        }

        if (isset($config['maxRolls']) && is_numeric($config['maxRolls'])) {
            $this->maxDieRolls = (int) $config['maxRolls'];
        }

        if (isset($config['showSums'])) {
            $this->showSums = (bool) $config['showSums'];
        }
    }

    /**
     * IRC events to watch
     *
     * @return array
     */
    public function getSubscribedEvents()
    {
        return array(
            'command.dice' => 'handleCommand',
            'command.dice.help' => 'handleCommandHelp',
        );
    }

    /**
     * Handle the dice roll command
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
     */
    public function handleCommand(Event $event, Queue $queue)
    {
        if ($this->validateParams($event)) {
            $params = $event->getCustomParams();
            $results = array();
            $total = 0;
            $count = $params[0];
            $sides = (isset($params[1])) ? $params[1] : $this->defaultDieSides;

            for ($roll = 1; $roll <= $count; $roll++) {
                $rollResult = $this->doRoll($sides);
                $results[] = $rollResult;
                $total += $rollResult;
            }
            $response = $this->generateResponse($event, $total, $results);
            $this->sendIrcResponseLine($event, $queue, $response);
        } else {
            $this->handleCommandHelp($event, $queue);
        }
    }

    /**
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param integer $total
     * @param array $results
     * @return string
     */
    public function generateResponse(Event $event, $total, array $results)
    {
        return sprintf(
            "%s: You rolled %d %s",
            $event->getNick(),
            $total,
            ($this->showSums && count($results) > 1) ? sprintf('(%s)', implode('+', $results)) : ''
        );
    }

    /**
     * Perform a single dice roll
     *
     * @param integer $sides
     * @return int
     */
    protected function doRoll($sides)
    {
        return mt_rand(1, (int)$sides);
    }

    /**
     * Check the supplied parameters are valid
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return boolean
     */
    protected function validateParams(Event $event)
    {
        return (
            $this->genericParamValidation($event) &&
            $this->firstParamValidation($event) &&
            $this->secondParamValidation($event)
        );
    }

    /**
     * Verify the combination of parameters are valid
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return boolean
     */
    private function genericParamValidation(Event $event)
    {
        $params = $event->getCustomParams();
        return (count($params) >= 1 && count($params) <= 2);
    }

    /**
     * Verify parameter 1 is valid
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @return boolean
     */
    private function firstParamValidation(Event $event)
    {
        $params = $event->getCustomParams();
        return (is_numeric($params[0]) && $params[0] > 0 && $params[0] <= $this->maxDieRolls);
    }

    /**
     * Verify parameter 2 is valid
     *
     * @param Event $event
     * @return bool
     */
    private function secondParamValidation(Event $event)
    {
        $params = $event->getCustomParams();
        return (!isset($params[1]) || (is_numeric($params[1]) && $params[1] >= 1 && $params[1] <= $this->maxDieSides));
    }

    /**
     * Handle the help command
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
     */
    public function handleCommandHelp(Event $event, Queue $queue)
    {
        $this->sendIrcResponse($event, $queue, $this->getHelpLines());
    }

    /**
     * Return an array of help command response lines
     *
     * @return array
     */
    public function getHelpLines()
    {
        return array(
            'Usage: dice [number of dice] [number of sides]',
            '[number of die] - how many dice to roll (maximum ' . $this->maxDieRolls . ')',
            sprintf(
                '[number of sides] (optional) the number of sides on each die (maximum %s - defaults to %s)',
                $this->maxDieSides,
                $this->defaultDieSides
            ),
            'Returns randomly generated numbers in response to dice rolling requests'
        );
    }

    /**
     * Send an array of response lines back to IRC
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
     * @param array $ircResponse
     */
    protected function sendIrcResponse(Event $event, Queue $queue, array $ircResponse)
    {
        foreach ($ircResponse as $ircResponseLine) {
            $this->sendIrcResponseLine($event, $queue, $ircResponseLine);
        }
    }

    /**
     * Send a single response line back to IRC
     *
     * @param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
     * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
     * @param string $ircResponseLine
     */
    protected function sendIrcResponseLine(Event $event, Queue $queue, $ircResponseLine)
    {
        $queue->ircPrivmsg($event->getSource(), $ircResponseLine);
    }
}


<?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.
 */

/**
 * OpenPlatformServiceProvider.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>
 * @author    lixiao <leonlx126@gmail.com>
 * @copyright 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\Encryption\Encryptor;
use EasyWeChat\Foundation\Application;
use EasyWeChat\OpenPlatform\AccessToken;
use EasyWeChat\OpenPlatform\Api\BaseApi;
use EasyWeChat\OpenPlatform\Api\PreAuthorization;
use EasyWeChat\OpenPlatform\Authorizer;
use EasyWeChat\OpenPlatform\AuthorizerAccessToken;
use EasyWeChat\OpenPlatform\EventHandlers;
use EasyWeChat\OpenPlatform\Guard;
use EasyWeChat\OpenPlatform\OpenPlatform;
use EasyWeChat\OpenPlatform\VerifyTicket;
use Overtrue\Socialite\SocialiteManager as Socialite;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

class OpenPlatformServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['open_platform.verify_ticket'] = function ($pimple) {
            return new VerifyTicket(
                $pimple['config']['open_platform']['app_id'],
                $pimple['cache']
            );
        };

        $pimple['open_platform.access_token'] = function ($pimple) {
            $accessToken = new AccessToken(
                $pimple['config']['open_platform']['app_id'],
                $pimple['config']['open_platform']['secret'],
                $pimple['cache']
            );
            $accessToken->setVerifyTicket($pimple['open_platform.verify_ticket']);

            return $accessToken;
        };

        $pimple['open_platform.encryptor'] = function ($pimple) {
            return new Encryptor(
                $pimple['config']['open_platform']['app_id'],
                $pimple['config']['open_platform']['token'],
                $pimple['config']['open_platform']['aes_key']
            );
        };

        $pimple['open_platform'] = function ($pimple) {
            return new OpenPlatform($pimple);
        };

        $pimple['open_platform.server'] = function ($pimple) {
            $server = new Guard($pimple['config']['open_platform']['token']);
            $server->debug($pimple['config']['debug']);
            $server->setEncryptor($pimple['open_platform.encryptor']);
            $server->setHandlers([
                Guard::EVENT_AUTHORIZED => $pimple['open_platform.handlers.authorized'],
                Guard::EVENT_UNAUTHORIZED => $pimple['open_platform.handlers.unauthorized'],
                Guard::EVENT_UPDATE_AUTHORIZED => $pimple['open_platform.handlers.updateauthorized'],
                Guard::EVENT_COMPONENT_VERIFY_TICKET => $pimple['open_platform.handlers.component_verify_ticket'],
            ]);

            return $server;
        };

        $pimple['open_platform.pre_auth'] = $pimple['open_platform.pre_authorization'] = function ($pimple) {
            return new PreAuthorization(
                $pimple['open_platform.access_token'],
                $pimple['request']
            );
        };

        $pimple['open_platform.api'] = function ($pimple) {
            return new BaseApi(
                $pimple['open_platform.access_token'],
                $pimple['request']
            );
        };

        $pimple['open_platform.authorizer'] = function ($pimple) {
            return new Authorizer(
                $pimple['open_platform.api'],
                $pimple['config']['open_platform']['app_id'],
                $pimple['cache']
            );
        };

        $pimple['open_platform.authorizer_access_token'] = function ($pimple) {
            return new AuthorizerAccessToken(
                $pimple['config']['open_platform']['app_id'],
                $pimple['open_platform.authorizer']
            );
        };

        // Authorization events handlers.
        $pimple['open_platform.handlers.component_verify_ticket'] = function ($pimple) {
            return new EventHandlers\ComponentVerifyTicket($pimple['open_platform.verify_ticket']);
        };
        $pimple['open_platform.handlers.authorized'] = function () {
            return new EventHandlers\Authorized();
        };
        $pimple['open_platform.handlers.updateauthorized'] = function () {
            return new EventHandlers\UpdateAuthorized();
        };
        $pimple['open_platform.handlers.unauthorized'] = function () {
            return new EventHandlers\Unauthorized();
        };

        $pimple['open_platform.app'] = function ($pimple) {
            return new Application($pimple['config']->toArray());
        };

        // OAuth for OpenPlatform.
        $pimple['open_platform.oauth'] = function ($pimple) {
            $callback = $this->prepareCallbackUrl($pimple);
            $scopes = $pimple['config']->get('open_platform.oauth.scopes', []);
            $socialite = (new Socialite([
                'wechat_open' => [
                    'client_id' => $pimple['open_platform.authorizer']->getAppId(),
                    'client_secret' => $pimple['open_platform.access_token'],
                    'redirect' => $callback,
                ],
            ]))->driver('wechat_open');

            if (!empty($scopes)) {
                $socialite->scopes($scopes);
            }

            return $socialite;
        };
    }

    /**
     * Prepare the OAuth callback url for wechat.
     *
     * @param Container $pimple
     *
     * @return string
     */
    private function prepareCallbackUrl($pimple)
    {
        $callback = $pimple['config']->get('oauth.callback');
        if (0 === stripos($callback, 'http')) {
            return $callback;
        }
        $baseUrl = $pimple['request']->getSchemeAndHttpHost();

        return $baseUrl.'/'.ltrim($callback, '/');
    }
}


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

namespace cascade\components\dataInterface;

use cascade\models\DataInterface;
use canis\base\exceptions\Exception;

/**
 * Item [[@doctodo class_description:cascade\components\dataInterface\Item]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Item extends \canis\base\collector\Item
{
    /**
     * @var [[@doctodo var_type:error]] [[@doctodo var_description:error]]
     */
    public $error;

    /**
     * @var [[@doctodo var_type:_name]] [[@doctodo var_description:_name]]
     */
    private $_name;
    /**
     * @var [[@doctodo var_type:_module]] [[@doctodo var_description:_module]]
     */
    private $_module;
    /**
     * @var [[@doctodo var_type:_checked]] [[@doctodo var_description:_checked]]
     */
    private $_checked;
    /**
     * @var [[@doctodo var_type:_interfaceObject]] [[@doctodo var_description:_interfaceObject]]
     */
    protected $_interfaceObject;
    /**
     * @var [[@doctodo var_type:_currentInterfaceAction]] [[@doctodo var_description:_currentInterfaceAction]]
     */
    protected $_currentInterfaceAction;

    /**
     * [[@doctodo method_description:run]].
     *
     * @param [[@doctodo param_type:resumeLog]] $resumeLog [[@doctodo param_description:resumeLog]] [optional]
     * @param [[@doctodo param_type:action]]    $action    [[@doctodo param_description:action]] [optional]
     *
     * @return [[@doctodo return_type:run]] [[@doctodo return_description:run]]
     */
    public function run($resumeLog = null, $action = null)
    {
        register_shutdown_function([$this, 'saveLog']);
        if ($action === null) {
            $action = new NonInteractiveAction();
        }

        $action->interface = $this;
        if (!empty($resumeLog)) {
            $action->resumeLog($resumeLog);
        }

        $this->_currentInterfaceAction = $action;
        if (!$this->_currentInterfaceAction->start()) {
            $this->error = 'Could not start interface action!';

            return false;
        }
        try {
            $this->object->run($this->_currentInterfaceAction);
        } catch (Exception $e) {
            $this->_currentInterfaceAction->status->addError('Exception raised: ' . $e->getMessage());
            $this->_currentInterfaceAction->end(true);
            $this->error = 'Exception raised while running action (' . $e->getMessage() . ').';

            return false;
        }
        $this->_currentInterfaceAction->end();

        return !$this->_currentInterfaceAction->status->hasError;
    }

    /**
     * [[@doctodo method_description:saveLog]].
     *
     * @return [[@doctodo return_type:saveLog]] [[@doctodo return_description:saveLog]]
     */
    public function saveLog()
    {
        if (isset($this->_currentInterfaceAction)) {
            $this->_currentInterfaceAction->end(true);
        }

        return true;
    }

    /**
     * Get interface object.
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     * @return [[@doctodo return_type:getInterfaceObject]] [[@doctodo return_description:getInterfaceObject]]
     *
     */
    public function getInterfaceObject()
    {
        if (is_null($this->_interfaceObject)) {
            $this->_interfaceObject = DataInterface::find()->where(['system_id' => $this->object->systemId])->one();
            if (empty($this->_interfaceObject)) {
                $this->_interfaceObject = new DataInterface();
                $this->_interfaceObject->name = $this->object->name;
                $this->_interfaceObject->system_id = $this->object->systemId;
                if (!$this->_interfaceObject->save()) {
                    var_dump($this->_interfaceObject->errors);
                    throw new Exception("Unable to save interface object!");
                }
            }
        }

        return $this->_interfaceObject;
    }
}


<?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.
 */

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

namespace EasyWeChat\Staff;

use EasyWeChat\Message\AbstractMessage;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;

/**
 * Class Transformer.
 */
class Transformer
{
    /**
     * transform message to XML.
     *
     * @param array|string|AbstractMessage $message
     *
     * @return array
     */
    public function transform($message)
    {
        if (is_array($message)) {
            $class = News::class;
        } else {
            if (is_string($message)) {
                $message = new Text(['content' => $message]);
            }

            $class = get_class($message);
        }

        $handle = 'transform'.substr($class, strlen('EasyWeChat\Message\\'));

        return method_exists($this, $handle) ? $this->$handle($message) : [];
    }

    /**
     * Transform text message.
     *
     * @return array
     */
    public function transformText(AbstractMessage $message)
    {
        return [
                'msgtype' => 'text',
                'text' => [
                           'content' => $message->get('content'),
                          ],
               ];
    }

    /**
     * Transform image message.
     *
     * @return array
     */
    public function transformImage(AbstractMessage $message)
    {
        return [
                'msgtype' => 'image',
                'image' => [
                            'media_id' => $message->get('media_id'),
                           ],
               ];
    }

    /**
     * Transform music message.
     *
     * @return array
     */
    public function transformMusic(AbstractMessage $message)
    {
        return [
                'msgtype' => 'music',
                'music' => [
                            'title' => $message->get('title'),
                            'description' => $message->get('description'),
                            'musicurl' => $message->get('url'),
                            'hqmusicurl' => $message->get('hq_url'),
                            'thumb_media_id' => $message->get('thumb_media_id'),
                           ],
               ];
    }

    /**
     * Transform video message.
     *
     * @return array
     */
    public function transformVideo(AbstractMessage $message)
    {
        return [
                'msgtype' => 'video',
                'video' => [
                            'title' => $message->get('title'),
                            'media_id' => $message->get('media_id'),
                            'description' => $message->get('description'),
                            'thumb_media_id' => $message->get('thumb_media_id'),
                           ],
               ];
    }

    /**
     * Transform voice message.
     *
     * @return array
     */
    public function transformVoice(AbstractMessage $message)
    {
        return [
                'msgtype' => 'voice',
                'voice' => [
                            'media_id' => $message->get('media_id'),
                           ],
               ];
    }

    /**
     * Transform articles message.
     *
     * @return array
     */
    public function transformNews($news)
    {
        $articles = [];

        if (!is_array($news)) {
            $news = [$news];
        }

        foreach ($news as $item) {
            $articles[] = [
                           'title' => $item->get('title'),
                           'description' => $item->get('description'),
                           'url' => $item->get('url'),
                           'picurl' => $item->get('pic_url'),
                          ];
        }

        return ['msgtype' => 'news', 'news' => ['articles' => $articles]];
    }

    /**
     * Transform material message.
     *
     * @return array
     */
    public function transformMaterial(AbstractMessage $message)
    {
        $type = $message->getType();

        return [
                'msgtype' => $type,
                $type => [
                            'media_id' => $message->get('media_id'),
                           ],
               ];
    }

    /**
     * Transform wxcard message.
     *
     * @return array
     */
    public function transformCard(AbstractMessage $message)
    {
        $type = $message->getType();

        return [
                'msgtype' => $type,
                $type => [
                            'card_id' => $message->get('card_id'),
                            ],
               ];
    }
}


<?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.
 */

/**
 * Stats.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\MiniProgram\Stats;

use EasyWeChat\MiniProgram\Core\AbstractMiniProgram;

class Stats extends AbstractMiniProgram
{
    const SUMMARY_TREND = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend';
    const DAILY_VISIT_TREND = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend';
    const WEEKLY_VISIT_TREND = 'https://api.weixin.qq.com/datacube/getweanalysisappidweeklyvisittrend';
    const MONTHLY_VISIT_TREND = 'https://api.weixin.qq.com/datacube/getweanalysisappidmonthlyvisittrend';
    const VISIT_DISTRIBUTION = 'https://api.weixin.qq.com/datacube/getweanalysisappidvisitdistribution';
    const DAILY_RETAIN_INFO = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo';
    const WEEKLY_RETAIN_INFO = 'https://api.weixin.qq.com/datacube/getweanalysisappidweeklyretaininfo';
    const MONTHLY_RETAIN_INFO = 'https://api.weixin.qq.com/datacube/getweanalysisappidmonthlyretaininfo';
    const VISIT_PAGE = 'https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage';
    const USER_PORTRAIT = 'https://api.weixin.qq.com/datacube/getweanalysisappiduserportrait';

    /**
     * Get summary trend.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function summaryTrend($from, $to)
    {
        return $this->query(self::SUMMARY_TREND, $from, $to);
    }

    /**
     * Get daily visit trend.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function dailyVisitTrend($from, $to)
    {
        return $this->query(self::DAILY_VISIT_TREND, $from, $to);
    }

    /**
     * Get weekly visit trend.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function weeklyVisitTrend($from, $to)
    {
        return $this->query(self::WEEKLY_VISIT_TREND, $from, $to);
    }

    /**
     * Get monthly visit trend.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function monthlyVisitTrend($from, $to)
    {
        return $this->query(self::MONTHLY_VISIT_TREND, $from, $to);
    }

    /**
     * Get visit distribution.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function visitDistribution($from, $to)
    {
        return $this->query(self::VISIT_DISTRIBUTION, $from, $to);
    }

    /**
     * Get daily retain info.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function dailyRetainInfo($from, $to)
    {
        return $this->query(self::DAILY_RETAIN_INFO, $from, $to);
    }

    /**
     * Get weekly retain info.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function weeklyRetainInfo($from, $to)
    {
        return $this->query(self::WEEKLY_RETAIN_INFO, $from, $to);
    }

    /**
     * Get monthly retain info.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function montylyRetainInfo($from, $to)
    {
        return $this->query(self::MONTHLY_RETAIN_INFO, $from, $to);
    }

    /**
     * Get visit page.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function visitPage($from, $to)
    {
        return $this->query(self::VISIT_PAGE, $from, $to);
    }

    /**
     * Get user portrait.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function userPortrait($from, $to)
    {
        return $this->query(self::USER_PORTRAIT, $from, $to);
    }

    /**
     * Unify query.
     *
     * @param string $from
     * @param string $to
     *
     * @return \EasyWeChat\Support\Collection
     */
    protected function query($api, $from, $to)
    {
        $params = [
            'begin_date' => $from,
            'end_date' => $to,
        ];

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


<?php

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

use \Venus\core\Config as Config;

/**
 * This class manage the vendor class
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 2.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	2.0.0
 */
class Vendor
{
    /**
     * cache of the vendor available
     *
     * @access private
     * @var    array
     */
    private static $_aCache = null;

	/**
	 * constructor - factory
	 * To call a specific vendor, you have to call this class like this :
	 * new \Venus\lib\Vendor('Apollina\Template');
	 * new \Venus\lib\Vendor('Attila\Orm');
	 * new \Venus\lib\Vendor('Mobile_Detect');
	 *
	 * @access public
	 * @param  string $sVendorName
	 * @param  mixed $mParam
	 * @param  mixed $mParam2
	 * @return bool|object
	 */

	public static function getVendor(string $sVendorName, $mParam = null, $mParam2 = null)
	{
	    if ($sVendorName === 'Apollina\Template') {

	        $oApollina = new $sVendorName($mParam, str_replace('kernel'.DIRECTORY_SEPARATOR.'lib', 'bundles', __DIR__),
	            str_replace('kernel'.DIRECTORY_SEPARATOR.'lib', CACHE_DIR, __DIR__), $mParam2);

	        return $oApollina->addFunctionPath(__DIR__ . DIRECTORY_SEPARATOR, '\Venus\lib\Functions\\');
	    }
	    else if ($sVendorName === 'Attila\Orm') {

	        $oDbConfig = Config::get('database')->configuration;

	        return new $sVendorName($oDbConfig->db, $oDbConfig->type, $oDbConfig->host, $oDbConfig->user, $oDbConfig->password,
	            $oDbConfig->db);
	    }
	    else if (isset($mParam) && isset($mParam2)) {

	        return new $sVendorName($mParam, $mParam2);
	    }
	    else if (isset($mParam)) {

	        return new $sVendorName($mParam);
	    }
	    else {

	        return new $sVendorName;
	    }
	}
}


<?php

namespace Havvg\Component\Lock;

use Havvg\Component\Lock\Acquirer\AcquirerInterface;
use Havvg\Component\Lock\Exception\ResourceLockedException;
use Havvg\Component\Lock\Lock\ExpiringLockInterface;
use Havvg\Component\Lock\Lock\LockInterface;
use Havvg\Component\Lock\Repository\RepositoryInterface;
use Havvg\Component\Lock\Resource\ResourceInterface;

/**
 * The LockManager is a convenient way to interact with the Lock component.
 */
class LockManager
{
    protected $repository;

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

    /**
     * Check whether the given Acquirer may access the Resource in question.
     *
     * @param AcquirerInterface $acquirer
     * @param ResourceInterface $resource
     *
     * @return bool
     */
    public function isAccessible(AcquirerInterface $acquirer, ResourceInterface $resource)
    {
        if (!$resource->isLocked()) {
            return true;
        }

        $lock = $resource->getLock();
        if ($lock instanceof ExpiringLockInterface and $this->isLockExpired($lock)) {
            $this->release($lock);

            return true;
        }

        return $lock->getAcquirer()->getIdentifier() === $acquirer->getIdentifier();
    }

    /**
     * Check whether the given Lock is expired and should be ignored.
     *
     * @param ExpiringLockInterface $lock
     *
     * @return bool
     */
    public function isLockExpired(ExpiringLockInterface $lock)
    {
        $now = new \DateTime();

        return ($now > $lock->getExpiresAt());
    }

    /**
     * Try to acquire a Lock on the given Resource.
     *
     * @param AcquirerInterface $acquirer
     * @param ResourceInterface $resource
     *
     * @return LockInterface
     *
     * @throws ResourceLockedException
     */
    public function acquire(AcquirerInterface $acquirer, ResourceInterface $resource)
    {
        if (!$this->isAccessible($acquirer, $resource)) {
            throw new ResourceLockedException(sprintf('The resource is not accessible. It is locked by "%s".', $resource->getLock()->getAcquirer()->getIdentifier()));
        }

        return $this->repository->acquire($acquirer, $resource);
    }

    /**
     * Release the given Lock freeing its Resource to be accessed.
     *
     * @param LockInterface $lock
     *
     * @return bool
     */
    public function release(LockInterface $lock)
    {
        return $this->repository->release($lock);
    }
}


<?php

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

namespace In2pire\Cli;

abstract class BaseCliApplication implements CliApplicationInterface
{
    /**
     * Settings.
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Is Application booted?
     *
     * @var boolean
     */
    protected $booted = false;

    /**
     * Get configuration from settings.yml file.
     *
     * @param string $name
     *   Settings name.
     * @param mixed $default
     *   (optional) Default value when setting is not in file.
     *
     * @return mixed
     *   Configuration value.
     */
    public function getConfig($name, $default = null)
    {
        return array_key_exists($name, $this->settings) ? $this->settings[$name] : $default;
    }

    /**
     * Boot Application.
     *
     * @return In2pire\Cli\ApplicationInterface
     *   The called object.
     */
    public function boot()
    {
        if ($this->booted) {
            return $this;
        }

        // If we have pinba, disable it.
        if (extension_loaded('pinba')) {
            ini_set('pinba.enabled', false);
        }

        // If we have newrelic, disable it.
        if (extension_loaded('newrelic')) {
            ini_set('newrelic.enabled', false);
        }

        // Set timezone.
        if (!empty($this->settings['timezone'])) {
            date_default_timezone_set($this->settings['timezone']);
        }

        $this->booted = true;

        return $this;
    }

    /**
     * Run application.
     *
     * @return In2pire\Cli\ApplicationInterface
     *   The called object.
     */
    public function run()
    {
        if (false === $this->boot()) {
            throw new \RuntimeExeption('Cannot not boot application');
        }

        return $this;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent\AbstractDataGenerator;
use OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent\HomeDataGenerator;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraProductionFixturesInterface;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraFunctionalFixturesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

/**
 * Class LoadNodeDemoData
 */
class LoadNodeDemoData extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface, OrchestraProductionFixturesInterface, OrchestraFunctionalFixturesInterface
{
    protected $nodede;
    protected $nodeen;
    protected $nodefr;

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

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $languages = array("de", "en", "fr");

        $homeNode = new HomeDataGenerator($this, $this->container, $manager, 1, 'status-draft');
        $this->addNode($manager, $homeNode, $languages);
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        return 560;
    }

    /**
     * @param ObjectManager         $manager
     * @param AbstractDataGenerator $dataGenerator
     * @param array                 $languages
     */
    protected function addNode(
        ObjectManager $manager,
        AbstractDataGenerator $dataGenerator,
        array $languages = array("fr", "en")
    ){
        foreach ($languages as $language) {
            $node = $dataGenerator->generateNode($language);
            $manager->persist($node);
            $this->setReference("node-".$node->getNodeId().'-'.$node->getLanguage().'-'.$node->getVersion(), $node);
        }
        $manager->flush();
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: marco
 * Date: 06/08/16
 * Time: 15.23
 *
 * This file contains the StringBuffer class.
 */

namespace Mbcraft\Piol;

/**
 * Class StringBuffer
 * @package Mbcraft\Piol
 *
 * This class models a string buffer, and implements the IReader and IWriter interfaces for reading
 * and writing on it.
 */
class StringBuffer implements IWriter
{

    private $pos = 0;
    private $closed = false;
    private $data;

    /**
     * Constructs a new StringBuffer.
     *
     * StringBuffer constructor.
     * @param string $data The data that is contained in the buffer. If no parameter is passed the buffer is empty by default.
     */
    function __construct($data="") {
        $this->data = "".$data;
    }

    /**
     * Returns the number of bytes available for reading from the current
     * position.
     *
     * @api
     */
    function available()
    {
        return strlen($this->data)-$this->pos;
    }

    /**
     * Checks if this reader is open.
     *
     * @return boolean true if this reader is open, false otherwise.
     *
     * @api
     */
    function isOpen()
    {
        return !$this->closed;
    }

    /**
     * Reads data from this reader following the 'scanf' parameter convention.
     *
     * @param string $format The format string of the data to read
     * @return array An array of ordered values readed following the format provided.
     *
     * @api
     */
    function scanf($format)
    {
        $spec_pattern = "/%[+-]?('.)?[-]?(\d)*(\..\d)?[%bcdeEfFgGosuxX]/";

        $source = substr($this->data,$this->pos);

        $result = sscanf($source,$format);

        if ($result==-1) return;
        else {
            $l = 0;
            foreach ($result as $v) {
                $l += strlen("".$v);
            }
        }

        $no_patterns_format = preg_replace($spec_pattern,"",$format);
        //echo "No patterns format : [".$no_patterns_format."] LEN=".strlen($no_patterns_format);
        $l+=strlen($no_patterns_format);

        $this->pos+=$l;

        return $result;
    }

    /**
     * Reads n bytes from this stream.
     *
     * @param int $length the number of bytes to read.
     * @return string|FALSE the readed string or FALSE on failure.
     *
     * @api
     */
    function read($length)
    {
        $l = $this->pos+$length < strlen($this->data) ? $length : strlen($this->data)-$this->pos;
        $result = substr($this->data,$this->pos,$l);
        $this->pos+=$l;
        return $result;
    }

    /**
     * Checks if the data at the index is on an EOL marker.
     *
     * @param $i The index on which to check
     * @return bool true if the index points to an EOL marker, false otherwise
     *
     * @internal
     */
    private function isEndOfLine($i) {
        $ch = $this->data[$i];

        if ($this->getLineEndingModeCrlf()) {
            if ($ch=="\r") {
                $more_ch = $i + 1 < strlen($this->data);

                if ($more_ch) {
                    $next_n = $this->data[$i + 1] == "\n";

                    if ($next_n) return true;
                }
            }
        } else {
            if ($ch=="\n") return true;
        }
        return false;
    }

    /**
     * Reads a line from this reader, ended by a CR or CRLF.
     *
     * @return string the readed line.
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function readLine()
    {
        $i = $this->pos;
        $tot_len = strlen($this->data);
        while ($i<$tot_len && !$this->isEndOfLine($i)) {
            $i++;
        }

        $result = substr($this->data,$this->pos,$i-$this->pos);
        $i++;   //skip first EOL char
        if ($this->getLineEndingModeCrlf()) $i++;  //skip second EOL char if needed
        $this->pos=$i;  //update position
        return $result;
    }

    /**
     * Reads one character from this reader.
     *
     * @return string a string of one character readed from the stream.
     * @throws \Mbcraft\Piol\IOException If  the parameter is not a string of one character.
     *
     * @api
     */
    function readChar()
    {
        return $this->data[$this->pos++];
    }

    /**
     * Moves the read pointer at the initial position of the file, as calling seek(0).
     *
     * @return boolean true if the operation succeded, false otherwise.
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function reset()
    {
        $this->pos = 0;
    }

    /**
     * Moves the read pointer at the specified location.
     *
     * @param int $location The location at which point the reader.
     * @return boolean true if the operation succeeded, false otherwise.
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function seek($location)
    {
        $this->pos = $location;
    }

    /**
     * Skip bytes from the current position of the stream.
     *
     * @param int $offset The number of bytes to skip.
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function skip($offset)
    {
        $this->pos += $offset;
    }

    /**
     * Returns the current position inside the opened stream.
     *
     * @return int the byte index of the reader inside the stream.
     * @throws IOException if this reader is already closed.
     *
     * @api
     */
    function pos()
    {
        return $this->pos;
    }

    /**
     * Checks if the stream is ended.
     *
     * @return true if the end of the stream is reached, false otherwise.
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function isEndOfStream()
    {
        return strlen($this->data)==$this->pos;
    }

    /**
     * Closes this reader, releasing the locks acquired.
     *
     * @throws \Mbcraft\Piol\IOException if this reader is already closed.
     *
     * @api
     */
    function close()
    {
        $this->closed = true;
    }

    /**
     * Returns the actual length of the buffer.
     *
     * @return int The total length of the buffer.
     *
     * @api
     */
    function length() {
        return strlen($this->data);
    }

    protected static $defaultLineEndingModeCrlf = true;
    protected $lineEndingModeCrlf = true;
    /**
     *
     * Sets the default line ending mode for all writers.
     *
     * @param boolean $default_line_ending_crlf true if CRLF should be used, false for CR.
     *
     * @api
     */
    static function setDefaultLineEndingModeCrlf($default_line_ending_crlf)
    {
        self::$defaultLineEndingModeCrlf = $default_line_ending_crlf;
    }

    /**
     *
     * Gets the default line ending mode for all writers.
     *
     * @return boolean true if CRLF should be used, false for CR.
     *
     * @api
     */
    static function getDefaultLineEndingModeCrlf()
    {
        return self::$defaultLineEndingModeCrlf;
    }

    /**
     *
     * Sets the line ending mode for this writer.
     *
     * @param boolean $line_ending_mode true for CRLF, false for CR.
     *
     * @api
     */
    function setLineEndingModeCrlf($line_ending_mode)
    {
        $this->lineEndingModeCrlf = $line_ending_mode;
    }

    /**
     *
     * Gets the line ending mode for this writer. If not set uses the default.
     *
     * @return boolean returns true if CRLF should be used, false for CR.
     *
     * @api
     */
    function getLineEndingModeCrlf()
    {
        return $this->lineEndingModeCrlf;
    }

    /**
     *
     * Writes values to this writer following the printf rules. All additional parameters
     * after 'format' are treated as data.
     *
     * @param mixed $format The format to use, following the printf rules.
     *
     * @return int the actual fprintf result.
     *
     * @throws \Mbcraft\Piol\IOException if this writer is already closed.
     *
     * @api
     */
    function printf($format)
    {
        $this->checkNotClosed();

        $args = func_get_args();
        $printf_args = array_slice($args, 1);
        $p = 'return sprintf($format';
        $i = 0;
        foreach ($printf_args as $arg) {

            $p.=',$printf_args[' . $i . ']';
            $i++;
        }
        $p.=");";
        $d = eval($p);
        $result = $this->write($d);
        return $result;
    }

    /**
     *
     * Writes a string inside this stream at the current position. No characters are added.
     *
     * @param string $string The string to write.
     * @return int the number of bytes written, or a negative value if an error occurred.
     *
     * @throws \Mbcraft\Piol\IOException if this writer is already closed.
     *
     * @api
     */
    function write($string)
    {
        $this->checkNotClosed();

        $l = strlen($string);

        $before_data = substr($this->data,0,$this->pos);
        $after_data = substr($this->data,$this->pos+$l);

        $this->data = $before_data.$string.$after_data;
        $this->pos += $l;
    }

    /**
     *
     * Writes a string in this stream, ending it with CRLF characters.
     *
     * @param string $string the string to write
     *
     * @return int the fwrite result code
     *
     * @throws \Mbcraft\Piol\IOException if this writer is already closed.
     *
     * @api
     */
    function writeln($string)
    {
        $this->checkNotClosed();

        $eol = $this->getLineEndingModeCrlf() ? "\r\n" : "\n";
        $this->write($string.$eol);
    }

    /**
     *
     * Truncate this stream at the specified size.
     *
     * @param int $size the maximum size of the data.
     * @return true if the operation was successful, false otherwise.
     *
     * @throws \Mbcraft\Piol\IOException if this writer is already closed.
     *
     * @api
     */
    function truncate($size)
    {
        $this->checkNotClosed();

        if (strlen($this->data > $size)) {
            $this->data = substr($this->data, 0, $size);
        }
    }

    private function checkNotClosed() {
        if ($this->closed) throw new IOException("The StringBuffer is closed!");
    }

    /**
     * Returns the total content of this buffer.
     *
     * @return string
     */
    function __toString() {
        return $this->data;
    }
}


<?php

namespace AdminBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use CoreBundle\Entity\Actor;
use EcommerceBundle\Entity\Product;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Class AdminManager
 */
class AdminManager
{
    private $entityManager;

    private $securityContext;

    private $parameters;

    private $container;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager, $securityContext, array $parameters, $container)
    {
        $this->entityManager = $entityManager;
        $this->securityContext = $securityContext;
        $this->parameters = $parameters['parameters'];
        $this->container = $container;
    }

    /**
     * Sort entities from the given IDs
     *
     * @param string $entityName
     * @param string $values
     */
    public function sort($entityName, $values)
    {
        $values = json_decode($values);

        for ($i=0; $i<count($values); $i++) {
            $this->entityManager
                ->getRepository($entityName)
                ->createQueryBuilder('e')
                ->update()
                ->set('e.order', $i)
                ->where('e.id = :id')
                ->setParameter('id', $values[$i]->id)
                ->getQuery()
                ->execute();
        }
    }

    /**
     * Sets an entity as filtrable
     *
     * @param string $entityName
     * @param int    $id
     *
     * @throws NotFoundHttpException
     * @return boolean
     */
    public function toggleFiltrable($entityName, $id)
    {
        $entity = $this->entityManager->getRepository($entityName)->find($id);

        if (!$entity) {
            throw new NotFoundHttpException();
        }

        $entity->toggleFiltrable();

        $this->entityManager->persist($entity);
        $this->entityManager->flush();

        return $entity->isFiltrable();
    }

}


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

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Options\UserServiceOptionsInterface,
    CmsUser\Options\ModuleOptions,
    CmsUser\Service\UserService,
    CmsUser\Service\UserServiceInterface;

class UserServiceFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return UserServiceInterface
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();

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

        /* @var $passwordGenerator \CmsCommon\Crypt\PasswordGeneratorInterface */
        $passwordGenerator = $services->get($options->getPasswordGeneratorService());

        /* @var $mailService \CmsMailer\Service\MailServiceInterface */
        $mailService = $services->get($options->getMailService());
        $mailService->setFromAddress($options->getSenderEmailAddress())
                    ->setFromName($options->getSenderName());

        return new UserService($options, $serviceLocator, $passwordGenerator, $mailService);
    }
}


<?php

namespace Wambo\Catalog\Model;

use Wambo\Catalog\Exception\SlugException;

/**
 * Class Slug represents a human-readable, descriptive URL fragment for the product (e.g.
 * "fancy-t-shirt-1-with-ice-cream-pooping-unicorn")
 *
 * @package Wambo\Catalog\Model
 */
class Slug
{
    /**
     * @var string $whiteSpacePattern A regular expression that matches white-space characters
     */
    private $whiteSpacePattern = '/[\s]/';

    /**
     * @var string $invalidCharactersPattern A regular expression that matches all characters that are invalid for a
     *      Slug
     */
    private $invalidCharactersPattern = '/[^\p{L}\w-_:.,+]/u';

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

    /**
     * @var int $maxLength Defines the maximum length of a Slug
     */
    private $maxLength = 64;
    /**
     * @var string
     */
    private $slug;

    /**
     * Create a new SlugValidator instance.
     *
     * @param string $slug  human-readable, descriptive URL fragment for the product (e.g.
     *                      "fancy-t-shirt-1-with-ice-cream-pooping-unicorn")
     *
     * @throws SlugException If the given $slug is invalid
     */
    public function __construct(string $slug)
    {
        $this->validateSlug($slug);
        $this->slug = $slug;
    }

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

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

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

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

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

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

}


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

namespace Autarky\Container\Factory;

use Autarky\Container\ContainerInterface;
use Autarky\Container\Exception\UnresolvableArgumentException;

/**
 * A factory.
 */
class Factory implements FactoryInterface
{
	/**
	 * The factory's definition.
	 *
	 * @var Definition
	 */
	protected $definition;

	/**
	 * The factory's default parameters.
	 *
	 * @var array
	 */
	protected $params;

	/**
	 * Constructor.
	 *
	 * @param Definition $definition
	 * @param array      $params
	 */
	public function __construct(Definition $definition, array $params = array())
	{
		$this->definition = $definition;
		$this->params = $params;
	}

	/**
	 * Get a new instance of the factory.
	 *
	 * @param  array  $params
	 *
	 * @return static
	 */
	public function getFactory(array $params = array())
	{
		$factory = clone $this;
		$factory->params = $params;
		return $factory;
	}

	/**
	 * {@inheritdoc}
	 */
	public function invoke(ContainerInterface $container, array $params = array())
	{
		$params = array_replace($this->params, $params);
		$callable = $this->definition->getCallable();

		if (is_array($callable) && is_string($callable[0])) {
			$callable[0] = $container->resolve($callable[0]);
		}

		$args = [];

		foreach ($this->definition->getArguments() as $arg) {
			if ($arg->isClass()) {
				$resolvedArg = $this->resolveClassArg($container, $arg, $params);
			} else {
				$resolvedArg = $this->resolveScalarArg($container, $arg, $params);
			}

			if ($resolvedArg instanceof FactoryInterface) {
				$resolvedArg = $resolvedArg->invoke($container);
			}

			$args[$arg->getPosition()] = $resolvedArg;
		}

		return call_user_func_array($callable, $args);
	}

	protected function resolveClassArg(ContainerInterface $container, ClassArgument $arg, array $params)
	{
		$name = $arg->getName();
		$class = $arg->getClass();

		// loop to prevent code repetition. executes once trying to find the
		// parameter name in the $params array, then once more trying to find
		// the class name (typehint) of the parameter.
		while ($name !== null) {
			if ($params && array_key_exists($name, $params)) {
				$class = $params[$name];
			}

			if (is_object($class)) {
				return $class;
			}

			$name = ($name != $class) ? $class : null;
		}

		try {
			return $container->resolve($class);
		} catch (\ReflectionException $exception) {
			if (!$arg->isRequired()) {
				return null;
			}

			throw $exception;
		}
	}

	protected function resolveScalarArg(ContainerInterface $container, ScalarArgument $arg, array $params)
	{
		$name = $arg->getName();

		if ($params && array_key_exists($name, $params)) {
			return $params[$name];
		}

		if (!$arg->isRequired()) {
			return $arg->getDefault();
		}

		$pos = $arg->getPosition() + 1;
		$defName = $this->definition->getName();
		$message = "Unresolvable argument: Argument #{$pos} ($name) of $defName"
			.' - Argument is required and has no value';

		throw new UnresolvableArgumentException($message);
	}

	/**
	 * Proxy for the invoke method. Makes the factory class callable.
	 *
	 * @param  ContainerInterface $container
	 * @param  array              $params
	 *
	 * @return mixed
	 */
	public function __invoke(ContainerInterface $container, array $params = array())
	{
		return $this->invoke($container, $params);
	}
}


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

namespace RedKiteCms\EventSystem\Listener\Request;

use RedKiteCms\Rendering\Queue\QueueManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContext;

/**
 * Class QueueListener listens to Kernel Request and renders the not executed queue flow when it exists
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Listener\Request
 */
class QueueListener
{
    /**
     * @var \RedKiteCms\Rendering\Queue\QueueManager
     */
    private $queueManager;
    /**
     * @type \Symfony\Component\Security\Core\SecurityContext
     */
    private $securityContext;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Rendering\Queue\QueueManager $queueManager
     * @param \Symfony\Component\Security\Core\SecurityContext $securityContext
     */
    public function __construct(QueueManager $queueManager, SecurityContext $securityContext)
    {
        $this->queueManager = $queueManager;
        $this->securityContext = $securityContext;
    }

    /**
     * Aligns the site slots
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->getMethod() == "POST") {
            return $event;
        }

        $token = $this->securityContext->getToken();
        if (null === $token) {
            return $event;
        }

        $data = $request->get("data");
        if (null === $data) {
            if ($this->queueManager->hasQueue()) {
                $content = $this->queueManager->renderQueue();
                $event->setResponse(new Response($content));

                return $event;
            }
        }
    }
}


<?php
namespace Lab123\Odin;

use Illuminate\Database\Eloquent\Collection as IlluminateCollection;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Collection extends IlluminateCollection
{

    static $loaded = false;

    /**
     * Get the collection of items as a plain array.
     *
     * @return array
     */
    public function toArray()
    {
        $urls = [];
        $actions = [];

        if (count($this->items) < 1) {
            return parent::toArray();
        }

        $entity = $this->items[0];

        if (is_array($entity->load)) {
            foreach ($entity->load as $k => $load) {
                $this->load($load);
            }
        }

        $data = parent::toArray();
        $actions = $entity->getActions();

        if (count($actions) > 0) {
            foreach ($data as $k => $resource) {

                if (count($resource) < 2) {
                    continue;
                }

                $data[$k] += [
                    'actions' => $actions
                ];
            }
        }

        $data = $this->normalizeArray($data);

        return $data;
    }

    private function normalizeArray($data)
    {
        $onlyOneProperty = false;

        foreach ($data as $resource) {
            if (count($resource) < 2) {
                $onlyOneProperty = true;
            }
        }

        if (! $onlyOneProperty) {
            return $data;
        }

        $newData = [];
        $rootUriResource = '';
        foreach ($data as $k => $value) {
            if (key_exists('uri', $value)) {
                $urlExploded = explode('/', $value['uri']);
                array_pop($urlExploded);
                $rootUriResource = implode('/', $urlExploded);
            }
            unset($data[$k]);
            $data[$k] = array_last($value);
            //$data['data'][$k] = array_last($value);
        }

        $data = [
            'url' => $rootUriResource
        ] + $data;

        return $data;
    }
}


<?php namespace Prologue\Support;

use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection {

	/**
	 * Tries to filter items by a key/value pair.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return \Prologue\Support\Collection
	 */
	public function filterBy($key, $value)
	{
		return $this->filter(function($item) use ($key, $value)
		{
			$itemValue = is_object($item) ? $item->{$key} : $item[$key];

			return $itemValue == $value;
		});
	}

	/**
	 * Orders items by a key.
	 *
	 * @param  string  $key
	 * @param  string  $direction
	 * @return \Prologue\Support\Collection
	 */
	public function orderBy($key, $direction = 'asc')
	{
		return $this->sort(function($a, $b) use ($key, $direction)
		{
			$valueA = is_object($a) ? $a->{$key} : $a[$key];
			$valueB = is_object($b) ? $b->{$key} : $b[$key];

			if ($valueA == $valueB) return 0;

			$result = ($valueA < $valueB) ? -1 : 1;

			// If the direction is descending, reverse the order.
			return $direction === 'desc' ? -($result) : $result;
		});
	}

}


<?php

namespace Gaufrette\Core\Operator;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\File;

final class LastModificationOperator extends AbstractOperator implements CanLoad, CanSave
{
    /**
     * {@inheritdoc}
     */
    public function supports(File $file, Adapter $adapter)
    {
        return $this->adapterHasBehavior($adapter, 'Gaufrette\Core\Adapter\KnowsLastModification');
    }

    /**
     * {@inheritdoc}
     */
    public function load(File $file, Adapter $adapter)
    {
        $time = $adapter->readLastModification($file->getName());

        if (null !== $time) {
            $file->setLastModification(\DateTime::createFromFormat('U', $time));
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function save(File $file, Adapter $adapter)
    {
        $datetime = $file->getLastModification();

        if (null !== $datetime) {
            $adapter->writeLastModification($file->getName(), $datetime->format('U'));
        }

        return $this;
    }
}


<?php namespace ForeverPHP\Core;

/**
 * Permite controlar todo el flujo de salida canalizandolo por una tuberia,
 * esto permite un mejor control de lo que se le entrega como respuesta al
 * cliente con una salida mas limpia.
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 1.0.0
 */
class Stream {
    /**
     * [$data description]
     *
     * @var [type]
     */
    private $data;

    /**
     * [$headerData description]
     *
     * @var [type]
     */
    private $headerData;

    /**
     * [$buffer description]
     *
     * @var [type]
     */
    private $buffer;

    /**
     * [$lastIndex description]
     *
     * @var [type]
     */
    private $lastIndex;

    /**
     * Contiene la instancia singleton de Cache.
     *
     * @var \ForeverPHP\Core\Stream
     */
    private static $instance;

    private function Stream() {
        $this->data = array();
        $this->headerData = array();
        $this->buffer = '';
        $this->lastIndex = 0;
    }

    /**
     * Obtiene o crea la instancia singleton de Stream.
     *
     * @return \ForeverPHP\Core\Stream
     */
    public static function getInstance() {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * [__call description]
     *
     * @param  [type] $name      [description]
     * @param  [type] $arguments [description]
     * @return [type]            [description]
     */
    public function __call($name, $arguments)
    {
        // Nota: el valor $name es sensible a mayúsculas.
        echo "Llamando al método de objeto '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**
     * Agrega datos a la tuberia.
     *
     * @param  mixed   $data
     * @param  integer $index
     * @param  boolean $isHeader
     * @return [type]            [description]
     */
    public function pipe($data, $index, $isHeader = false) {
        $this->lastIndex++;
        $this->data[$this->lastIndex] = $data;

    }

    /**
     * Retorna todos los elemento que se encuentran en la tuberia.
     *
     * @return array
     */
    public function getAll() {
        return $this->data;
    }

    /*public function getBuffer() {
        return $this->buffer;
    }*/

    /**
     * [remove description]
     *
     * @param  integer $index
     * @return [type]        [description]
     */
    public function remove($index) {

    }

    /**
     * Limpia el Stream.
     */
    public function clean() {
        $this->data = array();
        $this->buffer = '';
        $this->lastIndex = 0;
    }

    /**
     * Renderiza el contenido de Stream para ser enviado al cliente.
     */
    public function render() {
        echo $this->buffer;
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (count($arguments) === 3 && is_array($arguments[2])) {
            $options = $this->prepareOptions(array_pop($arguments));
            $arguments = array_merge($arguments, $options);
        }

        parent::setArguments($arguments);
    }

    /**
     * Returns a list of options and modifiers compatible with Redis.
     *
     * @param array $options List of options.
     *
     * @return array
     */
    protected function prepareOptions($options)
    {
        $options = array_change_key_case($options, CASE_UPPER);
        $normalized = array();

        if (!empty($options['MATCH'])) {
            $normalized[] = 'MATCH';
            $normalized[] = $options['MATCH'];
        }

        if (!empty($options['COUNT'])) {
            $normalized[] = 'COUNT';
            $normalized[] = $options['COUNT'];
        }

        return $normalized;
    }

    /**
     * {@inheritdoc}
     */
    public function parseResponse($data)
    {
        if (is_array($data)) {
            $members = $data[1];
            $result = array();

            for ($i = 0; $i < count($members); ++$i) {
                $result[$members[$i]] = (float) $members[++$i];
            }

            $data[1] = $result;
        }

        return $data;
    }
}


<?php
namespace Wambo\Catalog\Mapper;

use Wambo\Catalog\Exception\CatalogException;
use Wambo\Catalog\Model\Catalog;

/**
 * Class CatalogMapper creates \Wambo\Model\Product models from catalog data
 *
 * @package Wambo\Mapper
 */
class CatalogMapper
{
    /**
     * @var ProductMapper
     */
    private $productMapper;

    /**
     * Creates a new instance of the CatalogMapper class.
     *
     * @param ProductMapper $productMapper A ProductMapper instance for converting unstructured product data to Product
     *                                     models
     */
    public function __construct(ProductMapper $productMapper)
    {
        $this->productMapper = $productMapper;
    }

    /**
     * Get a Catalog model from the an array of catalog data
     *
     * @param array $catalogData An array containing a product catalog
     *
     * @return Catalog
     *
     * @throws CatalogException If the catalog cannot be created
     */
    public function getCatalog(array $catalogData)
    {
        /** @var array $skuIndex A list of all SKUs */
        $skuIndex = [];

        /** @var array $slugIndex A list of all product slugs */
        $slugIndex = [];

        $index = 1;
        $products = [];
        foreach ($catalogData as $catalogItem) {

            try {
                // convert the product data into a Product model
                $product = $this->productMapper->getProduct($catalogItem);

                // check for duplicate SKUs
                $sku = strtolower($product->getSku()->__toString());
                if (array_key_exists($sku, $skuIndex)) {
                    throw new CatalogException(sprintf("Cannot add a second product with the SKU '%s' to the catalog",
                        $sku));
                }
                $skuIndex[$sku] = 1;

                // check for duplicate Slugs
                $slug = strtolower($product->getSlug()->__toString());
                if (array_key_exists($slug, $slugIndex)) {
                    throw new CatalogException(sprintf("Cannot add a second product with the Slug '%s' to the catalog",
                        $slug));
                }
                $slugIndex[$slug] = 1;

                // add the product to the catalog
                $products[] = $product;

            } catch (\Exception $productException) {
                throw new CatalogException(sprintf("Cannot convert catalog item %s into a product: %s", $index,
                    $productException->getMessage()), $productException);
            }

            $index++;
        }

        return new Catalog($products);
    }
}


<?php
namespace Extlib;

/**
 * Generator class
 *
 * @category    Extlib
 * @author      Lukasz Ciolecki <ciolecki.lukasz@gmail.com>
 * @copyright   Copyright (c) Lukasz Ciolecki (mart)
 */
final class Generator
{
    /* Configuration */
    const RAND_MIN = 1;
    const RAND_MAX = 1000000;
    const CUT_LEN = 4;

    /* Algorithm types */
    const ALGO_MD5 = 'md5';
    const ALGO_SHA256 = 'sha256';
    const ALGO_SHA1   = 'shad1';

    /**
     * Array allowed types of algorithm
     *
     * @var array
     */
    static protected $allowedAlgorithm = array(
        self::ALGO_MD5,
        self::ALGO_SHA256,
        self::ALGO_SHA1
    );

    /**
     * Doctrine v1.2 generate method
     *
     *
     * @param string $tableName
     * @param string $field
     * @param string $length
     * @return string
     * @throws Extlib\Exception
     */
    static public function doctrine($tableName, $field, $length = 16)
    {
        do {
            $generate = self::generate($length);
        } while (self::doctrineQuery($tableName, $field, $generate));

        return $generate;
    }

    /**
     * Doctrine v2.x generate method
     *
     * @param \Doctrine\ORM\EntityManager $entityManager
     * @param string $entityName
     * @param string $field
     * @param int $length
     * @return string
     */
    static public function generateDoctrine2(\Doctrine\ORM\EntityManager $entityManager, $entityName, $field, $length = 16)
    {
        do {
            $generate = self::generate($length);
        } while (self::doctrine2Query($entityManager, $entityName, $field, $generate));

        return $generate;
    }

    /**
     * Phalcon ORM generate method
     *
     * @param string $modelName
     * @param string $field
     * @param int $length
     * @return string
     */
    static public function generatePhalcon($modelName, $field, $length = 16)
    {
        do {
            $generate = self::generate($length);
        } while (self::phalconQuery($modelName, $field, $generate));

        return $generate;
    }

    /**
     * Phalcon generate query
     *
     * @param string $modelName
     * @param string $field
     * @param string $generate
     * @return int
     */
    static protected function phalconQuery($modelName, $field, $generate)
    {
        $return = \Phalcon\Mvc\Model::query()
                                    ->setModelName($modelName)
                                    ->where("$field = :value:")
                                    ->bind(array('value' => $generate))
                                    ->execute();

        return (boolean) $return->count();
    }

    /**
     * Doctgrine ORM v1.2 generate query
     *
     * @param string $tableName
     * @param string $field
     * @param string $generate
     * @return int
     */
    static protected function doctrineQuery($tableName, $field, $generate)
    {
        return \Doctrine_Query::create()
                              ->select($field)
                              ->from($tableName)->where("$field = ?", $generate)
                              ->execute(array(), \Doctrine_Core::HYDRATE_SINGLE_SCALAR);
    }

    /**
     * Doctgrine ORM v2 generate query
     *
     * @param \Doctrine\ORM\EntityManager $entityManager
     * @param type $entityName
     * @param type $field
     * @param type $generate
     * @return mixed
     */
    static protected function doctrine2Query(\Doctrine\ORM\EntityManager $entityManager, $entityName, $field, $generate)
    {
        $result = $entityManager->createQueryBuilder()
                                ->select("entity.$field")
                                ->from($entityName, 'entity')
                                ->where("entity.$field = :$field")
                                ->setParameter("$field", $generate)
                                ->getQuery()
                                ->getResult();

        return !empty($result);
    }

    /**
     * Generate random string
     *
     * @param int $length
     * @param string $algorithm
     * @return string
     * @throws \Extlib\Exception
     */
    static public function generate($length = 16, $algorithm = 'sha256')
    {
        if (!in_array($algorithm, self::$allowedAlgorithm)) {
            throw new Exception("Hash algorithm $algorithm doesn't exists!");
        }

        $salt = hash($algorithm, time());

        return substr(hash($algorithm, (mt_rand(self::RAND_MIN, self::RAND_MAX) % $length) . $salt . mt_rand(self::RAND_MIN, self::RAND_MAX)), self::CUT_LEN, $length);
    }
}


<?php

namespace Dhii\Output;

use ArrayAccess;
use Dhii\Output\Exception\TemplateRenderException;
use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use Psr\Container\ContainerInterface;
use stdClass;

trait CreateTemplateRenderExceptionCapableTrait
{
    /**
     * Creates a new render failure exception.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null                             $message  The error message, if any.
     * @param int|null                                           $code     The error code, if any.
     * @param RootException|null                                 $previous The inner exception for chaining, if any.
     * @param TemplateInterface|null                             $template The associated renderer, if any.
     * @param array|ArrayAccess|stdClass|ContainerInterface|null $context  The associated context, if any.
     *
     * @return TemplateRenderException The new exception.
     */
    protected function _createTemplateRenderException(
        $message = null,
        $code = null,
        RootException $previous = null,
        TemplateInterface $template = null,
        $context = null
    ) {
        return new TemplateRenderException($message, $code, $previous, $template, $context);
    }
}


<?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.
 */

/**
 * User.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 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\MiniProgram\Sns;

use EasyWeChat\MiniProgram\Core\AbstractMiniProgram;

class Sns extends AbstractMiniProgram
{
    /**
     * Api.
     */
    const JSCODE_TO_SESSION = 'https://api.weixin.qq.com/sns/jscode2session';

    /**
     * JsCode 2 session key.
     *
     * @param string $jsCode
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getSessionKey($jsCode)
    {
        $params = [
            'appid' => $this->config['app_id'],
            'secret' => $this->config['secret'],
            'js_code' => $jsCode,
            'grant_type' => 'authorization_code',
        ];

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


<?php

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

/**
 * This class manage object
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 */
class ObjectOperation
{
	/**
	 * create an array with an object
	 *
	 * @access public
	 * @param $mObject
	 * @return array
	 */
	public static function objectToArray($mObject) : array
	{
		if ( is_object($mObject)) {

		    $mObject = (array) $mObject;
		}

		if (is_array($mObject)) {

			$aNew = array();

			foreach($mObject as $sKey => $mValues) {

				$sKey = preg_replace("/^\\0(.*)\\0/", "", $sKey);
				$aNew[$sKey] = self::objectToArray($mValues);
			}
		}
		else {

			$aNew = $mObject;
		}

		return $aNew;
	}
}


<?php
namespace eMacros\Runtime\Type;

use eMacros\Runtime\GenericFunction;

class CastToType extends GenericFunction {
	/**
	 * Expected type
	 * @var string
	 */
	public $type;

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

	/**
	 * Casts a value to a especified type
	 * Usage: (as-string 2)
	 * Returns: the casted value
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException("CastToType: No parameters found.");
		$value = $arguments[0];

		switch ($this->type) {
			case 'bool': case 'boolean': $value = (bool) $value; break;
			case 'int': case 'integer': $value = (int) $value; break;
			case 'float': case 'double': case 'real': $value = (double) $value; break;
			case 'string': $value = (string) $value; break;
			case 'array': $value = (array) $value; break;
			case 'object': $value = (object) $value; break;
			case 'unset': case 'null': $value = null; break;
			case 'binary': $value = (binary) $value; break;
		}

		return $value;
	}
}
?>


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

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockEditedEvent;
use RedKiteCms\EventSystem\Event\Block\BlockEditingEvent;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\JsonTools;
use RedKiteCms\Tools\Utils;

/**
 * Class BlockManagerArchive is the object assigned to archive a block after it is changed
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerArchive extends BlockManager
{
    /**
     * Archives the given block
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     * @param array $block
     */
    public function archive($sourceDir, array $options, $username, $block)
    {
        $this->resolveOptions($options);

        $block = json_decode($block, true);
        $block["history"] = array();
        $this->init($sourceDir, $options, $username);
        $historyDirName = sprintf('%s/archive/%s', $this->getDirInUse(), $options["blockname"]);
        $historyFileName = $historyDirName . '/history.json';
        if (!is_dir($historyDirName)) {
            mkdir($historyDirName);
        }

        $history = array();
        if (file_exists($historyFileName)) {
            $history = json_decode(file_get_contents($historyFileName), true);
        }
        $history = array_merge($history, array($block["history_name"] => $block));

        FilesystemTools::writeFile($historyFileName, json_encode($history));
    }
}


<?php
/*
 * This file is part of the Qimnet update tracker Bundle.
 *
 * (c) Antoine Guigan <aguigan@qimnet.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Qimnet\UpdateTrackerBundle\Templating;

use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
use Qimnet\UpdateTrackerBundle\CacheManager\CacheManagerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Renders a cached fragement.
 */
class CacheFragmentRenderer implements FragmentRendererInterface
{
    private $cacheManager;
    private $inlineRenderer;

    public function __construct(FragmentRendererInterface $inlineRenderer, CacheManagerInterface $cacheManager)
    {
        $this->cacheManager = $cacheManager;
        $this->inlineRenderer = $inlineRenderer;
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'cache';
    }

    /**
     * @inheritdoc
     *
     * Additional optional options :
     *
     *  * updateTrackerName : the update tracker namespaces the action is linked with.
     *  * ttl : the ttl of the object in the cache
     *  * repositoryName: the cache repository name
     */
    public function render($uri, Request $request, array $options = array())
    {
        $inlineRenderer = $this->inlineRenderer;

        if (!isset($options['updateTrackerName'])) {
            $options['updateTrackerName'] = 'global';
        }
        $uriHash = md5(serialize($uri));

        return $this->cacheManager->getObject($options['updateTrackerName'],
                'controller/' . $uriHash,
                function() use ($inlineRenderer, $uri, $request, $options) {
                    return $inlineRenderer->render($uri, $request, $options);
                },
                isset($options['ttl']) ? $options['ttl'] : null,
                isset($options['repositoryName']) ? $options['repositoryName'] : null);
    }
}


<?php
namespace app\manage\controller;

use think\Request;
use lookfeel\common\Format;
use core\manage\logic\FileLogic;

class Upload extends Base
{

    /**
     * 上传文件
     *
     * @param Request $request
     * @throws \think\exception\HttpResponseException
     */
    public function upload(Request $request)
    {
        $type = $request->param('upload_type', '');

        // 文件
        $upload_file = isset($_FILES['upload_file']) ? $_FILES['upload_file'] : null;
        if (empty($upload_file)) {
            responseReturn(Format::formatResult(0, '上传文件不存在'));
        }

        // 额外配置
        $upload_option = $request->param('upload_option', '');
        if (! empty($upload_option)) {
            $upload_option = json_decode($upload_option, true);
        } else {
            $upload_option = [];
        }

        // 上传文件
        $upload_driver = FileLogic::instance()->getUploadDriver();
        $res = $upload_driver->upload($upload_file, $type, $upload_option);
        responseReturn($res);
    }

    /**
     * wangEditor
     *
     * @param Request $request
     * @return string
     */
    public function wang(Request $request)
    {
        // 文件
        $upload_file = isset($_FILES['upload_file']) ? $_FILES['upload_file'] : null;
        if (empty($upload_file)) {
            return 'error|上传文件不存在';
        }

        // 额外配置
        $upload_option = [
            'width' => 1920,
            'height' => 1080
        ];

        // 上传文件
        $upload_driver = FileLogic::instance()->getUploadDriver();
        $res = $upload_driver->upload($upload_file, '', $upload_option);
        if ($res['code'] == 1) {
            return $res['data']['url'];
        } else {
            return 'error|' . $res['msg'];
        }
    }
}


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

/**
 * Class HidePageController is the object assigned to hide a published page from production
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Controller\Seo
 */
abstract class HidePageController extends BasePageController
{
    /**
     * Implements the action to hide a page from production
     * @param array $options
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function hide(array $options)
    {
        $request = $options["request"];
        $pageName = $request->get('page');
        $languageName = $request->get('language') . '_' . $request->get('country');
        $options["page_manager"]
            ->contributor($options["username"])
            ->hide($pageName, $languageName);

        return $this->buildJSonResponse(array());
    }
}


<?php

/**
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
 * @copyright Aimeos (aimeos.org), 2014-2018
 * @package MW
 * @subpackage Translation
 */

namespace Zend\I18n\Translator;
use Zend\I18n\Translator\Translator;

/**
 * Zend\I18n\Translator\Translator with ability to return all messages
 *
 * @package Zend
 * @subpackage I18n
 */
class MwTranslator extends Translator
{
	/**
	 * Returns all message strings and translations.
	 *
	 * @param string $domain Translation domain
	 * @param string $locale $locale ISO language name, like "en" or "en_US"
	 * @return Zend\I18n\Translator\TextDomain Array like TextDomain object
	 */
	public function getMessages( $domain = 'default', $locale = null )
	{
		if( $locale === null ) {
			$locale = $this->getLocale();
		}

		if( !isset( $this->messages[$domain][$locale] ) ) {
			$this->loadMessages( $domain, $locale );
		}

		return $this->messages[$domain][$locale];
	}
}


<?php

declare(strict_types=1);

namespace NAttreid\Breadcrumbs;

use Nette\Application\UI\Control;
use Nette\Localization\ITranslator;

/**
 * Drobeckova navigace
 *
 * @author Attreid <attreid@gmail.com>
 */
class Breadcrumb extends Control
{

	/**
	 * Text pred navigaci
	 * @var string
	 */
	private $title;

	/**
	 * Linky v navigaci
	 * @var Link[]
	 */
	private $links = [];

	/**
	 * Oddelovac
	 * @var string
	 */
	private $delimiter = '»';

	/** @var ITranslator */
	private $translator;

	/**
	 * Zobrazi pokud obsahuje pouze jeden link
	 * @var bool
	 */
	private $view = false;

	public function __construct(?ITranslator $translator)
	{
		parent::__construct();
		$this->translator = $translator;
	}

	/**
	 * Nastavi translator
	 * @param ITranslator $translator
	 */
	public function setTranslator(ITranslator $translator = null): void
	{
		$this->translator = $translator;
	}

	/**
	 * Nastavi text pred navigaci
	 * @param string $title
	 */
	public function setTitle(string $title): void
	{
		$this->title = $this->translator !== null ? $this->translator->translate($title) : $title;
	}

	/**
	 * Nastavi oddelovac
	 * @param string $delimiter
	 */
	public function setDelimiter(string $delimiter): void
	{
		$this->delimiter = $delimiter;
	}

	/**
	 * Zobrazi i tehdy pokud ma jen jeden link
	 */
	public function always(): void
	{
		$this->view = true;
	}

	/**
	 * Prida polozku do navigace
	 * @param string $name
	 * @param string $link
	 * @param array $arguments
	 * @return Link
	 */
	public function addLink(string $name, string $link = null, array $arguments = []): Link
	{
		$name = $this->translator !== null ? $this->translator->translate($name) : $name;
		return $this->addLinkUntranslated($name, $link, $arguments);
	}

	/**
	 * Prida polozku do navigace (bez prekladu jmena)
	 * @param string $name
	 * @param string $link
	 * @param array $arguments
	 * @return Link
	 */
	public function addLinkUntranslated(string $name, string $link = null, array $arguments = []): Link
	{
		return $this->links[] = new Link($name, $link, $arguments);
	}

	public function render(array $args = []): void
	{
		$template = $this->template;
		$template->setFile(__DIR__ . '/breadcrumb.latte');
		$template->title = $this->title;
		$template->links = $this->links;
		$template->delimiter = $this->delimiter;
		$template->view = (!empty($this->title) || count($this->links) > 1 || $this->view) && count($this->links) > 0;
		$template->args = $args;
		$template->render();
	}
}

interface IBreadcrumbFactory
{
	public function create(): Breadcrumb;
}