<?php
namespace Lab123\Odin\Uploads;

use Illuminate\Contracts\Filesystem\Filesystem as FilesystemContract;
use Intervention\Image\ImageManagerStatic as ImageManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\Storage;
use App;

class Image
{

    /**
     * Path to upload
     *
     * @var $path
     */
    protected $path;

    /**
     * Image name
     *
     * @var $name
     */
    protected $name;

    /**
     * Original image
     *
     * @var $originalImage
     */
    protected $originalImage;

    /**
     * Formated Image
     *
     * @var $image
     */
    protected $image;

    /**
     * Formated Thumbnaill
     *
     * @var $thumbnaill
     */
    protected $thumbnaill;

    /**
     * Visibility file
     *
     * @var $visibility
     */
    protected $visibility = FilesystemContract::VISIBILITY_PRIVATE;

    /**
     * Properties to format Image
     *
     * @var $properties array
     */
    protected $properties = [
        'format' => 'jpg',
        'quality' => '75',
        'width' => '1000',
        'height' => null
    ];

    /**
     * Properties to format Thumbnaill
     *
     * @var $thumbnaillProperties array
     */
    protected $thumbnaillProperties = [
        'prefix' => 'thumb',
        'width' => '200',
        'height' => null
    ];

    /**
     * Create image in server (upload)
     *
     * @return void
     */
    public function create($file, $name = '')
    {
        $this->fill(compact('file', 'name'));

        if ($this->upload($this->getDirBeforeAlbum(), $this->getPayload($this->image))) {
            return $this->getFullName();
        }

        return false;
    }

    /**
     * Create thumbnaill in server (upload)
     *
     * @return void
     */
    public function thumbnaillCreate()
    {
        $this->thumbnaill = $this->format($this->image, $this->thumbnaillProperties);

        return $this->upload($this->getFullPathThumbnail(), $this->getPayload($this->thumbnaill));
    }

    /**
     * Remove image in server (upload)
     *
     * @return void
     */
    public function remove($imageName)
    {
        list ($this->name) = explode('.', $imageName);

        if (Storage::disk('s3')->has($this->getDirBeforeAlbum())) {
            Storage::delete($this->getDirBeforeAlbum());
        }

        if (Storage::disk('s3')->has($this->getFullPathThumbnail())) {
            Storage::delete($this->getFullPathThumbnail());
        }
    }

    /**
     * Upload image to path
     *
     * @return void
     */
    private function upload($path, $payload)
    {
        return Storage::disk('s3')->put($path, $payload, $this->visibility);
    }

    /**
     * Format image (format, resize, etc)
     *
     * @return void
     */
    public function format($image, array $properties)
    {
        if (key_exists('format', $properties)) {
            $image->encode($properties['format'], $properties['quality']);
        }

        if (key_exists('width', $properties)) {
            $image->resize($properties['width'], $properties['height'], function ($constraint) {
                $constraint->aspectRatio();
            });
        }

        return $image;
    }

    /**
     * Get full name (name and extension)
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->name . '.' . $this->properties['format'];
    }

    /**
     * Get Path
     *
     * @return string
     */
    public function getPath()
    {
        return App::environment() . $this->path;
    }

    /**
     * Get directory before album directory
     *
     * @return string
     */
    public function getDirBeforeAlbum()
    {
        return $this->getPath() . $this->getFullName();
    }

    /**
     * Get full path file
     *
     * @return string
     */
    public function getFullPath($file = '')
    {
        $this->name = ($file) ? $file : $this->name;

        return config('odin.assetsUrl') . $this->getPath() . $this->name;
    }

    /**
     * Get full path Thumbnail
     *
     * @return string
     */
    public function getFullPathThumbnail()
    {
        return $this->getPath() . $this->getThumbnaillPrefix() . $this->getFullName();
    }

    /**
     * Get prefix of Thumbnail
     *
     * @return string
     */
    public function getThumbnaillPrefix()
    {
        return ($this->thumbnaillProperties['prefix']) ? $this->thumbnaillProperties['prefix'] . '-' : '';
    }

    /**
     * Payload of image
     *
     * @return string
     */
    public function getPayload($image)
    {
        return (string) $image->encode();
    }

    /**
     * Fill object
     *
     * @return void
     */
    protected function fill($array)
    {
        if (is_null($array['file'])) {
            return;
        }

        $this->originalImage = ImageManager::make($array['file']);
        $this->image = $this->format($this->originalImage, $this->properties);

        $this->name = ($array['name']) ? $array['name'] : uniqid();
    }
}


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

namespace justso\justtexts;

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

/**
 * Handles requests regarding generated website pages.
 *
 * @package    justso\service
 */
class PageService extends RestService
{
    /**
     * @var PageList
     */
    private $pageList;

    /**
     * Initializes the service.
     *
     * @param SystemEnvironmentInterface $environment
     */
    public function __construct(SystemEnvironmentInterface $environment)
    {
        parent::__construct($environment);
        $this->pageList = new PageList($environment);
    }

    /**
     * Sets the pageList.
     *
     * @param PageList $pageList
     */
    public function setPageList(PageList $pageList)
    {
        $this->pageList = $pageList;
    }

    /**
     * Yields a list of pages or a single page, if a page name is specified in the service name.
     */
    public function getAction()
    {
        $id = $this->getPageId();
        if ($id !== null) {
            $result = $this->pageList->getPage($id)->getJSON();
        } else {
            $result = array();
            foreach ($this->pageList->getPages() as $pageName) {
                $result[] = $this->pageList->getPage($pageName)->getJSON();
            }
        }
        $this->environment->sendJSONResult($result);
    }

    /**
     * Creates a new page
     */
    public function postAction()
    {
        $request = $this->environment->getRequestHelper();
        $id = $request->getIdentifierParam('name');
        try {
            $this->pageList->getPage($id);
        } catch (InvalidParameterException $e) {
            $page = $this->pageList->addPageFromRequest($id, $request);
            $this->environment->sendJSONResult($page->getJSON());
            return;
        }
        throw new InvalidParameterException("Page already exists");
    }

    public function putAction()
    {
        $request = $this->environment->getRequestHelper();
        $id = $this->getPageId();
        $this->pageList->getPage($id);
        $newName = $request->getIdentifierParam('name');
        if ($id != $newName) {
            if ($this->pageList->getPage($newName)) {
                throw new InvalidParameterException("Page already exists");
            }
            $this->pageList->renamePage($id, $newName);
        }
        $page = $this->pageList->changePageFromRequest($newName, $request);
        $this->environment->sendJSONResult($page->getJSON());
    }

    public function deleteAction()
    {
        $id = $this->getPageId();
        $this->pageList->deletePage($id);

        $arguments = [$this->environment, $id];
        /** @var \justso\justtexts\TextInterface $pageTexts */
        $pageTexts = $this->environment->getDIC()->get('\justso\justtexts\Text', $arguments);
        $pageTexts->removeAll();

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

    /**
     * Checks if the page is contained in service name or specified in parameter 'id' and returns the value then.
     *
     * @return mixed
     */
    private function getPageId()
    {
        if (preg_match('/\/page\/(\w+)$/', $this->name, $matches)) {
            $id = $matches[1];
        } else {
            $id = $this->environment->getRequestHelper()->getIdentifierParam('id', null, true);
        }
        return $id;
    }
}


<?php
namespace AuthModule\Service;

use Zend\Authentication\Adapter\AdapterInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use AuthModule\AuthenticationService;
use Zend\Authentication\Storage\Session;
use Zend\Session\SessionManager;

/**
 * Class AuthenticationServiceFactory
 */
class AuthenticationServiceFactory implements FactoryInterface
{
    /**
     * Config Key
     *
     * @var string
     */
    protected $configKey = 'authentication';

    /**
     * Config
     *
     * @var array
     */
    protected $config;

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return AuthenticationService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $this->getConfig($serviceLocator);
        $authService = new AuthenticationService();

        $sessionStorageConfig = [
            'namespace' => __NAMESPACE__,
            'member'    => null,
        ];
        if (isset($config['session_storage']) && is_array($config['session_storage'])) {
            $sessionStorageConfig = array_merge($sessionStorageConfig, $config['session_storage']);
        }

        /** @var $sessionManager SessionManager */
        $sessionManager = $serviceLocator->get('Zend\Session\SessionManager');

        $authService->setStorage(
            new Session($sessionStorageConfig['namespace'], $sessionStorageConfig['member'], $sessionManager)
        );

        if (isset($config['adapter']) && is_string($config['adapter']) && $serviceLocator->has($config['adapter'])) {
            /** @var $adapter AdapterInterface */
            $adapter = $serviceLocator->get($config['adapter']);
            $authService->setAdapter($adapter);
        }

        return $authService;
    }

    /**
     * Get auth configuration, if any
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return array
     */
    protected function getConfig(ServiceLocatorInterface $serviceLocator)
    {
        if ($this->config !== null) {
            return $this->config;
        }

        if (!$serviceLocator->has('Config')) {
            $this->config = [];
            return $this->config;
        }

        $config = $serviceLocator->get('Config');
        if (!isset($config[$this->configKey])
            || !is_array($config[$this->configKey])
        ) {
            $this->config = [];
            return $this->config;
        }

        $this->config = $config[$this->configKey];
        return $this->config;
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Value\Tv;

use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;

/**
 * Calculate TV on the compressed downline tree.
 *
 * @deprecated use \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Tv
 */
class Calc
{
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpDwnlTree;

    public function __construct(
        \Praxigento\Downline\Api\Helper\Tree $hlpDwnlTree
    )
    {
        $this->hlpDwnlTree = $hlpDwnlTree;
    }

    /**
     * Calculate TV for the downline tree.
     *
     * @param \Praxigento\BonusHybrid\Repo\Data\Downline[] $dwnlBonus
     * @return \Praxigento\BonusHybrid\Repo\Data\Downline[] updated tree (with TV)
     */
    public function exec($dwnlBonus)
    {
        $result = [];
        $mapById = $this->hlpDwnlTree->mapById($dwnlBonus, EBonDwnl::A_CUST_REF);
        $mapTeams = $this->hlpDwnlTree->mapByTeams($dwnlBonus, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF);
        /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $one */
        foreach ($dwnlBonus as $one) {
            $custId = $one->getCustomerRef();
            /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $cust */
            $cust = $mapById[$custId];
            /* initial TV equal to own PV */
            $tv = $cust->getPv();
            if (isset($mapTeams[$custId])) {
                /* add PV of the front line team (first generation) */
                $frontTeam = $mapTeams[$custId];
                foreach ($frontTeam as $teamMemberId) {
                    /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $member */
                    $member = $mapById[$teamMemberId];
                    $memberPv = $member->getPv();
                    $tv += $memberPv;
                }
            }
            $cust->setTv($tv);
            $result[$custId] = $cust;
        }
        return $result;
    }
}


<?php

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

namespace ItePHP\Validator;

/**
 * Validator for file
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class FileValidator extends ValidatorAbstract{

	/**
	 * {@inheritdoc}
	 */
	public function validate($value){

		$empty=false;

		try{
			$empty=$this->getOption('empty');
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		if(!$value && $empty){
            return null;
		}

		if(!$value){
			return 'File not uploaded.';
		}

		if($value->isError()){
			return $value->getError();
		}

		try{
			$accept=$this->getOption('accept');
			if(!preg_match('/'.str_replace(array('*','/'),array('.+','\\/'),$accept).'/' ,$value->getExtension())){
				return 'Invalid file type.';
			}
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		try{
			$maxSize=$this->getOption('maxSize');
			if($value->getSize()>$maxSize){
				return 'File is too large.';
			}
		}
		catch(ValueNotFoundException $e){
			//ignore
		}
        return null;
	}
}


<?php

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

use \Venus\core\Config as Config;
use \Venus\lib\Cache\Apc as Apc;
use \Venus\lib\Cache\File as CacheFile;
use \Venus\lib\Cache\Memcache as CacheMemcache;
use \Venus\lib\Cache\Redis as Redis;
use \Venus\lib\Cache\Mock as Mock;

/**
 * This class manage the Cache
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Cache
{
	/**
	 * type of cache (memcache/file)
	 *
	 * @access private
	 * @var    string
	 */
	private static $_sTypeOfCache = 'file';

	/**
	 * type of cache (memcache/file)
	 *
	 * @access private
	 * @var    array
	 */
	private static $_aCache = array();

	/**
	 * set the cache that we would use
	 *
	 * @access private
	 * @param  string $sCacheName name of cache
	 * @return object
	 */
	public static function setCacheType(string $sCacheName)
	{
		if ($sCacheName === 'file') { self::$_sTypeOfCache = 'file'; }
		else if ($sCacheName === 'memcache') { self::$_sTypeOfCache = 'memcache'; }
		else if ($sCacheName === 'apc') { self::$_sTypeOfCache = 'apc'; }
		else if ($sCacheName === 'redis') { self::$_sTypeOfCache = 'redis'; }
		else { self::$_sTypeOfCache = 'mock'; }
	}

	/**
	 * set a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  mixed $mValue value of this sesion var
	 * @param  int $iFlag unused
	 * @param  int $iExpire expiration of cache
	 * @return void
	 */
	public static function set(string $sName, $mValue, int $iFlag = 0, int $iExpire = 0)
	{
		return self::_getCacheObject()->set($sName, $mValue, $iFlag, $iExpire);
	}

	/**
	 * get a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @param  int $iFlags flags
	 * @param  int $iTimeout expiration of cache
	 * @return bool
	 */
	public static function get(string $sName, int &$iFlags = null, int $iTimeout = 0) : bool
	{
		return self::_getCacheObject()->get($sName, $iFlags, $iTimeout);
	}

	/**
	 * delete a value
	 *
	 * @access public
	 * @param  string $sName name of the session
	 * @return boolean
	 */
	public static function delete(string $sName) : bool
	{
		return self::_getCacheObject()->delete($sName);
	}

	/**
	 * flush the cache
	 *
	 * @access public
	 * @return boolean
	 */
	public static function flush() : bool
	{
		return self::_getCacheObject()->flush();
	}

	/**
	 * initialize the cache class and get the good object
	 *
	 * @access private
	 * @return object
	 */
	private static function _getCacheObject()
	{
		if (self::$_sTypeOfCache === 'file') {

			if (!isset(self::$_aCache['file'])) { self::$_aCache['file'] = new CacheFile; }

			return self::$_aCache['file'];
		}
		else if (self::$_sTypeOfCache === 'memcache') {

			if (!isset(self::$_aCache['memcache'])) {

			    $oDbConf = Config::get('Memcache')->configuration;

			    if (isset($oDbConf->port)) { $sPort = $oDbConf->port; }
			    else { $sPort = null; }

			    if (isset($oDbConf->timeout)) { $iTimeout = $oDbConf->timeout; }
			    else { $iTimeout = null; }

			    self::$_aCache['memcache'] = new CacheMemcache($oDbConf->host, $sPort, $iTimeout);
			}

			return self::$_aCache['memcache'];
		}
		else if (self::$_sTypeOfCache === 'apc') {

			if (!isset(self::$_aCache['apc'])) { self::$_aCache['apc'] = new Apc; }

			return self::$_aCache['apc'];
		}
		else if (self::$_sTypeOfCache === 'redis') {

			if (!isset(self::$_aCache['redis'])) {

			    $oDbConf = Config::get('Redis')->configuration;
			    self::$_aCache['memcache'] = new Redis($oDbConf);
			}

			return self::$_aCache['redis'];
		}
		else if (self::$_sTypeOfCache === 'mock') {

			if (!isset(self::$_aCache['mock'])) { self::$_aCache['mock'] = new Mock; }

			return self::$_aCache['mock'];
		}
	}
}


<?php

namespace nadir2\core;

/**
 * The application helper class, which provides config data loading and general
 * access to them. It's realized as Singleton.
 * @author Leonid Selikhov.
 */
class AppHelper implements RunnableInterface
{
    use \nadir2\tools\AccessorsTrait;

    /**
     * @var string The path to the application root.
     * @get
     * @isset
     */
    protected $appRoot = null;

    /**
     * @var string The path to the configuration file.
     * @get
     * @isset
     */
    protected $configFile = null;

    /**
     * @var string The route configuration.
     * @accessors
     */
    public $routeConfig = null;

    /** @var self The singleton-object of current class. */
    private static $instance = null;

    /** @var mixed[] The configuration data set. */
    private $configSet = [];

    /** @var string The site basic URL. */
    private $siteBaseUrl = '';

    /**
     * The closed class constructor. It determines  the site basic URL.
     * @return self
     */
    private function __construct()
    {
        $this->siteBaseUrl = self::getBaseUrl();
    }

    /**
     * It retrurns the current class instance.
     * @return self
     */
    public static function getInstance(): self
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * This is mutator-method. It sets the path to the root of application.
     * @param string $appRoot The path to the application root.
     * @return self
     */
    public function setAppRoot(string $appRoot): self
    {
        $this->appRoot = $appRoot;
        return self::$instance;
    }

    /**
     * It sets the path to the main configuration of application file relative
     * to its root.
     * @param string $filePath
     * @return self
     */
    public function setConfigFile(string $filePath): self
    {
        $this->configFile = $filePath;
        return self::$instance;
    }

    /**
     * It loads main file of configuration and checks for validity.
     * @return void
     * @throws Exception It's thrown if some errors with the main configuration
     * file occurred.
     */
    public function run(): void
    {
        if (!$this->isAppRootSet()) {
            throw new Exception("The application root wasn't defined.");
        }
        if (!$this->isConfigFileSet()) {
            throw new Exception("The main config file wasn't defined.");
        }
        $configPath = $this->getAppRoot().$this->getConfigFile();
        if (!is_readable($configPath)) {
            throw new Exception("It's unable to load ".$configPath
                .'as main config file.');
        }
        $config = require_once $configPath;
        if (!is_array($config)) {
            throw new Exception('The main config must be an array.');
        }
        $this->configSet = $config;
    }

    /**
     * It returns the config value by passed name or all config set if it wasn't
     * specified.
     * @param string $sName The config name.
     * @return mixed|null
     */
    public function getConfig(string $sName = '')
    {
        if (empty($sName)) {
            return $this->configSet;
        } elseif (isset($this->configSet[$sName])) {
            return $this->configSet[$sName];
        } else {
            return null;
        }
    }

    /**
     * The method returns the whole set of application configurations.
     * @return array
     */
    public function getAllConfigs(): array
    {
        return $this->getConfig();
    }

    /**
     * It determines the basic site URL.
     * @return string|null
     */
    private static function getBaseUrl(): ?string
    {
        $serverName = filter_input(
            \INPUT_SERVER,
            'SERVER_NAME',
            \FILTER_SANITIZE_STRING
        );
        if (!empty($serverName)) {
            $https = filter_input(\INPUT_SERVER, 'HTTPS', \FILTER_SANITIZE_STRING);
            $protocol = !empty($https) && strtolower($https) === 'on' ? 'https'
                : 'http';
            return $protocol.'://'.$serverName;
        }
        return null;
    }

    /**
     * This is method-accessor to basic site URL.
     * @return string|null
     */
    public function getSiteBaseUrl(): ?string
    {
        return $this->siteBaseUrl;
    }

    /**
     * The method returns absolute or relative path (URL) to the component by
     * passed name. The absolute URL used to determs path to assets (media-data)
     * as usual.
     * @param string $name The component name.
     * @param boolean $asAbsolute The optional flag is equal true by default.
     * @return string|null
     */
    public function getComponentUrl(string $name, bool $asAbsolute = true): ?string
    {
        $rootMap = $this->getConfig('componentsRootMap');
        $siteUrl = $asAbsolute ? $this->siteBaseUrl : '';
        return isset($rootMap[$name]) ? $siteUrl.$rootMap[$name] : null;
    }

    /**
     * The method returns full path to the parent directory of component by its
     * name.
     * @param string $name The component name.
     * @return string|null
     */
    public function getComponentRoot(string $name): ?string
    {
        $rootMap = $this->getConfig('componentsRootMap');
        return isset($rootMap[$name]) ? $this->getAppRoot().$rootMap[$name] : null;
    }
}


<?php

namespace SilverCommerce\QuantityField\Forms;

use SilverStripe\Forms\NumericField;

/**
 * Text input field with validation for numeric values.
 *
 * @package quantityfield
 */
class QuantityField extends NumericField
{
    /**
     * Construct this field (we override the default to set a default value)
     *
     * @param [type] $name
     * @param [type] $title
     * @param string $value
     * @param [type] $maxLength
     * @param [type] $form
     */
    public function __construct($name, $title = null, $value = 1, $maxLength = null, $form = null)
    {
        parent::__construct($name, $title, $value);
    }

    public function Type()
    {
        return 'quantity numeric text';
    }

    /**
     * PHP Validation
     *
     * @return boolean
     * @throws Exception
    **/
    public function validate($validator)
    {
        $value = $this->Value() + 0;

        if(is_int($value)) {
            return true;
        }

        $validator->validationError(
            $this->name,
            _t(
                'Checkout.VALIDATION', '{value} is not a valid number, only whole numbers can be accepted for this field',
                array('value' => $value)
            ),
            "validation"
        );

        return false;
    }

    public function dataValue()
    {
        $value = $this->Value();
        $value =  (is_numeric($value)) ? $value : 0;

        return $this->cast($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\Theme;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\PageCollection\PagesCollectionParser;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

/**
 * Class ThemeAligner is the object assigned to align the site that handles a theme or a site that uses a theme when the theme had changed.
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Theme
 */
class ThemeAligner extends ThemeBase
{
    /**
     * Aligns the site slots according with the changes made with the theme in use
     *
     * @param \RedKiteCms\Content\PageCollection\PagesCollectionParser $pagesCollectionParser
     */
    public function align(PagesCollectionParser $pagesCollectionParser)
    {
        $themeSlots = $this->findSlotsInTemplates();
        $slots = $this->mergeSlotsByStatus($themeSlots);
        if (!array_key_exists("page", $slots)) {
            return;
        }
        $pageSlots = $slots["page"];
        unset($slots["page"]);

        $files = $this->removeCommonSlots($slots);
        $files = array_merge($files, $this->removePageSlots($pagesCollectionParser, $pageSlots));

        if (!empty($files)) {
            $fs = new Filesystem();
            $fs->remove($files);
        }
    }

    private function mergeSlotsByStatus($templates)
    {
        $slots = array();
        foreach ($templates as $template) {
            foreach ($template as $templateSlots) {
                $slots = array_merge_recursive($slots, $templateSlots);
            }
        }

        return $slots;
    }

    private function removeCommonSlots($slots)
    {
        $filesToRemove = array();
        $slotsDir = $this->configurationHandler->siteDir() . '/slots';
        $finder = new Finder();
        $slotFolders = $finder->directories()->depth(0)->in($slotsDir);
        foreach ($slotFolders as $slotFolder) {
            $slotFolder = (string)$slotFolder;
            $repeat = "language";
            if (is_dir($slotFolder . '/active')) {
                $repeat = "site";
            }

            $slotFolderName = basename($slotFolder);
            if (!in_array($slotFolderName, $slots[$repeat])) {
                $filesToRemove[] = $slotFolder;
            }
        }

        return $filesToRemove;
    }

    private function removePageSlots(PagesCollectionParser $pagesCollectionParser, $slots)
    {
        $filesToRemove = array();
        $pagesDir = $this->configurationHandler->pagesDir();
        $pages = $pagesCollectionParser->pages();
        $languages = $this->configurationHandler->languages();
        foreach ($pages as $page) {
            foreach ($languages as $language) {
                $pageDir = sprintf('%s/%s/%s', $pagesDir, $page["name"], $language);

                $finder = new Finder();
                $slotFolders = $finder->directories()->depth(0)->in($pageDir);
                foreach ($slotFolders as $slotFolder) {
                    $slotFolderName = basename($slotFolder);
                    if (!in_array($slotFolderName, $slots)) {
                        $filesToRemove[] = (string)$slotFolder;
                    }
                }
            }
        }

        return $filesToRemove;
    }
}


<?php
	/**
	 * Created by IntelliJ IDEA.
	 * User: Gabriel Peleskei
	 * Date: 25.11.2018
	 */

	namespace GabrielPeleskei\InterruptHandler;

	use function call_user_func_array;
	use Closure;
	use function is_array;
	use function is_callable;
	use function str_replace;
	use function uniqid;

	/**
	 * Class Listener
	 *
	 * Is returned by {@see Handler::register()}
	 *
	 * @package GabrielPeleskei\InterruptHandler
	 *
	 * @property bool $interrupt
	 * @property-read string $name
	 * @property-set  string|null $name
	 * @property-read string $id
	 * @property-read array $signals
	 * @method string name($name=null)
	 */
	class Listener {
		/**
		 * @var string generated id
		 */
		protected $_id;
		/**
		 * @var array Signals to register against
		 */
		protected $_signals   = [];
		/**
		 * @var int current interrupt, 0 none
		 */
		protected $_interrupt = 0;
		/**
		 * @var Callable|Closure|array method/function to call on interruption
		 */
		protected $_caller;
		/**
		 * @var bool
		 */
		protected $_resetAfter = false;
		/**
		 * @var string|null
		 */
		protected $_name;

		/**
		 * Listener constructor.
		 * @param array $signals singals to register against
		 */
		public function __construct(array $signals) {
			$this->_id      = str_replace('.', '', uniqid('sig_lst_', true));
			$this->_signals = $signals;
		}

		/**
		 * @param int $signal test if signal is part of this class
		 * @return bool true if registered
		 */
		public function hasSignal($signal) {
			return in_array($signal, $this->_signals, true);
		}

		/**
		 * @param null|bool $shouldReset if null return current value, else sets value beforehand
		 * @return bool
		 */
		public function resetAfter($shouldReset = null) {
			if (null !== $shouldReset) {
				$this->_resetAfter = true;
			}
			return $this->_resetAfter;
		}

		/**
		 * @param Callable|Closure|array $callableOrArray method/function to call on interruption
		 */
		public function setNotification($callableOrArray) {
			if (is_callable($callableOrArray) || is_array($callableOrArray) || ($callableOrArray instanceof Closure)) {
				$this->_caller = $callableOrArray;
			}
		}

		/**
		 * resets the interrupt signal
		 */
		public function reset() {
			$this->_interrupt = 0;
		}

		/**
		 * Called on interruption
		 * @return null|int
		 */
		public function notify() {
			declare(ticks=1);
			if (is_array($this->_caller) && !empty($this->_caller)) {
				// array
				return call_user_func_array($this->_caller, [$this->_interrupt]);
			} else if ($this->_caller instanceof Closure) {
				// closure
				return $this->_caller->call($this, $this->_interrupt);
			} else if (is_callable($this->_caller)) {
				// callable
				$cl = Closure::fromCallable($this->_caller);
				return $cl->call($this,$this->_interrupt);
			}
			return null;
		}

		/**
		 * Magic access
		 * @param string $name
		 * @return array|bool|null|string
		 */
		public function __get($name) {
			// interrupt state
			if ($name === 'interrupt') {
				declare(ticks=1);
				$return = (bool)$this->_interrupt;
				if ($this->_resetAfter) {
					$this->reset();
				}
				return $return;
			}
			// id
			if ($name === 'id') {
				return $this->_id;
			}
			// list of signals (registered)
			if ($name === 'signals') {
				return $this->_signals;
			}
			if ( $name === 'name') {
				return $this->name();
			}
			return null;
		}

		/**
		 * Magic setter
		 * @param string $name
		 * @param mixed $value
		 */
		public function __set($name, $value) {
			if ($name === 'interrupt' && $this->hasSignal($value)) {
				// set interrupt signal and notify
				$this->_interrupt = (int)$value;
				$this->notify();
			} else if ($name === 'name') {
				$this->name($value);
			}
		}

		/**
		 * @param $name
		 * @param $arguments
		 * @return string
		 */
		public function __call($name, $arguments) {
			if ($name === 'name') {
				if ( isset($arguments[0]) && null !== $arguments[0]) {
					$this->_name = $arguments[0];
				}
				return $this->_name ?: $this->_id;
			}
		}

		/**
		 * @return string
		 * @see Listener::$name
		 */
		public function __toString() {
			return $this->name;
		}
	}


<?php

namespace SwooleFlierMouseBase;

use SwooleFlierMouseBase\http\Request;
use SwooleFlierMouseBase\interfaces\Conf as ConfI;
use Symfony\Component\Yaml\Yaml;

class Conf implements ConfI
{
	static public    $conf      = NULL;
	static protected $conf_path = NULL;
	static public    $temp      = NULL;
	static public    $root      = NULL;
	static protected $daemonize = FALSE;

	static public function get ($key = FALSE)
	{
		if (NULL === self::$conf) {
			self::read();
		}

		return self::$conf[ $key ];
	}

	static public function read ($conf_path = FALSE)
	{
		if (FALSE === $conf_path && NULL === self::$conf_path) {
			throw new SwooleFlierMouseBaseException('conf file not set!');
		}

		if ($conf_path) {
			if (!file_exists($conf_path)) {
				throw new SwooleFlierMouseBaseException("conf file {$conf_path} not exists!");
			}
		}

		self::$conf_path = $conf_path;
		self::$conf      = Yaml::parse(file_get_contents(self::$conf_path));

		self::$root = realpath(__DIR__ . '/../');
		self::$temp = self::$root . DIRECTORY_SEPARATOR . self::get('temp');

		if (!is_dir(self::$temp)) {
			mkdir(self::$temp, 0777, TRUE);
		}
	}

	/**
	 * 创建临时文件
	 *
	 * @param $session_id
	 * @param $name
	 * @param $context
	 *
	 * @return bool|string
	 */
	static public function createTempFile ($session_id, $name, $context)
	{
		$dir = self::$temp . DIRECTORY_SEPARATOR . $session_id;
		if (!is_dir($dir)) {
			mkdir($dir, 0777, TRUE);
		}
		$file_path_name = $dir . DIRECTORY_SEPARATOR . uniqid() . "-{$name}";
		if (file_put_contents($file_path_name, $context)) {
			return $file_path_name;
		}
		else {
			return FALSE;
		}
	}

	/**
	 * 删除目录
	 *
	 * @param $dir
	 *
	 * @return bool
	 */
	public static function deleteDir ($dir)
	{
		if (!is_dir($dir)) {
			return FALSE;
		}

		$dh = opendir($dir);
		while ($file = readdir($dh)) {
			if ($file != "." && $file != "..") {
				$full_path = $dir . "/" . $file;
				if (!is_dir($full_path)) {
					unlink($full_path);
				}
				else {
					self::delete_dir($full_path);
				}
			}
		}
		closedir($dh);
		if (rmdir($dir)) {
			return TRUE;
		}
		else {
			return FALSE;
		}
	}

	public static function setDaemonize ($daemonize = TRUE)
	{
		self::$daemonize = $daemonize;
	}

	public static function isDaemonize ()
	{
		return self::$daemonize;
	}

}


<?php
declare(strict_types=1);

namespace Ciebit\Stories\Storages\Database;

use PDOStatement;

use function implode;

abstract class SqlFilters
{
    static private $valueKey = 0;

    private $bindList; #:Array
    private $filtersSql; #:Array
    private $limit; #:int
    private $offset; #:int

    protected function addBind(string $key, int $type, $value): self
    {
        $this->bindList[] = [
            'key' => $key,
            'value' => $value,
            'type' => $type
        ];
        return $this;
    }

    protected function addFilter(string $key, string $sql, int $type, $value): self
    {
        $this->addBind($key, $type, $value);
        $this->addSqlFilter($sql);
        return $this;
    }

    protected function addSqlFilter(string $sql): self
    {
        $this->filtersSql[] = $sql;
        return $this;
    }

    protected function bind(PDOStatement $statment): self
    {
        if (! is_array($this->bindList)) {
            return $this;
        }

        foreach ($this->bindList as $bind) {
            $statment->bindValue(":{$bind['key']}", $bind['value'], $bind['type']);
        }

        return $this;
    }

    protected function generateSqlFilters(): string
    {
        if (empty($this->filtersSql)) {
            return '1';
        }
        return implode(' AND ', $this->filtersSql);
    }

    protected function generateSqlLimit(): string
    {
        $init = (int) $this->offset;
        $sql =
            $this->limit === null
            ? ''
            : "LIMIT {$init},{$this->limit}";
        return $sql;
    }

    protected function getValueKey(): string
    {
        return 'value_'. self::$valueKey++;
    }

    protected function setLimit(int $total): self
    {
        $this->limit = $total;
        return $this;
    }

    protected function setOffset(int $lineInit): self
    {
        $this->offset = $lineInit;
        return $this;
    }
}


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

/**
 * StaffServiceProvider.php.
 *
 * This file is part of the 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.
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\Staff\Session;
use EasyWeChat\Staff\Staff;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class StaffServiceProvider.
 */
class StaffServiceProvider 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['staff'] = function ($pimple) {
            return new Staff($pimple['access_token']);
        };

        $pimple['staff_session'] = $pimple['staff.session'] = function ($pimple) {
            return new Session($pimple['access_token']);
        };
    }
}


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

use JMS\Serializer\SerializerInterface;
use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\EventSystem\Event\Render\PageRenderedEvent;
use RedKiteCms\EventSystem\RenderEvents;
use RedKiteCms\Exception\Publish\PageNotPublishedException;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Finder\Finder;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class Page is the object assigned to handle a website page
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\FilesystemEntity
 */
class Page extends Entity implements RenderableInterface
{
    /**
     * @type string
     */
    private $username;
    /**
     * @type array
     */
    private $pageAttributes = array();
    /**
     * @type array
     */
    private $seoAttributes = array();
    /**
     * @type array
     */
    private $pageSlots = array();
    /**
     * @type array
     */
    private $commonSlots = array();
    /**
     * @type string
     */
    private $pageName = null;
    /**
     * @type string
     */
    private $language = null;
    /**
     * @type string
     */
    private $country = null;
    /**
     * @type string
     */
    private $currentLanguage = null;
    /**
     * @type \RedKiteCms\FilesystemEntity\SlotParser
     */
    private $slotParser;

    /**
     * Constructor
     *
     * @param \JMS\Serializer\SerializerInterface $serializer
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver
     * @param \RedKiteCms\FilesystemEntity\SlotParser $slotParser
     */
    public function __construct(
        SerializerInterface $serializer,
        OptionsResolver $optionsResolver,
        SlotParser $slotParser
    ) {
        parent::__construct($serializer, $optionsResolver);

        $this->slotParser = $slotParser;
    }

    /**
     * Returns the page attributes
     *
     * @return array
     */
    public function getPageAttributes()
    {
        return $this->pageAttributes;
    }

    /**
     * Sets the seo attributes for this page
     *
     * @return $this
     */
    public function setSeoAttributes(array $seoAttributes)
    {
        $this->seoAttributes = $seoAttributes;

        return $this;
    }

    /**
     * Returns the seo attributes for this page
     *
     * @return array
     */
    public function getSeoAttributes()
    {
        return $this->seoAttributes;
    }

    /**
     * Returns the page slots
     *
     * @return array
     */
    public function getPageSlots()
    {
        return $this->pageSlots;
    }

    /**
     * Returns the common slots
     *
     * @return array
     */
    public function getCommonSlots()
    {
        return $this->commonSlots;
    }

    /**
     * Returns page name
     * @return string
     */
    public function getPageName()
    {
        return $this->pageName;
    }

    /**
     * Returns the current page language
     *
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * Returns the current language country
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * returns the full language, combining language and country
     *
     * @return string
     */
    public function getCurrentLanguage()
    {
        return $this->currentLanguage;
    }

    /**
     * {@inheritdoc}
     */
    public function render($sourceDir, array $options, $username = null)
    {
        $this->pageName = $options["page"];
        $this->language = $options["language"];
        $this->country = $options["country"];
        $this->currentLanguage = $this->language . '_' . $this->country;

        $this->username = $username;
        $this->fetchPageAttributes($sourceDir);
        $this->fetchPageBlocks($sourceDir, $options);
    }

    private function fetchPageAttributes($sourceDir)
    {
        $fileName = (null !== $this->username) ? $this->username : 'page';
        $file = sprintf('%s/pages/pages/%s/%s.json', $sourceDir, $this->pageName, $fileName);
        $this->pageAttributes = json_decode(FilesystemTools::readFile($file), true);

        $fileName = (null !== $this->username) ? $this->username : 'seo';
        $file = sprintf('%s/pages/pages/%s/%s/%s.json', $sourceDir, $this->pageName, $this->currentLanguage, $fileName);
        if ($fileName === 'seo' && !file_exists($file)) {
            throw new PageNotPublishedException('production_page_not_available');
        }
        $this->seoAttributes = json_decode(FilesystemTools::readFile($file), true);
    }

    private function fetchPageBlocks($sourceDir, array $options)
    {
        $slotsFolder = sprintf('%s/pages/pages/%s/%s', $sourceDir, $this->pageName, $this->currentLanguage);
        $this->pageSlots = $this->renderSlots($sourceDir, $slotsFolder, $options);

        $slotsFolder = sprintf('%s/slots', $sourceDir, $this->pageName);
        $this->commonSlots = $this->renderSlots($sourceDir, $slotsFolder, $options);
        $this->pageSlots = array_merge($this->pageSlots, $this->commonSlots);
    }

    private function renderSlots($sourceDir, $slotsFolder, array $options)
    {
        $slots = array();
        $finder = new Finder();
        $folders = $finder->directories()->depth(0)->in($slotsFolder);
        foreach ($folders as $folder) {
            $folder = (string)$folder;
            $slotName = basename($folder);
            $options["slot"] = $slotName;
            $slot = new Slot($this->serializer, $this->optionsResolver, $this->slotParser);
            $slot->render($sourceDir, $options, $this->username);
            $slots[$slotName] = $slot;
        }

        return $slots;
    }
}


<?php

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

namespace Predis\Configuration\Option;

use Predis\Cluster\Hash;
use Predis\Configuration\OptionInterface;
use Predis\Configuration\OptionsInterface;

/**
 * Configures an hash generator used by the redis-cluster connection backend.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class CRC16 implements OptionInterface
{
    /**
     * Returns an hash generator instance from a descriptive name.
     *
     * @param OptionsInterface $options     Client options.
     * @param string           $description Identifier of a hash generator (`predis`, `phpiredis`)
     *
     * @return callable
     */
    protected function getHashGeneratorByDescription(OptionsInterface $options, $description)
    {
        if ($description === 'predis') {
            return new Hash\CRC16();
        } elseif ($description === 'phpiredis') {
            return new Hash\PhpiredisCRC16();
        } else {
            throw new \InvalidArgumentException(
                'String value for the crc16 option must be either `predis` or `phpiredis`'
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function filter(OptionsInterface $options, $value)
    {
        if (is_callable($value)) {
            $value = call_user_func($value, $options);
        }

        if (is_string($value)) {
            return $this->getHashGeneratorByDescription($options, $value);
        } elseif ($value instanceof Hash\HashGeneratorInterface) {
            return $value;
        } else {
            $class = get_class($this);
            throw new \InvalidArgumentException("$class expects a valid hash generator");
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefault(OptionsInterface $options)
    {
        return function_exists('phpiredis_utils_crc16')
            ? new Hash\PhpiredisCRC16()
            : new Hash\CRC16();
    }
}


<?php

namespace Webforge\Types;

use Psc\Code\Generate\GClass;
use Psc\Code\Code;
use Webforge\Common\ClassInterface;

class ObjectType extends Type implements ParameterHintedType, DoctrineExportableType, SerializationType {

  /**
   * @var ClassInterface
   */
  protected $class;

  public function __construct(ClassInterface $class = NULL) {
    if (isset($class)) {
      $this->setClass($class);
    }
  }

  public function getName($context = self::CONTEXT_DEFAULT) {
    if ($context === self::CONTEXT_DEBUG)
      return isset($this->class) ? $this->class->getFQN() : 'Object';

    return parent::getName($context);
  }

  public function expandNamespace($namespace) {
    if (isset($this->class) && $this->class->getNamespace() === NULL)
      $this->class->setNameSpace($namespace);
    return $this;
  }

  /**
   * @return NULL|String
   */
  public function getClassFQN() {
    return isset($this->class) ? $this->class->getFQN() : NULL;
  }

  /**
   * @param Webforge\Common\ClassInterface $class
   * @chainable
   */
  public function setClass(ClassInterface $class = NULL) {
    $this->class = $class;
    return $this;
  }

  /**
   * @return ClassInterface
   */
  public function getClass() {
    return $this->class;
  }

  public function getGClass() {
    return $this->class;
  }

  public function hasClass() {
    return isset($this->class);
  }

  /**
   * Gibt den internen PHPTypen des Types zurück
   *
   * ist in diesem falle auch der DocType
   * wenn die Klasse gesetzt ist, wird der Name der Klasse ohne \ Davor zurückgegeben
   */
  public function getPHPType() {
    return isset($this->class) ? $this->class->getFQN() : 'object';
  }

  /**
   * Returns the PHPHint as php code for the Object
   *
   * if class is not known \stdClass is returned
   *
   * e.g. encodeJSON(\stdClass $object)
   *
   * if class is known and namespace context is the same as the class only the relative className will be returned
   *
   * e.g. setPerson(Person $person)
   *
   * if class is known and namespace context is not set the full qualified name with \ in front will be returned
   *
   * e.g. setPerson(\ACME\Entities\Person $person)
   */
  public function getPHPHint($namespaceContext = NULL) {
    if (!isset($this->class)) {
      return '\stdClass';
    }

    if (isset($namespaceContext) && trim($this->class->getNamespace(),'\\') === trim($namespaceContext,'\\')) {
      return $this->class->getName();
    }

    return '\\'.$this->class->getFQN();
  }

  /**
   * @inheritdoc
   */
  public function getParameterHint($useFQN = TRUE) {
    if (!isset($this->class)) {
      return $useFQN ? '\\stdClass' : 'stdClass';
    }

    if ($useFQN) {
      return '\\'.$this->class->getFQN();
    } else {
      return $this->class->getName();
    }
  }

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

  public function getDoctrineExportType() {
    return \Doctrine\DBAL\Types\Type::OBJECT;
  }

  public function getSerializationType() {
    if (isset($this->class)) {
      return $this->class->getFQN();
    } else {
      return NULL;
    }
  }

  public function implementsInterface($FQN) {
    if (!($FQN instanceof ClassInterface)) {
      $FQN = GClassAdapter::newGClass($FQN);
    }

    try {
      return $this->getGClass()->getReflection()->implementsInterface((string) $FQN);
    } catch (\ReflectionException $e) {
      throw new Exception('Cannot reflect class: '.$this->getGClass().' '.$e->getMessage());
    }
  }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Repository;

use Doctrine\ORM\EntityRepository as DoctrineEntityRepository;
use Dothiv\Bundle\ContentfulBundle\Entity\Config;
use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use PhpOption\Option;
use Symfony\Component\Validator\ValidatorInterface;

class DoctrineConfigRepository extends DoctrineEntityRepository implements ConfigRepositoryInterface
{
    /**
     * @var ValidatorInterface
     */
    protected $validator;

    /**
     * @param object     $entity
     * @param array|null $groups The validation groups to validate.
     *
     * @throws InvalidArgumentException if $entity is invalid
     * @return object $entity
     */
    protected function validate($entity, array $groups = null)
    {
        $errors = $this->validator->validate($entity, $groups);
        if (count($errors) != 0) {
            throw new InvalidArgumentException((string)$errors);
        }
        return $entity;
    }

    /**
     * @param ValidatorInterface $validator
     */
    public function setValidator(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function persist(Config $config)
    {
        $this->getEntityManager()->persist($this->validate($config));
        return $this;
    }

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

    /**
     * {@inheritdoc}
     */
    function get($key)
    {
        return Option::fromValue($this->findOneBy(
            array('name' => $key)
        ))->getOrCall(function () use ($key) {
            $config = new Config();
            $config->setName($key);
            return $config;
        });
    }

    /**
     * {@inheritdoc}
     */
    public function getItemByIdentifier($identifier)
    {
        return Option::fromValue($this->get($identifier));
    }
}


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\controllers;

use dektrium\user\Finder;
use dektrium\user\models\Account;
use dektrium\user\models\SettingsForm;
use dektrium\user\Module;
use yii\authclient\ClientInterface;
use yii\base\Model;
use yii\helpers\Url;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * SettingsController manages updating user settings (e.g. profile, email and password).
 *
 * @property \dektrium\user\Module $module
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class SettingsController extends Controller
{
    /** @inheritdoc */
    public $defaultAction = 'profile';

    /** @var Finder */
    protected $finder;

    /**
     * @param string $id
     * @param \yii\base\Module $module
     * @param Finder $finder
     * @param array $config
     */
    public function __construct($id, $module, Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($id, $module, $config);
    }

    /** @inheritdoc */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'disconnect' => ['post']
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow'   => true,
                        'actions' => ['profile', 'account', 'confirm', 'networks', 'connect', 'disconnect'],
                        'roles'   => ['@']
                    ],
                ]
            ],
        ];
    }

    /** @inheritdoc */
    public function actions()
    {
        return [
            'connect' => [
                'class'           => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'connect'],
            ]
        ];
    }

    /**
     * Shows profile settings form.
     * @return string|\yii\web\Response
     */
    public function actionProfile()
    {
        $model = $this->finder->findProfileById(\Yii::$app->user->identity->getId());

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'Your profile has been updated'));
            return $this->refresh();
        }

        return $this->render('profile', [
            'model' => $model,
        ]);
    }

    /**
     * Displays page where user can update account settings (username, email or password).
     * @return string|\yii\web\Response
     */
    public function actionAccount()
    {
        /** @var SettingsForm $model */
        $model = \Yii::createObject(SettingsForm::className());

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            \Yii::$app->session->setFlash('success', \Yii::t('user', 'Your account details have been updated'));
            return $this->refresh();
        }

        return $this->render('account', [
            'model' => $model,
        ]);
    }

    /**
     * Attempts changing user's password.
     * @param  integer $id
     * @param  string  $code
     * @return string
     * @throws \yii\web\HttpException
     */
    public function actionConfirm($id, $code)
    {
        $user = $this->finder->findUserById($id);

        if ($user === null || $this->module->emailChangeStrategy == Module::STRATEGY_INSECURE) {
            throw new NotFoundHttpException;
        }

        $user->attemptEmailChange($code);

        return $this->redirect(['account']);
    }

    /**
     * Displays list of connected network accounts.
     * @return string
     */
    public function actionNetworks()
    {
        return $this->render('networks', [
            'user' => \Yii::$app->user->identity
        ]);
    }

    /**
     * Disconnects a network account from user.
     * @param  integer $id
     * @return \yii\web\Response
     * @throws \yii\web\NotFoundHttpException
     * @throws \yii\web\ForbiddenHttpException
     */
    public function actionDisconnect($id)
    {
        $account = $this->finder->findAccountById($id);
        if ($account === null) {
            throw new NotFoundHttpException;
        }
        if ($account->user_id != \Yii::$app->user->id) {
            throw new ForbiddenHttpException;
        }
        $account->delete();

        return $this->redirect(['networks']);
    }

    /**
     * Connects social account to user.
     * @param  ClientInterface $client
     * @return \yii\web\Response
     */
    public function connect(ClientInterface $client)
    {
        $attributes = $client->getUserAttributes();
        $provider   = $client->getId();
        $clientId   = $attributes['id'];

        $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId);

        if ($account === null) {
            $account = \Yii::createObject([
                'class'     => Account::className(),
                'provider'  => $provider,
                'client_id' => $clientId,
                'data'      => json_encode($attributes),
                'user_id'   => \Yii::$app->user->id,
            ]);
            $account->save(false);
            \Yii::$app->session->setFlash('success', \Yii::t('user', 'Your account has been connected'));
        } else if (null == $account->user) {
            $account->user_id = \Yii::$app->user->id;
            $account->save(false);
        } else {
            \Yii::$app->session->setFlash('error', \Yii::t('user', 'This account has already been connected to another user'));
        }

        $this->action->successUrl = Url::to(['/user/settings/networks']);
    }

    /**
     * Performs ajax validation.
     * @param Model $model
     * @throws \yii\base\ExitException
     */
    protected function performAjaxValidation(Model $model)
    {
        if (\Yii::$app->request->isAjax && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            echo json_encode(ActiveForm::validate($model));
            \Yii::$app->end();
        }
    }
}


<?php namespace ForeverPHP\Http;

use ForeverPHP\Core\Settings;

/**
 * Contiene información de un archivo enviado por el request.
 *
 * @since       Version 0.4.0
 */
class RequestFile {

    private $filename = '';

    private $name = '';

    private $extension = '';

    private $mimetype = '';

    private $realPath = '';

    private $error = null;

    private $size = 0;

    public function __construct($fileInfo) {
        $this->filename = $fileInfo['name'];

        // Valida si el nombre del archivo viene en array
        if (is_array($this->filename)) {
            $this->filename = $this->filename[0];
        }

        // Obtengo el nombre y la extención del archivo
        $nameAndExtension = explode('.', $this->filename);
        $this->name = $nameAndExtension[0];
        $this->extension = $nameAndExtension[1];

        $this->mimetype = $fileInfo['type'];
        $this->realPath = $fileInfo['tmp_name'];
        $this->error = $fileInfo['error'];
        $this->size = $fileInfo['size'];
    }

    public function getFilename() {
        return $this->filename;
    }

    public function getName() {
        return $this->name;
    }

    public function getExtension() {
        return $this->extension;
    }

    public function getMimeType() {
        return $this->mimetype;
    }

    public function getRealPath() {
        return $this->realPath;
    }

    public function hasError() {
        if ($this->error != 0) {
            return true;
        }

        return false;
    }

    public function getSize() {
        return $this->size;
    }

    /**
     * Mueve el archivo a la ruta entregada.
     *
     * @param  string $path
     * @return boolean
     */
    public function move($path, $filename = null) {
        $newFilename = ($filename != null) ? $filename : $this->filename;

        // Valida si la ruta termina con slash
        $lastSlash = substr($path, strlen($path), 1);

        if ($lastSlash !== '/') {
            $path .=  '/';
        }

        // Retorno TRUE si se movio el archivo, de lo contrario FALSE
        $result = move_uploaded_file($this->realPath, $path . $newFilename);

        return $result;
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Basket;

use Psr\Container\ContainerInterface;
use RunetId\Client\RunetIdClient;
use Ruwork\RunetIdBundle\Basket\Handler\HandlerInterface;
use Ruwork\RunetIdBundle\Basket\Loader\LoaderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class Basket implements BasketInterface
{
    private $client;
    private $payerRunetId;
    private $payCollection;
    private $loaders;
    private $handlers;

    public function __construct(
        RunetIdClient $client,
        int $payerRunetId,
        ContainerInterface $loaders,
        ContainerInterface $handlers
    ) {
        $this->client = new Client($client, $payerRunetId);
        $this->payerRunetId = $payerRunetId;
        $this->payCollection = new PayCollection($this->client);
        $this->loaders = $loaders;
        $this->handlers = $handlers;
    }

    /**
     * {@inheritdoc}
     */
    public function getPayerRunetId(): int
    {
        return $this->payerRunetId;
    }

    /**
     * {@inheritdoc}
     */
    public function load(string $class, array $options = [])
    {
        /** @var LoaderInterface $loader */
        $loader = $this->loaders->get($class);
        $options = $this->resolveOptions($loader, $options);
        $element = $loader->load($options, $this, $this->payCollection);

        if (!$element instanceof $class) {
            throw new \UnexpectedValueException(sprintf(
                'Loaded element is expected to be an instance of "%s".',
                $class
            ));
        }

        return $element;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(string $handler, array $options = []): void
    {
        /** @var HandlerInterface $handler */
        $handler = $this->handlers->get($handler);
        $options = $this->resolveOptions($handler, $options);
        $handler->handle($options, $this, $this->client);
    }

    /**
     * @param HandlerInterface|LoaderInterface $configurator
     */
    private function resolveOptions($configurator, array $options): array
    {
        $resolver = new OptionsResolver();
        $configurator->configureOptions($resolver);

        return $resolver->resolve($options);
    }
}


<?php

namespace Bavix\SDK;

use Bavix\Foundation\SharedInstance;
use Bavix\Helpers\Arr;
use Bavix\Helpers\Str;

class PathBuilder
{

    use SharedInstance;

    /**
     * @var int
     */
    protected $depth = 2;

    /**
     * @var int
     */
    protected $length = 2;

    /**
     * @var string
     */
    protected $charPad = '0';

    /**
     * @var int
     */
    protected $typePad = STR_PAD_RIGHT;

    /**
     * PathBuilder constructor.
     *
     * @param int $length
     * @param int $depth
     */
    public function __construct($length = 2, $depth = 2)
    {
        $this->length = $length;
        $this->depth  = $depth;
    }

    /**
     * @param string $data
     *
     * @return string
     */
    protected function string($data)
    {
        return \str_pad(
            $data,
            $this->depth * $this->length,
            $this->charPad,
            $this->typePad
        );
    }

    /**
     * @param int $data
     */
    public function setLength($data)
    {
        $this->length = $data;
    }

    /**
     * @param int $data
     */
    public function setDepth($data)
    {
        $this->depth = $data;
    }

    /**
     * @param string $data
     */
    public function setCharPad($data)
    {
        $this->charPad = $data;
    }

    /**
     * @param int $data
     */
    public function setTypePad($data)
    {
        $this->typePad = $data;
    }

    /**
     * @param string $string
     *
     * @return array
     */
    public function hash($string)
    {
        return implode('/', Arr::slice(
            Str::split($this->string($string), $this->length),
            0, $this->depth
        ));
    }

    /**
     * <type>(/<config>)/<hash>{s1}/<hash>{s2}/<hash>
     *
     * @param string $type
     * @param string $hash
     * @param string $config
     *
     * @return string
     */
    public function generate($type, $config, $hash)
    {
        return $type . '/' . $config . '/' . $this->hash($hash) . '/' . $hash;
    }

}


<?php

namespace TaskQueue\Invoker;

use DependencyInjection\Container;
use TaskQueue\Invoker\Exception\ArrayPairLengthAwareException;
use TaskQueue\Invoker\Exception\ClassInstanceException;
use TaskQueue\Invoker\Exception\ClassMethodException;

class MethodInvoker implements InvokerInterface
{
    /**
     * @var array
     */
    private $method;

    public function __construct($args)
    {
        if (!is_array($args)) {
            throw new \InvalidArgumentException(
                sprintf("Parameter 1 of %s must be an array.", __METHOD__)
            );
        }

        if (sizeof($args) !== 2) {
            throw new ArrayPairLengthAwareException(
                sprintf("Parameter 1 of %s must be an array with length === 2.", __METHOD__)
            );
        }

        if (!isset($args['instance'])) {
            throw new ClassInstanceException("\$args index key 'instance' must exists.");
        }

        if (!isset($args['method'])) {
            throw new ClassMethodException("\$args index key 'method' must exists.");
        }

        $args['instance'] = (!is_object($args['instance'])
            ? (class_exists($args['instance'])
                ? (new Container)->make($args['instance'])
                : null)
            : $args['instance']);

        $this->method = $args;
    }

    /**
     * {@inheritdoc}
     */
    public function invoke()
    {
        return call_user_func_array(
            [$this->method['instance'], $this->method['method']], func_get_args()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function invokeWithArgs($args)
    {
        if (!is_array($args)) {
            throw new \InvalidArgumentException(
                sprintf("Parameter 1 of %s must be an array.", __METHOD__)
            );
        }

        return call_user_func_array(
            [$this->method['instance'], $this->method['method']], $args
        );
    }
}


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

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Validator\Regex,
    Zend\Validator\StringLength,
    Zend\Validator\ValidatorChain,
    Zend\Validator\ValidatorInterface,
    CmsUser\Options\InputFilterOptionsInterface,
    CmsUser\Options\ModuleOptions;

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

        $validator = new ValidatorChain();
        $validator->setPluginManager($serviceLocator);

        $validator->attachByName('StringLength', [
            'messages' => [
                StringLength::TOO_SHORT => 'The username must be at least %min% characters long',
                StringLength::TOO_LONG => 'The username must not be more than %max% characters',
            ],
            'encoding' => 'UTF-8',
            'min' => 5,
            'max' => 30,
        ], true);

        $validator->attachByName('Regex', [
            'messages' => [
                Regex::NOT_MATCH => 'Incorrect username. ' .
                    'Username must contain alphanumeric characters without spaces',
            ],
            'pattern' => $options->getUsernameRegexPattern(),
        ], true);

        $validator->attachByName('CmsUserNoUsernameExists', [], true);

        return $validator;
    }
}


<?php

/*
 * This File is part of the Thapp\Jmg\Http\Psr7 package
 *
 * (c) iwyg <mail@thomas-appel.com>
 *
 * For full copyright and license information, please refer to the LICENSE file
 * that was distributed with this package.
 */

namespace Thapp\Jmg\Http\Psr7;

use Thapp\Jmg\Resource\ImageResourceInterface;

/**
 * @class NotModifiedImageResonse
 *
 * @package Thapp\Jmg\Http\Psr7
 * @version $Id$
 * @author iwyg <mail@thomas-appel.com>
 */
class NotModifiedImageResonse extends ImageResponse
{
    /** @var array */
    const STATUS = [304 => 'Not Modified'];

    /** @var Psr\Http\Message\StreamInterface */
    private $body;

    /** @var array */
    private static $excludeHeaders = [
        'allow', 'last-modified', 'content-md5', 'content-encoding',
        'content-lenght', 'content-type'
    ];

    /**
     * {@inheritdoc}
     */
    public function getReasonPhrase()
    {
        return self::STATUS[$this->getStatusCode()];
    }

    /**
     * {@inheritdoc}
     */
    public function getStatusCode()
    {
        return key(self::STATUS);
    }

    /**
     * {@inheritdoc}
     */
    public function getBody()
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareHeaders(array $headers)
    {
        return array_merge($this->getDefaultHeader(), array_filter($headers, function ($key) {
            return !in_array(strtolower($key), self::$excludeHeaders);
        }, ARRAY_FILTER_USE_KEY), ['content-length' => 0]);
    }
}


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateHcLanguagesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('hc_languages', function(Blueprint $table)
		{
			$table->string('id', 36)->unique('id_UNIQUE');
			$table->integer('count', true);
			$table->string('language_family');
			$table->string('language');
			$table->string('native_name');
			$table->string('iso_639_1');
			$table->string('iso_639_2');
			$table->boolean('front_end')->default(0);
			$table->boolean('back_end')->default(0);
			$table->boolean('content')->default(0);
			$table->timestamps();
			$table->softDeletes();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('hc_languages');
	}

}


<?php

namespace Dhii\Data\Container;

use Psr\Container\ContainerInterface as BaseContainerInterface;

/**
 * Functionality for resolving the inner-most container from a container chain.
 *
 * @since [*next-version*]
 */
trait ResolveContainerCapableTrait
{
    /**
     * Resolves the inner-most container of a container chain.
     *
     * Will recursively try and retrieve the assigned container, until reaching a non-container-aware container,
     * or an inner container that is null, in which case the outer container is returned.
     *
     * @since [*next-version*]
     *
     * @param BaseContainerInterface|ContainerAwareInterface $container The optionally container-aware container to resolve.
     *
     * @return BaseContainerInterface The inner-most container.
     */
    protected function _resolveContainer(BaseContainerInterface $container)
    {
        $parent = null;

        while ($container instanceof ContainerAwareInterface) {
            $parent = $container->getContainer();

            if (!($parent instanceof BaseContainerInterface)) {
                break;
            }
            $container = $parent;
        }

        return $container;
    }
}


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

/**
 * Staff.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\Core\AbstractAPI;
use EasyWeChat\Support\Collection;

/**
 * Class Staff.
 */
class Staff extends AbstractAPI
{
    const API_LISTS = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist';
    const API_ONLINE = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist';
    const API_DELETE = 'https://api.weixin.qq.com/customservice/kfaccount/del';
    const API_UPDATE = 'https://api.weixin.qq.com/customservice/kfaccount/update';
    const API_CREATE = 'https://api.weixin.qq.com/customservice/kfaccount/add';
    const API_INVITE_BIND = 'https://api.weixin.qq.com/customservice/kfaccount/inviteworker';
    const API_MESSAGE_SEND = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
    const API_AVATAR_UPLOAD = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg';
    const API_RECORDS = 'https://api.weixin.qq.com/customservice/msgrecord/getrecord';
    const API_MSG_LIST = 'https://api.weixin.qq.com/customservice/msgrecord/getmsglist';

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

    /**
     * List all online staffs.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function onlines()
    {
        return $this->parseJSON('get', [self::API_ONLINE]);
    }

    /**
     * Create a staff.
     *
     * @param string $account
     * @param string $nickname
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function create($account, $nickname)
    {
        $params = [
                   'kf_account' => $account,
                   'nickname' => $nickname,
                  ];

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

    /**
     * Update a staff.
     *
     * @param string $account
     * @param string $nickname
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($account, $nickname)
    {
        $params = [
                   'kf_account' => $account,
                   'nickname' => $nickname,
                  ];

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

    /**
     * Delete a staff.
     *
     * @param string $account
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($account)
    {
        // XXX: 微信那帮搞技术的都 TM 是 SB，url上的文本居然不 TM urlencode,
        // 这里客服账号因为有 @ 符，而微信不接收urlencode的账号。。
        // 简直是日了...
        // #222
        // PS: 如果你是微信做接口的，奉劝你们，尊重技术，不会别乱搞，笨不是你们的错，你们出来坑人就是大错特错。
        $accessTokenField = sprintf('%s=%s', $this->accessToken->getQueryName(), $this->accessToken->getToken());
        $url = sprintf(self::API_DELETE.'?%s&kf_account=%s', $accessTokenField, $account);

        $contents = $this->getHttp()->parseJSON(file_get_contents($url));

        $this->checkAndThrow($contents);

        return new Collection($contents);
    }

    /**
     * Invite a staff.
     *
     * @param string $account
     * @param string $wechatId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function invite($account, $wechatId)
    {
        $params = [
                   'kf_account' => $account,
                   'invite_wx' => $wechatId,
                  ];

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

    /**
     * Set staff avatar.
     *
     * @param string $account
     * @param string $path
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function avatar($account, $path)
    {
        return $this->parseJSON('upload', [self::API_AVATAR_UPLOAD, ['media' => $path], [], ['kf_account' => $account]]);
    }

    /**
     * Get message builder.
     *
     * @param \EasyWeChat\Message\AbstractMessage|string $message
     *
     * @return \EasyWeChat\Staff\MessageBuilder
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function message($message)
    {
        $messageBuilder = new MessageBuilder($this);

        return $messageBuilder->message($message);
    }

    /**
     * Send a message.
     *
     * @param string|array $message
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function send($message)
    {
        return $this->parseJSON('json', [self::API_MESSAGE_SEND, $message]);
    }

    /**
     * Get staff session history.
     *
     * @param int $startTime
     * @param int $endTime
     * @param int $page
     * @param int $pageSize
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function records($startTime, $endTime, $page = 1, $pageSize = 10)
    {
        $params = [
                   'starttime' => is_numeric($startTime) ? $startTime : strtotime($startTime),
                   'endtime' => is_numeric($endTime) ? $endTime : strtotime($endTime),
                   'pageindex' => $page,
                   'pagesize' => $pageSize,
                  ];

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

    /**
     * 获取聊天记录.
     *
     * @param int $startTime
     * @param int $endTime
     * @param int $msgId
     * @param int $number
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function messages($startTime, $endTime, $msgId = 1, $number = 10000)
    {
        $params = [
                   'starttime' => is_numeric($startTime) ? $startTime : strtotime($startTime),
                   'endtime' => is_numeric($endTime) ? $endTime : strtotime($endTime),
                   'msgid' => $msgId,
                   'number' => $number,
                  ];

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


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\HWIOAuth;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface;
use RunetId\Client\RunetIdClient;
use Symfony\Component\HttpFoundation\Request as HttpRequest;

final class ResourceOwner implements ResourceOwnerInterface
{
    private $client;
    private $name;

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

    /**
     * {@inheritdoc}
     */
    public function getAccessToken(HttpRequest $request, $redirectUri, array $extraParameters = [])
    {
        return [
            'access_token' => $request->query->get('token'),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getUserInformation(array $accessToken, array $extraParameters = [])
    {
        $result = $this->client
            ->userAuth()
            ->setToken($accessToken['access_token'])
            ->getResult();

        return new UserResponse($this, $result);
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthorizationUrl($redirectUri, array $extraParameters = [])
    {
        return $this->client->generateOAuthUri($redirectUri);
    }

    /**
     * {@inheritdoc}
     */
    public function isCsrfTokenValid($csrfToken)
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function handles(HttpRequest $request)
    {
        return $request->query->has('token');
    }

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

    /**
     * {@inheritdoc}
     */
    public function getOption($name)
    {
        throw new \InvalidArgumentException(sprintf('Option "%s" does not exist.', $name));
    }

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

    /**
     * {@inheritdoc}
     */
    public function addPaths(array $paths)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function refreshAccessToken($refreshToken, array $extraParameters = [])
    {
    }
}


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

namespace VinceT\AdminBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

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

    /**
     * [__construct description]
     *
     * @param ContainerInterface $container [description]
     */
    public function __construct(ContainerInterface $container)
    {
        $this->setContainer($container);
    }

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

    /**
     * Gets filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'render_attributes' => new \Twig_Filter_Method($this, 'renderAttributes', array('is_safe' => array('html'))),
        );
    }

    /**
     * renderAttributes
     *
     * @param array $attributes attributes to render
     * @param array $defaults   defaults value
     *
     * @return [type]
     */
    public function renderAttributes(array $attributes, array $defaults = array())
    {
        $s = '';
        foreach ($attributes as $name => $value) {
            if ( array_key_exists($name, $defaults) ) {
                $value = $value.' '.$defaults[$name];
            }
            $s .= sprintf(' %s="%s"', $name, $value);
        }
        foreach ($defaults as $name => $value) {
            if ( !array_key_exists($name, $attributes) ) {
                $s .= sprintf(' %s="%s"', $name, $value);
            }
        }
        return $s;
    }

    /**
     * Gets global variables
     *
     * @return [type]
     */
    public function getGlobals()
    {
        return array(
            'admin_theme_handler' => $this->container->get('vince_t.admin.theme.handler')
        );
    }

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

}


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

namespace Praxigento\BonusHybrid\Service\Calc\Compress;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 as PCpmrsPhase2;

class Phase2
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** Calculation scheme (DEFAULT or EU) */
    const CTX_IN_SCHEME = 'in.scheme';

    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 */
    private $procCmprsPhase2;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Compress\Phase2\GetPv */
    private $rouGetPv;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Compress\Phase2\SaveDownline */
    private $rouSaveDwnl;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Proc\Compress\Phase2 $procCmprsPhase2,
        \Praxigento\BonusHybrid\Service\Calc\Compress\Phase2\GetPv $rouGetPv,
        \Praxigento\BonusHybrid\Service\Calc\Compress\Phase2\SaveDownline $rouSaveDwnl
    ) {
        $this->logger = $logger;
        $this->daoCalc = $daoCalc;
        $this->daoBonDwnl = $daoBonDwnl;
        $this->servPeriodGet = $servPeriodGet;
        $this->procCmprsPhase2 = $procCmprsPhase2;
        $this->rouGetPv = $rouGetPv;
        $this->rouSaveDwnl = $rouSaveDwnl;
    }

    /**
     * Collect data for Phase2 compression and call process common for general & forecast calculations.
     *
     * @param $calcIdWriteOff
     * @param $calcIdPhase1
     * @param $calcIdPhase2
     * @param $scheme
     * @return array
     */
    private function compressPhase2($calcIdWriteOff, $calcIdPhase1, $calcIdPhase2, $scheme)
    {
        $pv = $this->rouGetPv->exec($calcIdWriteOff);
        $dwnlPlain = $this->daoBonDwnl->getByCalcId($calcIdWriteOff);
        $dwnlPhase1 = $this->daoBonDwnl->getByCalcId($calcIdPhase1);
        $ctx = new \Praxigento\Core\Data();
        $ctx->set(PCpmrsPhase2::IN_CALC_ID_PHASE2, $calcIdPhase2);
        $ctx->set(PCpmrsPhase2::IN_SCHEME, $scheme);
        $ctx->set(PCpmrsPhase2::IN_DWNL_PLAIN, $dwnlPlain);
        $ctx->set(PCpmrsPhase2::IN_DWNL_PHASE1, $dwnlPhase1);
        $ctx->set(PCpmrsPhase2::IN_MAP_PV, $pv);
        $out = $this->procCmprsPhase2->exec($ctx);
        $dwnlPhase2 = $out->get(PCpmrsPhase2::OUT_DWNL_PHASE2);
        $legs = $out->get(PCpmrsPhase2::OUT_LEGS);
        $result = [$dwnlPhase2, $legs];
        return $result;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* get working data from context */
        $scheme = $ctx->get(self::CTX_IN_SCHEME) ?? Cfg::SCHEMA_DEFAULT;
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Phase2 compression for '$scheme' scheme is started.");
        /**
         * Get dependent calculation data
         *
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $writeOffCalc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $phase1Calc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $phase2Calc
         * @var \Praxigento\BonusBase\Repo\Data\Period $phase2Period
         */
        list($writeOffCalc, $phase1Calc, $phase2Calc, $phase2Period) = $this->getCalcData($scheme);
        $writeOffCalcId = $writeOffCalc->getId();
        $phase1CalcId = $phase1Calc->getId();
        $phase2CalcId = $phase2Calc->getId();
        $phase2PeriodId = $phase2Period->getId();
        $dsBegin = $phase2Period->getDstampBegin();
        $dsEnd = $phase2Period->getDstampEnd();
        $this->logger->info("Phase2 compression period #$phase2PeriodId ($dsBegin-$dsEnd)");
        /* perform calculation for given source calculations */
        list($downline, $legs) = $this->compressPhase2($writeOffCalcId, $phase1CalcId, $phase2CalcId, $scheme);
        /* save calculation results */
        $this->rouSaveDwnl->exec($downline, $legs, $writeOffCalcId, $phase1CalcId,$scheme);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($phase2CalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Phase2 compression for '$scheme' scheme is completed.");
    }

    /**
     * Get calculation/period data related to current calculation.
     *
     * @param string $scheme see \Praxigento\BonusHybrid\Config::SCHEMA_XXX
     * @return array [$writeOffCalc, $phase1Calc, $phaseCalc, $phase2Period]
     */
    private function getCalcData($scheme)
    {
        $calcTypeCode = ($scheme == Cfg::SCHEMA_EU)
            ? Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_EU
            : Cfg::CODE_TYPE_CALC_COMPRESS_PHASE2_DEF;
        /**
         * Get data for phase2 compression and OV (base) calculations
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_OV);
        $req->setDepCalcTypeCode($calcTypeCode);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Period $phase2Period */
        $phase2Period = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $phaseCalc */
        $phaseCalc = $resp->getDepCalcData();
        /**
         * Get data for PV Write Off & phase1 compression calculations
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_PV_WRITE_OFF);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        $req->setDepIgnoreComplete(true);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $writeOffCalc */
        $writeOffCalc = $resp->getBaseCalcData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $phase1Calc */
        $phase1Calc = $resp->getDepCalcData();
        /**
         * Compose results.
         */
        $result = [$writeOffCalc, $phase1Calc, $phaseCalc, $phase2Period];
        return $result;
    }

}


<?php
namespace FelixOnline\Base;
use \FelixOnline\Exceptions\InternalException;

/**
 * Session class
 */
class Session implements \ArrayAccess
{
    private $name;
    private $id;
    private $cli;
    private $clistore = array();

    /**
     * Constructor
     */
    public function __construct($name, $cli = false)
    {
        $this->name = $name; // session name
        $this->cli = $cli;
    }

    /**
     * Start session
     * @codeCoverageIgnore
     */
    public function start()
    {
        if(!$this->cli) {
            if (session_status() === PHP_SESSION_DISABLED) {
                throw new InternalException('Sessions are disabled');
            }

            if (session_status() === PHP_SESSION_ACTIVE) {
                throw new InternalException('Session already started.');
            }

            session_name($this->name); // set session name
            session_start();

            $this->id = session_id();
        } else {
            $this->clistore = array();
            $this->id = rand();
        }
    }

    /**
     * Reset session
     * @codeCoverageIgnore
     */
    public function reset()
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            session_destroy();
        }

        $this->start();
    }

    /**
     * Emit session data
     * @codeCoverageIgnore
     */
    public function close()
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            session_write_close();
        }

        $this->id = null;
    }

    /**
     * Destroy session
     * @codeCoverageIgnore
     */
    public function destroy()
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            session_destroy();
        }

        $this->id = null;
    }

    public function offsetSet($offset, $value)
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            if (is_null($offset)) {
                $_SESSION[] = $value;
            } else {
                $_SESSION[$offset] = $value;
            }
        } else {
            if (is_null($offset)) {
                $this->clistore[] = $value;
            } else {
                $this->clistore[$offset] = $value;
            }
        }
    }

    public function offsetExists($offset)
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            return isset($_SESSION[$offset]);
        } else {
            return isset($this->clistore[$offset]);
        }
    }

    public function offsetUnset($offset)
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            unset($_SESSION[$offset]);
        } else {
            unset($this->clistore[$offset]);
        }
    }

    public function offsetGet($offset)
    {
        if($this->id == null) {
            throw new InternalException('Session not loaded');
        }

        if(!$this->cli) {
            return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
        } else {
            return isset($this->clistore[$offset]) ? $this->clistore[$offset] : null;
        }
    }

    public function getName()
    {
        return $this->name;
    }

    public function getId()
    {
        return $this->id;
    }
}


<?php
/**
 * This file is part of SoloProyectos common library.
 *
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http-controller/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http-controller
 */
namespace soloproyectos\http\data;
use soloproyectos\arr\Arr;
use soloproyectos\http\data\HttpDataInterface;

/**
 * Class HttpCookie.
 *
 * @package Http\Data
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http-controller/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http-controller
 */
class HttpCookie implements HttpDataInterface
{
    /**
     * By default the cookie expires in one year (365 * 24 * 60 * 60 seconds)
     */
    const DEFAULT_EXPIRATION_TIME = 31536000;

    /**
     * Gets a request attribute.
     *
     * @param string $name    Request attribute.
     * @param string $default Default value (not required)
     *
     * @return mixed
     */
    public function get($name, $default = "")
    {
        return Arr::get($_COOKIE, $name, $default);
    }

    /**
     * Sets a request attribute.
     *
     * @param string $name           Request attribute.
     * @param mixed  $value          Request value.
     * @param int    $expirationTime Expiration time (default is one year)
     *
     * @return void
     */
    public function set(
        $name,
        $value,
        $expirationTime = HttpCookie::DEFAULT_EXPIRATION_TIME
    ) {
        setcookie($name, $value, time() + $expirationTime, "/");
    }

    /**
     * Does the request attribute exist?
     *
     * @param string $name Request attribute.
     *
     * @return boolean
     */
    public function exist($name)
    {
        return Arr::exist($_COOKIE, $name);
    }

    /**
     * Deletes a request attribute.
     *
     * @param string $name Request attribute.
     *
     * @return void
     */
    public function delete($name)
    {
        setcookie($name, "", time() - 3600, "/");
        Arr::delete($_COOKIE, $name);
    }
}