<?php

/*
 * Encryption addon for Bear Framework
 * https://github.com/ivopetkov/encryption-bearframework-addon
 * Copyright (c) Ivo Petkov
 * Free to use under the MIT license.
 */

namespace IvoPetkov\BearFrameworkAddons;

use BearFramework\App;

/**
 *
 */
class Encryption
{

    /**
     * The cipher method
     * @var string
     */
    private $cipher = 'AES-256-CBC';

    /**
     *
     * @var array
     */
    private $cache = [];

    /**
     *
     */
    public function __construct()
    {

    }

    /**
     * Encrypts the value provided. The default key will be used if none specified.
     *
     * @param string $value
     * @param string $key
     * @return string
     */
    public function encrypt(string $value, string $key = null): string
    {
        if ($key === null) {
            $key = $this->getDefaultKey();
        }
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher));
        return $iv . openssl_encrypt($value, $this->cipher, $key, 0, $iv);
    }

    /**
     * Decrypts the value provided. The default key will be used if none specified.
     *
     * @param string $value
     * @param string $key
     * @return string
     */
    public function decrypt(string $value, string $key = null): ?string
    {
        if ($key === null) {
            $key = $this->getDefaultKey();
        }
        $ivLength = openssl_cipher_iv_length($this->cipher);
        $iv = substr($value, 0, $ivLength);
        $result = @openssl_decrypt(substr($value, $ivLength), $this->cipher, $key, 0, $iv);
        if ($result === false) {
            return null;
        }
        return $result;
    }

    /**
     * Returns the default key.
     */
    private function getDefaultKey()
    {
        if (isset($this->cache['defaultKey'])) {
            return $this->cache['defaultKey'];
        }
        $app = App::get();
        $cacheKey = 'ivopetkov-encryption-default-key';
        $value = $app->cache->getValue($cacheKey);
        if ($value === null) {
            $dataKey = 'encryption/default.key';
            $value = $app->data->getValue($dataKey);
            if ($value === null) {
                $value = md5(openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher)) . uniqid('', true) . rand(0, 999999999));
                $app->data->set($app->data->make($dataKey, $value));
            }
            $app->cache->set($app->cache->make($cacheKey, $value));
        }
        $this->cache['defaultKey'] = $value;
        return $value;
    }

}


<?php
/**
 * e-Arc Framework - the explicit Architecture Framework
 *
 * @package earc/di
 * @link https://github.com/Koudela/earc-di/
 * @copyright Copyright (c) 2018 Thomas Koudela
 * @license http://opensource.org/licenses/MIT MIT License
 */

namespace eArc\di;

/**
 * @inheritDoc
 */
class DependencyObject implements interfaces\DependencyObjectInterface
{
    protected $dc;
    protected $base;
    protected $name;
    protected $config;
    protected $instance;

    /**
     * @inheritDoc
     */
    public function __construct(string $name, $config, DependencyContainer $dc, DependencyContainer $base)
    {
        $this->dc = $dc;
        $this->base = $base;
        $this->name = $name;
        $this->config = $config;
    }

    /**
     * @inheritDoc
     */
    final public function getInstance(): object
    {
        if (!isset($this->instance)) {
            $this->instance = $this->makeInstance();
        }

        return $this->instance;
    }

    /**
     * @inheritDoc
     */
    final public function makeInstance(): object
    {
        if ($this->config instanceof \Closure) {
            return ($this->config)();
        }

        if (!is_array($this->config)) {
            return $this->config;
        }

        if (\count($this->config) === 0) {
            return new $this->name();
        }

        return new $this->name(...$this->calculateArguments($this->config));
    }

    /**
     * Calculate the arguments for the enclosed object.
     *
     * @param array $config
     * @return array
     */
    private function calculateArguments(array $config): array
    {
        $args = [];

        foreach ($config as $key => $item)
        {
            if (\is_string($item) && $this->base->has($item)) {
                $args[] = $this->base->get($item);
                continue;
            }

            if (\is_string($key) && \is_array($item)) {
                $this->dc->set($key, $item);
                $args[] = $this->dc->get($key);
                continue;
            }

            $args[] = $item;
        }

        return $args;
    }
}


<?php

namespace eig\UUID;

use eig\UUID\Facades\UUID;

/**
 * Class AssignUUID
 * @package eig\UUID
 * @license MIT
 * @author James Johnson
 * @author Excellent InGenuity LLC
 */
trait AssignUUID
{

    /**
     * assignUUID
     *
     * @param null $field
     */
    protected function assignUUID($field = null)
    {
        if ($field != null) {
            $this->{$field} = UUID::generate();
        } else {
            $this->id = UUID::generate();
        }
    }
}


<?PHP

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\LabelText;

class LabelImage extends LabelText
{

	private $prefix ;

    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->prefix = isset($xmlArr["ATTRIBUTES"]["URLPREFIX"]) ? $xmlArr["ATTRIBUTES"]["URLPREFIX"] : null;
        $this->prefix =  Expression::evaluateExpression($this->prefix,$this);
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	$this->prefix = Expression::evaluateExpression($this->prefix, $formobj);
    	$func = $this->getFunction();
    	if($this->width){
    		$width_str = " width=\"".$this->width."\" ";
    	}
        if($this->height){
    		$height_str = " height=\"".$this->height."\" ";
    	}
    	$value = $this->getText()?$this->getText():$this->getValue();
    	if($value){

    		if ($this->link)
            {
                $link = $this->getLink();
                $target = $this->getTarget();
                $sHTML = "" . "prefix.$value."\"  border=\"0\" $width_str $height_str />" . "";
            }
            else
            {
                $sHTML = "prefix.$value."\" $func $width_str $height_str />";
            }

    	}
        return $sHTML;
    }

}

?>


<?php namespace Interpro\QuickStorage\Laravel\Handle;

use Illuminate\Support\Facades\Log;
use Interpro\ImageFileLogic\Concept\ImageLogicAgent;
use Interpro\QuickStorage\Concept\Command\Command;
use Interpro\QuickStorage\Concept\Exception\WrongBlockNameException;
use Interpro\QuickStorage\Laravel\Model\Block;
use Interpro\QuickStorage\Laravel\Model\Bool;
use Interpro\QuickStorage\Laravel\Model\Imageitem;
use Interpro\QuickStorage\Laravel\Model\Numb;
use Interpro\QuickStorage\Laravel\Model\Pdatetime;
use Interpro\QuickStorage\Laravel\Model\Stringfield;
use Interpro\QuickStorage\Laravel\Model\Textfield;

class ReinitOneBlockCommandHandler {

    private $imageLogicAgent;

    /**
     * Create the command handler.
     *
     * @return void
     */
    public function __construct(ImageLogicAgent $imageLogicAgent)
    {
        $this->imageLogicAgent = $imageLogicAgent;
    }

    /**
     * Handle the command.
     *
     * @param  Command  $command
     * @return void
     */
    public function handle(Command $command)
    {
        $this->reinitBlock($command->block_name);
    }

    //Создание структуры блоков лэндинга из конфига
    public function reinitBlock($block_name='')
    {
        if(!array_key_exists($block_name, config('qstorage')))
        {
            throw new WrongBlockNameException('В настройке нет блока с именем '.$block_name);
        }

        $blockstruct = config('qstorage')[$block_name];

        $newBlock = Block::find($block_name);

        if(!$newBlock)
        {
            $newBlock = new Block();
        }

        $newBlock->name = $block_name;

        if(array_key_exists('title', $blockstruct))
        {
            $newBlock->title = $blockstruct['title'];
        }

        if(array_key_exists('stringfields', $blockstruct))
        {
            foreach($blockstruct['stringfields'] as $fieldname)
            {
                $stringfield = Stringfield::firstOrCreate(['block_name'=>$block_name, 'name'=>$fieldname]);
            }
        }

        if(array_key_exists('textfields', $blockstruct))
        {
            foreach($blockstruct['textfields'] as $fieldname)
            {
                $textfield = Textfield::firstOrCreate(['block_name'=>$block_name, 'name'=>$fieldname]);
            }
        }

        if(array_key_exists('numbs', $blockstruct))
        {
            foreach($blockstruct['numbs'] as $fieldname)
            {
                $numb = Numb::firstOrCreate(['block_name'=>$block_name, 'name'=>$fieldname]);
            }
        }

        if(array_key_exists('bools', $blockstruct))
        {
            foreach($blockstruct['bools'] as $fieldname)
            {
                $boolitem = Bool::firstOrCreate(['block_name'=>$block_name, 'name'=>$fieldname]);
            }
        }

        if(array_key_exists('pdatetimes', $blockstruct))
        {
            foreach($blockstruct['pdatetimes'] as $fieldname)
            {
                $dtitem = Pdatetime::firstOrCreate(['block_name'=>$block_name, 'name'=>$fieldname]);
            }
        }

        if(array_key_exists('images', $blockstruct))
        {
            foreach($blockstruct['images'] as $fieldname)
            {
                $image_name = $block_name.'_'.$fieldname;

                $image = Imageitem::where('block_name', $block_name)->where('group_id', 0)->where('name', $fieldname)->first();

                if(!$image)
                {
                    $image = new Imageitem;
                    $image->name = $fieldname;
                    $image->block_name = $block_name;
                    $image->group_id = 0;

                    $image->preview_link   = $this->imageLogicAgent->getPlaceholder($image_name, 'preview');
                    $image->primary_link   = $this->imageLogicAgent->getPlaceholder($image_name, 'primary');
                    $image->original_link  = $this->imageLogicAgent->getPlaceholder($image_name, 'primary');
                    $image->secondary_link = $this->imageLogicAgent->getPlaceholder($image_name, 'secondary');
                    $image->icon_link      = $this->imageLogicAgent->getPlaceholder($image_name, 'icon');

                    $image->save();
                }
            }
        }

        $newBlock->save();

    }

}


<?php

namespace Interpro\QS\Executors;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Interpro\Core\Contracts\Executor\AInitializer;
use Interpro\Core\Contracts\Mediator\InitMediator;
use Interpro\Core\Contracts\Mediator\RefConsistMediator;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\QS\Exception\QSException;
use Interpro\QS\Model\Block;
use Interpro\QS\Model\Group;
use Interpro\QS\Model\Ref;

class Initializer implements AInitializer
{
    private $refConsistMediator;
    private $initMediator;

    public function __construct(RefConsistMediator $refConsistMediator, InitMediator $initMediator)
    {
        $this->initMediator = $initMediator;
        $this->refConsistMediator = $refConsistMediator;
    }

    protected function enumerate($stname, $sid, $refname, $name, $id)
    {
        $query = Group::query();

        $query->where('id', '=', $id);

        $refs_query = Ref::selectRaw('entity_id')
            ->whereRaw('entity_name = "'.$name.'"')
            ->whereRaw('name = "'.$refname.'"')
            ->whereRaw('ref_entity_name = "'.$stname.'"')
            ->whereRaw('ref_entity_id = "'.$sid.'"');

        $sorter_query = Group::selectRaw('MAX(sorter)+1 AS next_sorter')
        ->whereRaw('id in '.DB::raw('('.$refs_query->toSql().')'));

        $query->leftJoin(DB::raw('('.$sorter_query->toSql().') AS nextst'), function($join)
        {
            //внимание!, костыль, как сделать join без on секции сразу не нашел
            $join->on('nextst.next_sorter', '=', 'nextst.next_sorter');
        });

        $query->update(['sorter' => DB::raw('nextst.next_sorter')]);
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'qs';
    }

    private function slugExist($name, $slug)
    {
        $collection = Group::where('slug', $slug)->where('name', $name)->get();

        return !$collection->isEmpty();
    }

    private function refExist(AType $type, $id)
    {
        $ref = new ARef($type, $id);

        return $this->refConsistMediator->exist($ref);
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\AType $type
     * @param array $defaults
     *
     * @return \Interpro\Core\Contracts\Ref\ARef
     */
    public function init(AType $type, array $defaults = [])
    {
        $type_name = $type->getName();

        $self_fields = ['id', 'name', 'slug', 'title', 'sorter', 'show', 'predefined'];

        //file_put_contents('/home/boris/sites/development/PRINT_R', print_r($type->getName().PHP_EOL, true), FILE_APPEND);

        //[[[
        DB::beginTransaction();

        if($type->getRank() === TypeRank::BLOCK)
        {
            $model = Block::where('name', '=', $type_name)->first();
            if(!$model)
            {
                $model = new Block();
                $model->name = $type_name;

                if(array_key_exists('show', $defaults))
                {
                    $model->show = (bool) $defaults['show'];
                }
                else
                {
                    $model->show = true;
                }

                if(array_key_exists('title', $defaults))
                {
                    $model->title = $defaults['title'];
                }
                else
                {
                    $model->title = 'Блок '.$type_name;
                }

                $model->save();
            }

            $id = 0;
        }
        elseif($type->getRank() === TypeRank::GROUP)
        {
            $model = new Group();
            $model->name = $type_name;

            if(array_key_exists('show', $defaults))
            {
                $model->show = (bool) $defaults['show'];
            }
            else
            {
                $model->show = true;
            }

            if(array_key_exists('title', $defaults))
            {
                $model->title = $defaults['title'];
            }
            else
            {
                $model->title = 'Элемент группы '.$type_name;
            }

            if(array_key_exists('slug', $defaults))
            {
                if($this->slugExist($type_name, $defaults['slug']))
                {
                    throw new QSException('Значение slug '.$defaults['slug'].' для типа '.$type_name.' уже занято!');
                }

                $model->slug = $defaults['slug'];
            }
            else
            {
                $model->slug = 'new'.time();
            }

            if(array_key_exists('sorter', $defaults))
            {
                $model->sorter = $defaults['sorter'];
            }
            else
            {
                $model->sorter = 0;
            }

            if(array_key_exists('predefined', $defaults))
            {
                $model->predefined = $defaults['predefined'];
            }
            else
            {
                $model->predefined = false;
            }

            $model->save();

            $id = $model->id;
        }
        else
        {
            throw new QSException('При инициализации передан тип с рангом отличным от блока и группы: '.$type->getRank().'!');
        }

        //----------------------------------------------------------------------
        $refs = $type->getRefs();

        $sid = 0;
        $stname = '';

        foreach($refs as $ref_name => $ref)
        {
            $refType = $ref->getFieldType();

            $ref_type_name = $refType->getName();

            if(array_key_exists($ref_name, $defaults))
            {
                $ref_entity_id = (int) $defaults[$ref_name];
            }
            else
            {
                $ref_entity_id = 0;
            }

            if($refType->getRank() === TypeRank::GROUP and $ref_entity_id === 0)
            {
                $throwexc = false;
            }
            else
            {
                $throwexc = !$this->refExist($refType, $ref_entity_id);
            }

            if ($throwexc)
            {
                throw new QSException('Сущность по ссылке отсутствует: '.$ref_type_name.'('.$ref_entity_id.')!');
            }

            $ref = Ref::firstOrNew(['entity_name' => $type_name, 'entity_id' => $id, 'name' => $ref_name, 'ref_entity_name' => $ref_type_name]);

            $ref->ref_entity_id = $ref_entity_id;

            $ref->save();

            if($ref_name === 'superior')
            {
                $sid = $ref_entity_id;
                $stname = $ref_type_name;
            }
        }

        if($stname and !array_key_exists('sorter', $defaults))
        {
            $this->enumerate($stname, $sid, 'superior', $type_name, $id);
        }

        $Aref = new ARef($type, $id);
        //----------------------------------------------------------------------
        $owns = $type->getOwns();

        foreach($owns as $own_name => $own)
        {
            if(in_array($own_name, $self_fields))
            {
                continue;
            }

            $family = $own->getFieldTypeFamily();
            $mode = $own->getMode();

            if(array_key_exists($own_name, $defaults))
            {
                $value = $defaults[$own_name];
            }
            else
            {
                $value = null;
            }

            if($mode === TypeMode::MODE_B)
            {
                $initializer = $this->initMediator->getBInitializer($family);
                $initializer->init($Aref, $own, $value);
            }
            elseif($mode === TypeMode::MODE_C)
            {
                $initializer = $this->initMediator->getCInitializer($family);
                $initializer->init($Aref, $own, $value);
            }
        }

        DB::commit();
        //]]]

        return $Aref;
    }
}


<?php
/*
This is part of Wedeto, the WEb DEvelopment TOolkit.
It is published under the MIT Open Source License.

Copyright 2017, Egbert van der Wal

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace Wedeto\Resolve;

use Serializable;

/**
 * Manage routes discovered by the router. Each app is stored
 * with it's content type, route and file path.
 */
class Route implements Serializable
{
    /** The route to this node */
    protected $route;

    /** The depth of this node */
    protected $depth;

    /** The app files linked to this node directly */
    protected $apps = array();

    /** The child nodes */
    protected $children = array();

    /**
     * Create a route node.
     * @param string $route The route to get here
     * @param int $depth The depth of this node.
     */
    public function __construct(string $route, int $depth)
    {
        $this->route = $route;
        $this->depth = $depth;
    }

    /**
     * Link an app to this route.
     * @param string $path The path to the app
     * @param string $ext The file extension for this app
     * @param string $module The module this app belongs to
     * @return Route Provides fluent interface
     */
    public function addApp(string $path, $ext, string $module)
    {
        $ext_key = empty($ext) ? '_' : $ext;
        if (!isset($this->apps[$ext_key]))
        {
            $this->apps[$ext_key] = array(
                'path' => $path,
                'module' => $module,
                'route' => $this->route,
                'ext' => $ext,
                'depth' => $this->depth
            );
        }
        return $this;
    }

    /**
     * Get a sub route for the specified route part. If a
     * child node does not exist yet, it will be created.
     * @param string $route_part The child route part
     * @return Route The child node
     */
    public function getSubRoute(string $route_part)
    {
        $sub_route = $this->route === '/' ? '/' . $route_part : $this->route . '/' . $route_part;

        if (!isset($this->children[$route_part]))
            $this->children[$route_part] = new Route($sub_route, $this->depth + 1);

        return $this->children[$route_part];
    }

    /**
     * Find a app for the specified route (or part of it). This method
     * recursively delegates to the child nodes, until an app is found.
     *
     * index.php will match all other route endings. If a child node for a
     * route part exists, this child becomes responsible, and if it does not
     * resolve, null is returned, which should be interpreted as a 404 - Not
     * Found.
     *
     * @param array $parts The route parts to resolve
     * @param string $ext The file extension that may be removed from the route
     * @return array The resolved route, or null if none was found.
     */
    public function resolve(array $parts, string $ext)
    {
        $part = array_shift($parts);

        $sub_part = $part;
        if (!empty($ext) && substr($part, -strlen($ext)) === $ext)
            $sub_part = substr($part, 0, -strlen($ext));

        // Ask child routes to resolve the route
        if (isset($this->children[$sub_part]))
        {
            // When a sub route exists, there's not falling back to this level anymore.
            return $this->children[$sub_part]->resolve($parts, $ext);
            //if (!empty($route))
            //    return $route;
        }

        // No sub-route, so put the part back in place
        if (!empty($part) && $sub_part !== "index")
            array_unshift($parts, $part);
        $route = null;

        // Check if a ext-specific app is available
        if (!empty($ext) && isset($this->apps[$ext]))
            $route = $this->apps[$ext];

        // Check if a generic app is available
        if (empty($route) && isset($this->apps['_']))
            $route = $this->apps['_'];

        if (empty($route) && empty($ext) && !empty($this->apps))
        {
            $route = reset($this->apps);
            $route['ext'] = null;
        }

        if (!empty($route) && !empty($ext))
            $route['ext'] = $ext;

        if (!empty($route) && !isset($route['remainder']))
            $route['remainder'] = $parts;

        // Return the route
        return $route;
    }

    /**
     * Serialize the route.
     * @return string data The serialized route
     */
    public function serialize()
    {
        return serialize([
            'route' => $this->route,
            'depth' => $this->depth,
            'apps' => $this->apps,
            'children' => $this->children
        ]);
    }

    /**
     * Unserialize the route from serialized PHP data
     * @param string $data The PHP Serialized data
     */
    public function unserialize($data)
    {
        $data = unserialize($data);
        $this->route = $data['route'];
        $this->depth = $data['depth'];
        $this->apps = $data['apps'];
        $this->children = $data['children'];
    }
}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Server\Capabilities;

use Innmind\Rest\Client\{
    Server\Capabilities as CapabilitiesInterface,
    Server\DefinitionFactory,
    Definition\HttpResource,
    Exception\InvalidArgumentException,
    Format\Format,
    Formats,
};
use Innmind\HttpTransport\Transport;
use Innmind\Url\{
    UrlInterface,
    Url,
};
use Innmind\UrlResolver\ResolverInterface;
use Innmind\Http\{
    Message\Request\Request,
    Message\Method\Method,
    Headers\Headers,
    ProtocolVersion\ProtocolVersion,
    Header\Value,
    Header\LinkValue,
    Header\Accept,
    Header\AcceptValue,
};
use Innmind\Immutable\{
    MapInterface,
    SetInterface,
    Map,
    Set,
};

final class Capabilities implements CapabilitiesInterface
{
    private $fulfill;
    private $host;
    private $resolver;
    private $make;
    private $formats;
    private $optionsUrl;
    private $names;
    private $paths;
    private $definitions;

    public function __construct(
        Transport $fulfill,
        UrlInterface $host,
        ResolverInterface $resolver,
        DefinitionFactory $make,
        Formats $formats
    ) {
        $this->fulfill = $fulfill;
        $this->host = $host;
        $this->resolver = $resolver;
        $this->make = $make;
        $this->formats = $formats;
        $optionsUrl = $resolver->resolve((string) $host, '/*');
        $this->optionsUrl = Url::fromString($optionsUrl);
        $this->paths = new Map('string', UrlInterface::class);
        $this->definitions = new Map('string', HttpResource::class);
    }

    /**
     * {@inheritdoc}
     */
    public function names(): SetInterface
    {
        if ($this->names instanceof SetInterface) {
            return $this->names;
        }

        $headers = ($this->fulfill)
            (
                new Request(
                    $this->optionsUrl,
                    Method::options(),
                    new ProtocolVersion(1, 1)
                )
            )
            ->headers();

        if (!$headers->has('Link')) {
            return $this->names = new Set('string');
        }

        return $this->names = $headers
            ->get('Link')
            ->values()
            ->filter(function(Value $value): bool {
                return $value instanceof LinkValue;
            })
            ->reduce(
                new Set('string'),
                function(Set $names, LinkValue $link): Set {
                    $this->paths = $this->paths->put(
                        $link->relationship(),
                        $link->url()
                    );

                    return $names->add($link->relationship());
                }
            );
    }

    public function get(string $name): HttpResource
    {
        if (!$this->names()->contains($name)) {
            throw new InvalidArgumentException;
        }

        if ($this->definitions->contains($name)) {
            return $this->definitions->get($name);
        }

        $url = $this->resolver->resolve(
            (string) $this->host,
            (string) $this->paths->get($name)
        );
        $url = Url::fromString($url);
        $response = ($this->fulfill)(
            new Request(
                $url,
                Method::options(),
                new ProtocolVersion(1, 1),
                Headers::of(
                    new Accept(
                        ...$this
                            ->formats
                            ->all()
                            ->values()
                            ->sort(function(Format $a, Format $b): bool {
                                return $a->priority() < $b->priority();
                            })
                            ->reduce(
                                new Set(Value::class),
                                function(Set $values, Format $format): Set {
                                    return $values->add(new AcceptValue(
                                        $format->preferredMediaType()->topLevel(),
                                        $format->preferredMediaType()->subType()
                                    ));
                                }
                            )
                    )
                )
            )
        );
        $definition = ($this->make)(
            $name,
            $url,
            $response
        );
        $this->definitions = $this->definitions->put(
            $name,
            $definition
        );

        return $definition;
    }

    /**
     * {@inheritdoc}
     */
    public function definitions(): MapInterface
    {
        $this->names()->foreach(function(string $name) {
            $this->get($name);
        });

        return $this->definitions;
    }

    /**
     * {@inheritdoc}
     */
    public function refresh(): CapabilitiesInterface
    {
        $this->names = null;
        $this->paths = $this->paths->clear();
        $this->definitions = $this->definitions->clear();

        return $this;
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Core;

/**
 * Benchmark class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Benchmark
{
    const APPLICATION_MARKER = '_application_';

    /**
     * @var array
     */
    protected $markers = [];

    //TODO: add marker groups
    /**
     * @param string $marker
     */
    public function startMarker($marker)
    {
        $this->markers[$marker]['start']['time']   = microtime(true);
        $this->markers[$marker]['start']['memory'] = memory_get_usage();
    }

    /**
     * @param string $marker
     */
    public function stopMarker($marker)
    {
        $this->markers[$marker]['stop']['time']   = microtime(true);
        $this->markers[$marker]['stop']['memory'] = memory_get_usage();
    }

    /**
     * @param string $marker
     */
    public function deleteMarker($marker)
    {
        unset($this->markers[$marker]);
    }

    /**
     * @param string $marker
     *
     * @return array
     */
    public function getTotal($marker)
    {
        if (isset($this->markers[$marker]['total'])) {
            return $this->markers[$marker]['total'];
        }

        if ($marker === self::APPLICATION_MARKER) {
            $this->markers[self::APPLICATION_MARKER]['total']['time'] = microtime(true) - START_TIME;
            $this->markers[self::APPLICATION_MARKER]['total']['memory'] = memory_get_usage() - START_MEMORY;

            return $this->markers[self::APPLICATION_MARKER]['total'];
        }

        if (!isset($this->markers[$marker]['stop'])) {
            $marker_array = $this->markers[$marker];

            $marker_array['total']['time'] = microtime(true) - $marker_array['start']['time'];
            $marker_array['total']['memory'] = memory_get_usage() - $marker_array['memory']['time'];

            return $marker_array['total'];
        } else {
            $this->markers[$marker]['total']['time'] = $this->markers[$marker]['stop']['time'] - $this->markers[$marker]['start']['time'];
            $this->markers[$marker]['total']['memory'] = $this->markers[$marker]['stop']['memory'] - $this->markers[$marker]['memory']['time'];

            return $this->markers[$marker]['total'];
        }
    }

    /**
     * @param array $markers
     *
     * @return array
     */
    public function getMax(array $markers)
    {
        $max = [
            'time'   => 0,
            'memory' => 0,
        ];

        foreach ($markers as $marker) {
            $total = $this->getTotal($marker);

            if ($total['time'] > $max['time']) {
                $max['time'] = $total['time'];
            }

            if ($total['memory'] > $max['memory']) {
                $max['memory'] = $total['memory'];
            }
        }

        return $max;
    }

    /**
     * @param array $markers
     *
     * @return array
     */
    public function getMin(array $markers)
    {
        $min = [
            'time'   => 0,
            'memory' => 0,
        ];

        foreach ($markers as $marker) {
            $total = $this->getTotal($marker);

            if ($min['time'] === 0 || $total['time'] < $min['time']) {
                $min['time'] = $total['time'];
            }

            if ($min['memory'] === 0 || $total['memory'] < $min['memory']) {
                $min['memory'] = $total['memory'];
            }
        }

        return $min;
    }

    /**
     * @param array $markers
     *
     * @return array
     */
    public function getTotals(array $markers)
    {
        $totals = [
            'time'   => 0,
            'memory' => 0,
        ];

        foreach ($markers as $marker) {
            $total = $this->getTotal($marker);

            $totals['time']   += $total['time'];
            $totals['memory'] += $total['memory'];
        }

        return $totals;
    }

    /**
     * @param array $markers
     *
     * @return array
     */
    public function getAverage(array $markers)
    {
        $count = count($markers);
        $total = $this->getTotals($markers);

        $average = [
            'time' => $total['time'] / $count,
            'memory' => $total['memory'] / $count,
        ];

        return $average;
    }

    /**
     * @param array $markers
     *
     * @return array
     */
    public function getStatistic(array $markers)
    {
        return [
            'min'     => $this->getMax($markers),
            'max'     => $this->getMin($markers),
            'total'   => $this->getTotals($markers),
            'average' => $this->getAverage($markers),
        ];
    }

    /**
     * @return array
     */
    public function getAppStatistic()
    {
        return $this->getTotals([self::APPLICATION_MARKER]);
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

use Datetime;
use DateTimeInterface;
use InvalidArgumentException;
use Nette\InvalidStateException;
use Nette\SmartObject;

/**
 * Pomocna trida pro datum
 *
 * @author Attreid <attreid@gmail.com>
 */
class Date extends Lang
{
	use SmartObject;

	/** @var string[][] */
	private static $dayNamesShort = [
		'en' => [1 => 'mon', 2 => 'tue', 3 => 'wed', 4 => 'thu', 5 => 'fri', 6 => 'sat', 7 => 'sun'],
		'cs' => [1 => 'po', 2 => 'út', 3 => 'st', 4 => 'čt', 5 => 'pá', 6 => 'so', 7 => 'ne'],
		'de' => [1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'],
		'sk' => [1 => 'po', 2 => 'ut', 3 => 'st', 4 => 'št', 5 => 'pia', 6 => 'so', 7 => 'ne'],
		'pl' => [1 => 'pn', 2 => 'wt', 3 => 'śr', 4 => 'cz', 5 => 'pt', 6 => 'so', 7 => 'n'],
		'es' => [1 => 'Lun', 2 => 'Mar', 3 => 'Mié', 4 => 'Jue', 5 => 'Vie', 6 => 'Sáb', 7 => 'Dom'],
		'hu' => [1 => 'hét', 2 => 'kedd', 3 => 'sze', 4 => 'csüt', 5 => 'pén', 6 => 'szo', 7 => 'vas'],

	];

	/** @var string[][] */
	private static $dayNames = [
		'en' => [1 => 'sunday', 2 => 'monday', 3 => 'tuesday', 4 => 'wednesday', 5 => 'thursday', 6 => 'friday', 7 => 'saturday'],
		'cs' => [1 => 'neděle', 2 => 'pondělí', 3 => 'úterý', 4 => 'středa', 5 => 'čtvrtek', 6 => 'pátek', 7 => 'sobota'],
		'de' => [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'],
		'sk' => [1 => 'pondelok', 2 => 'utorok', 3 => 'streda', 4 => 'štvrtok', 5 => 'piatok', 6 => 'sobota', 7 => 'nedeľa'],
		'pl' => [1 => 'poniedziałek', 2 => 'wtorek', 3 => 'środa', 4 => 'czwartek', 5 => 'piątek', 6 => 'sobota', 7 => 'niedziela'],
		'es' => [1 => 'Lunes', 2 => 'Martes', 3 => 'Miércoles', 4 => 'Jueves', 5 => 'Viernes', 6 => 'Sábado', 7 => 'Domingo'],
		'hu' => [1 => 'hétfő', 2 => 'kedd', 3 => 'szerda', 4 => 'csütörtök', 5 => 'péntek', 6 => 'szombat', 7 => 'vasárnap'],
	];

	/** @var string[][] */
	private static $monthNamesShort = [
		'en' => [1 => 'jan', 2 => 'feb', 3 => 'mar', 4 => 'apr', 5 => 'may', 6 => 'jun', 7 => 'jul', 8 => 'aug', 9 => 'sep', 10 => 'oct', 11 => 'nov', 12 => 'dec'],
		'cs' => [1 => 'led', 2 => 'úno', 3 => 'bře', 4 => 'dub', 5 => 'kvě', 6 => 'čer', 7 => 'črn', 8 => 'srp', 9 => 'zář', 10 => 'říj', 11 => 'lis', 12 => 'pro'],
		'de' => [1 => 'Jan', 2 => 'Feb', 3 => 'Mär', 4 => 'Apr', 5 => 'Mai', 6 => 'Jun', 7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Dez'],
		'sk' => [1 => 'jan', 2 => 'feb', 3 => 'mar', 4 => 'apr', 5 => 'máj', 6 => 'jún', 7 => 'júl', 8 => 'aug', 9 => 'sep', 10 => 'okt', 11 => 'nov', 12 => 'dez'],
		'pl' => [1 => 'sty', 2 => 'lu', 3 => 'mar', 4 => 'kw', 5 => 'maj', 6 => 'cze', 7 => 'lip', 8 => 'sie', 9 => 'wrz', 10 => 'pa', 11 => 'lis', 12 => 'gru'],
		'es' => [1 => 'Ene', 2 => 'Feb', 3 => 'Mar', 4 => 'Abr', 5 => 'May', 6 => 'Jun', 7 => 'Jul', 8 => 'Ago', 9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dic'],
		'hu' => [1 => 'jan', 2 => 'feb', 3 => 'márc', 4 => 'ápr', 5 => 'máj', 6 => 'jún', 7 => 'júl', 8 => 'aug', 9 => 'szept', 10 => 'okt', 11 => 'nov', 12 => 'dec'],
	];

	/** @var string[][] */
	private static $monthNames = [
		'en' => [1 => 'january', 2 => 'february', 3 => 'march', 4 => 'april', 5 => 'may', 6 => 'june', 7 => 'july', 8 => 'august', 9 => 'september', 10 => 'october', 11 => 'november', 12 => 'december'],
		'cs' => [1 => 'leden', 2 => 'únor', 3 => 'březen', 4 => 'duben', 5 => 'květen', 6 => 'červen', 7 => 'červenec', 8 => 'srpen', 9 => 'září', 10 => 'říjen', 11 => 'listopad', 12 => 'prosinec'],
		'de' => [1 => 'Januar', 2 => 'Februar', 3 => 'März', 4 => 'April', 5 => 'Mai', 6 => 'Juni', 7 => 'Juli', 8 => 'August', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Dezember'],
		'sk' => [1 => 'január', 2 => 'február', 3 => 'marec', 4 => 'apríl', 5 => 'máj', 6 => 'jún', 7 => 'júl', 8 => 'august', 9 => 'september', 10 => 'október', 11 => 'november', 12 => 'december'],
		'pl' => [1 => 'styczeń', 2 => 'luty', 3 => 'marzec', 4 => 'kwiecień', 5 => 'maj', 6 => 'czerwiec', 7 => 'lipiec', 8 => 'sierpień', 9 => 'wrzesień', 10 => 'październik', 11 => 'listopad', 12 => 'grudzień'],
		'es' => [1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', 5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto', 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'],
		'hu' => [1 => 'január', 2 => 'február', 3 => 'március', 4 => 'április', 5 => 'május', 6 => 'június', 7 => 'július', 8 => 'augusztus', 9 => 'szeptember', 10 => 'október', 11 => 'november', 12 => 'december'],
	];

	/** @var string[][] */
	private static $date = [
		'en' => 'n/j/Y',
		'cs' => 'j.n.Y',
		'de' => 'j.n.Y',
		'sk' => 'j.n.Y',
		'pl' => 'j.n.Y',
		'es' => 'j/n/Y',
		'hu' => 'Y.n.j.',
	];

	/** @var string[][] */
	private static $time = [
		'en' => 'G:i',
		'cs' => 'G:i',
		'de' => 'G:i',
		'sk' => 'G:i',
		'pl' => 'G:i',
		'es' => 'G:i',
		'hu' => 'G:i',
	];

	/** @var string[][] */
	private static $seconds = [
		'en' => ':s',
		'cs' => ':s',
		'de' => ':s',
		'sk' => ':s',
		'pl' => ':s',
		'es' => ':s',
		'hu' => ':s',
	];

	/**
	 * Formatovani
	 * @param bool $date
	 * @param bool $time
	 * @param bool $seconds
	 * @return string
	 */
	public static function getFormat(bool $date = true, bool $time = true, bool $seconds = false): string
	{
		$format = null;
		if ($date) {
			$format .= self::$date[self::$locale];
		}

		if ($time) {
			if (!empty($format)) {
				$format .= ' ';
			}

			$format .= self::$time[self::$locale];

			if ($seconds) {
				$format .= self::$seconds[self::$locale];
			}
		}

		if ($format === null) {
			throw new InvalidStateException;
		}

		return $format;
	}

	/**
	 * Vrati pocatecni rok - aktualni rok. V pripade, ze se shoduji pouze aktualni
	 * @param int $beginYear pocatecni rok
	 * @return string napr: 2012 - 2014 nebo pouze 2014
	 */
	public static function getYearToActual(int $beginYear): string
	{
		$actualYear = strftime('%Y');
		if ($beginYear == $actualYear) {
			return $actualYear;
		} else {
			return $beginYear . ' - ' . $actualYear;
		}
	}

	/**
	 * Vrati aktualni cas na milivteriny
	 * @return string
	 */
	public static function getCurrentTimeStamp(): string
	{
		$t = microtime(true);
		$micro = sprintf('%06d', ($t - floor($t)) * 1000000);
		$d = new DateTime(date('Y-m-d H:i:s.' . $micro, (int) $t));
		return $d->format('Y_m_d_H_i_s_u');
	}

	/**
	 * Vrati nazev dne
	 * @param int|DateTimeInterface $day
	 * @return string
	 */
	public static function getDay($day): string
	{
		if ($day instanceof DateTimeInterface) {
			$day = (int) $day->format('N');
		}
		if (!is_int($day)) {
			throw new InvalidArgumentException;
		}
		return self::$dayNames[self::$locale][$day];
	}

	/**
	 * Vrati zkraceny nazev dne
	 * @param int|DateTimeInterface $day
	 * @return string
	 */
	public static function getShortDay($day): string
	{
		if ($day instanceof DateTimeInterface) {
			$day = (int) $day->format('N');
		}
		if (!is_int($day)) {
			throw new InvalidArgumentException;
		}
		return self::$dayNamesShort[self::$locale][$day];
	}

	/**
	 * Vrati nazev mesice
	 * @param int|DateTimeInterface $month
	 * @return string
	 */
	public static function getMonth($month): string
	{
		if ($month instanceof DateTimeInterface) {
			$month = (int) $month->format('n');
		}
		if (!is_int($month)) {
			throw new InvalidArgumentException;
		}
		return self::$monthNames[self::$locale][$month];
	}

	/**
	 * Vrati zkraceny nazev mesice
	 * @param int|DateTimeInterface $month
	 * @return string
	 */
	public static function getShortMonth($month): string
	{
		if ($month instanceof DateTimeInterface) {
			$month = (int) $month->format('n');
		}
		if (!is_int($month)) {
			throw new InvalidArgumentException;
		}
		return self::$monthNamesShort[self::$locale][$month];
	}

	/**
	 * Vrati nazvy dnu
	 * @return string[]
	 */
	public static function getDays(): array
	{
		return self::$dayNames[self::$locale];
	}

	/**
	 * Vrati zkracene nazvy dnu
	 * @return string[]
	 */
	public static function getShortDays(): array
	{
		return self::$dayNamesShort[self::$locale];
	}

	/**
	 * Vrati nazvy mesicu
	 * @return string[]
	 */
	public static function getMonths(): array
	{
		return self::$monthNames[self::$locale];
	}

	/**
	 * Vrati zkracene nazvy mesicu
	 * @return string[]
	 */
	public static function getShortMonths(): array
	{
		return self::$monthNamesShort[self::$locale];
	}

	/**
	 * Vrati lokalizovany format data
	 * @param DateTimeInterface|int $datetime
	 * @param string $format
	 * @return string|null
	 */
	private static function formatDate($datetime, string $format): ?string
	{
		if (empty($datetime)) {
			return null;
		} elseif ($datetime instanceof DateTimeInterface) {
			$date = $datetime;
		} else {
			$date = DateTime::createFromFormat('U', (string) $datetime);
		}
		return $date->format($format);
	}

	/**
	 * Lokalizovane datum
	 * @param DateTimeInterface|int $datetime datum nebo timestamp
	 * @return string|null
	 */
	public static function getDate($datetime): ?string
	{
		return self::formatDate($datetime, self::getFormat(true, false, false));
	}

	/**
	 * Lokalizovane datum s casem
	 * @param DateTimeInterface|int $datetime datum nebo timestamp
	 * @param bool $withSeconds
	 * @return null|string
	 */
	public static function getDateTime($datetime, bool $withSeconds = false): ?string
	{
		return self::formatDate($datetime, self::getFormat(true, true, $withSeconds));
	}

	/**
	 * Lokalizovany cas
	 * @param DateTimeInterface|int $datetime datum nebo timestamp
	 * @param bool $withSeconds
	 * @return null|string
	 */
	public static function getTime($datetime, bool $withSeconds = false): ?string
	{
		return self::formatDate($datetime, self::getFormat(false, true, $withSeconds));
	}

	/**
	 * Vrati predchozi mesic
	 * @return Range
	 */
	public static function getPreviousMonth(): Range
	{
		return new Range(new DateTime('first day of last month'), new DateTime('last day of last month'));
	}

}


<?php

namespace Amcms;

use Slim\App;

class Application extends App
{
    /**
     * Create a new Application Instance
     */
    public function __construct($container = [])
    {
        parent::__construct($container);
        $this->registerBaseServices();
    }

    /**
     * Register some "internal" services
     * @return void
     */
    public function registerBaseServices()
    {
        //see example https://github.com/slimphp/Slim/blob/3.x/Slim/DefaultServicesProvider.php
        $container = $this->getContainer();

        // wrapper for Request validation
        if (!isset($container['validator'])) {
            $container['validator'] = new \Amcms\Services\ValidatorService($container);
        }

        // Auth service
        if (!isset($container['auth'])) {
            $container['auth'] = new \Amcms\Services\AuthService($container);
        }

        // Twig View
        if (!isset($container['twig'])) {
            $container['twig'] = function ($c) {
                $isDebug = $c['settings']['debug'] ?: false;
                $twigTemplatesPath = $c['path'] . '/' . (isset($c['settings']['templates']['twig']['template_path']) ? trim($c['settings']['templates']['twig']['template_path'], '/') : 'resources/views/templates');
                $twigCachePath = $c['path'] . '/' . (isset($c['settings']['templates']['twig']['cache_path']) ? trim($c['settings']['templates']['twig']['cache_path'], '/') : 'storage/cache');

                $view = new \Amcms\View\TwigView($twigTemplatesPath, [
                    'cache' => $twigCachePath,
                    'debug' => $isDebug,
                    // 'auto_update' => false,
                ]);

                $view->addExtension(new \Amcms\View\TwigExtension($c));

                return $view;
            };
        }
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: LabelList.php 543 2009-10-03 08:50:00Z mr_a_ton$
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\Element;

/**
 * LebelText - class LabelText is element that view value who binds
 * with a BizField
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2009
 * @version 1.0
 * @access public
 */
class LabelText extends Element
{

    public $fieldName;
    public $label;
    public $displayFormat;
    public $text;
    public $link;
    public $target;
    public $maxLength;
    public $percent;
    public $stripTags;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->fieldName = isset($xmlArr["ATTRIBUTES"]["FIELDNAME"]) ? $xmlArr["ATTRIBUTES"]["FIELDNAME"] : null;
        $this->label = isset($xmlArr["ATTRIBUTES"]["LABEL"]) ? $xmlArr["ATTRIBUTES"]["LABEL"] : null;
        $this->text = isset($xmlArr["ATTRIBUTES"]["TEXT"]) ? $xmlArr["ATTRIBUTES"]["TEXT"] : null;

        //$this->text .= "haiii ...";

        /*
        if (strpos($this->text, 'Openbizx')) {
            echo __METHOD__ . ' : ' . $this->text . '
';
            echo __METHOD__ . ' : ' . $this->getText() . '
';
        }
        */

        $this->link = isset($xmlArr["ATTRIBUTES"]["LINK"]) ? $xmlArr["ATTRIBUTES"]["LINK"] : null;
        $this->target = isset($xmlArr["ATTRIBUTES"]["TARGET"]) ? $xmlArr["ATTRIBUTES"]["TARGET"] : null;
        $this->maxLength = isset($xmlArr["ATTRIBUTES"]["MAXLENGHT"]) ? $xmlArr["ATTRIBUTES"]["MAXLENGHT"] : null;
        $this->maxLength = isset($xmlArr["ATTRIBUTES"]["MAXLENGTH"]) ? $xmlArr["ATTRIBUTES"]["MAXLENGTH"] : null;
        $this->percent = isset($xmlArr["ATTRIBUTES"]["PERCENT"]) ? $xmlArr["ATTRIBUTES"]["PERCENT"] : "N";
        $this->displayFormat = isset($xmlArr["ATTRIBUTES"]["DISPLAYFORMAT"]) ? $xmlArr["ATTRIBUTES"]["DISPLAYFORMAT"] : null;
        $this->stripTags = isset($xmlArr["ATTRIBUTES"]["STRIPTAGS"]) ? $xmlArr["ATTRIBUTES"]["STRIPTAGS"] : "N";
    }

    /**
     * Get target of link
     * ...
     *
     * @return string
     */
    protected function getTarget()
    {
        if ($this->target == null) {
            return null;
        }
        return "target='" . $this->target . "'";
    }

    /**
     * Get link of LabelText
     *
     * @return string
     */
    protected function getLink()
    {
        if ($this->link == null) {
            return null;
        }
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

    /**
     * Get text of label
     *
     * @return string
     */
    protected function getText()
    {
        if ($this->text == null) {
            return null;
        }
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formObj);
    }

    /**
     * Render label
     *
     * @return string HTML text
     */
    public function renderLabel()
    {
        return $this->label;
    }

    /**
     * Render, draw the element according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $value = $this->text ? $this->getText() : $this->value;
        if ($value === null || $value === "") {// why do we ignore empty?
            return "";
        }

        $style = $this->getStyle();
        $id = $this->objectName;
        $func = $this->getFunction();

        if ($this->translatable == 'Y') {
            $value = $this->translateString($value);
        }
        $value_org = strip_tags($value);
        if ((int) $this->maxLength > 0) {
            if (function_exists('mb_strlen') && function_exists('mb_substr')) {
                if (mb_strlen($value, 'UTF8') > (int) $this->maxLength) {
                    $value = mb_substr($value, 0, (int) $this->maxLength, 'UTF8') . '...';
                }
            } else {
                if (strlen($value) > (int) $this->maxLength) {
                    $value = substr($value, 0, (int) $this->maxLength) . '...';
                }
            }
        }

        if ($value !== null) {
            if ($this->displayFormat) {
                $value = sprintf($this->displayFormat, $value);
            }
            if ($this->percent == 'Y') {
                $value = sprintf("%.2f", $value * 100) . '%';
            } else {
                if (strtoupper($this->stripTags) == 'Y') {
                    $value = strip_tags($value);
                } else {
                    $value = htmlentities($value, ENT_QUOTES, "UTF-8");
                }
            }

            if ($this->link) {
                $link = $this->getLink();
                $target = $this->getTarget();
                //$sHTML = "" . $val . "";
                $sHTML = "htmlAttr>" . $value . "";
            } else {
                $sHTML = "htmlAttr>" . $value . "";
            }
            if ($this->backgroundColor) {
                $bgcolor = $this->getBackgroundColor();
                if ($bgcolor) {
                    $sHTML = "
$sHTML
";
                }
            }
        }

        return $sHTML;
    }

}


<?php

/*
 * Copyright (c) 2012-2014 Alessandro Siragusa <alessandro@togu.io>
 *
 * This file is part of the Togu CMS.
 *
 * Togu is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Togu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Togu.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Togu\AdminBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\View\View;
use \JMS\Serializer\SerializationContext;
use \Doctrine\DBAL\DBALException;
use \JMS\Serializer\DeserializationContext;
use FOS\RestBundle\Controller\Annotations\Route;
use Application\Togu\ApplicationModelsBundle\Document\Page;
use Application\Togu\ApplicationModelsBundle\Document\Section;

/**
 * Class PageController
 * @package Togu\MediaBundle\Controller
 */
class SectionTreeController extends FOSRestController {

    /**
     * Get the Sections records corresponding to the url or null
     * @param ParamFetcherInterface $paramFetcher
     *
     * @Route(requirements={"url"=".+"})
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
	public function getIsurlavailableAction($url) {
		$manager = $this->get('doctrine_phpcr.odm.default_document_manager');

		try {
			$routeInfo = $this->get('router')->match($url);

			if(! isset($routeInfo['type']) || ! isset($routeInfo['_route'])) {
				$view = View::create(array(
					"forbidden" => true
				), 200);
				return $this->handleView($view);
			}
			$route = $manager->find(null, $routeInfo['_route']);
			$document = $route->getContent();
			if($document && $document instanceof Page) {
				$sectionConfig = $document->getSection()->getSectionConfig();

				$view = View::create(array(
					"id" => $sectionConfig->getId()
				), 200);
				return $this->handleView($view);
			}
		} catch (\Exception $e) {
		}
		$view = View::create(array(
			"available" => true
		), 200);
		return $this->handleView($view);
	}

    /**
     * Get list of a Sections records
     * @param ParamFetcherInterface $paramFetcher
     *
     * @Route(requirements={"id"=".+"})
     *
     * @QueryParam(name="group", description="The JMS Serializer group", default="")
     * @QueryParam(name="depth", description="The depth to use for serialization", default="1")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getSectiontreeAction($id, ParamFetcherInterface $paramFetcher) {
        $manager = $this->get('doctrine_phpcr.odm.default_document_manager');

        $parent = $manager->find(null, $id);

        if(! $parent instanceof Section) {
        	$parent = $parent->getSectionConfig();
        }

        $children = $parent->getNextSection();
        $list = array();
        foreach ($children as $section) {
        	$list[] = $section->getSectionConfig();
        }

        $context = $this->getSerializerContext(array('list'));
        $view = View::create($list, 200)->setSerializationContext($context);
        return $this->handleView($view);
    }

    /**
     * Create a new Section record
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function postSectiontreeAction() {
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $entity = $serializer->deserialize(
            $this->getRequest()->getContent(),
            'Application\Togu\ApplicationModelsBundle\Document\Section',
            'json',
            DeserializationContext::create()->setGroups(array("Default", "post"))
        );
		$modelLoader = $this->get('togu.generator.model.config');
		if(! $modelLoader->hasModel($entity->getType())) {
			throw new \InvalidArgumentException(sprintf('The model %s does not exist', $entity->getType()));
		}
        $validator = $this->get('validator');
        $validations = $validator->validate($entity, array('Default', 'post'));
        if ($validations->count() === 0) {
            $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
            $rootData = $manager->find(null, '/data');

            $sectionClassName = $modelLoader->getFullClassName($entity->getType());
            $section = new $sectionClassName(array(
				"sectionConfig" => $entity,
            	"parentDocument" => $rootData
            ));
            $entity->getParentSection()->getSectionConfig()->addNextSection($section);
            $entity->getPage()->setSection($section);
            $manager->persist($entity);
            $manager->persist($section);
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
                	"success" => true,
                	"records" => array($entity)
                ), 200)->setSerializationContext($this->getSerializerContext(array('Default', 'post')))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Update an existing Section record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function putSectiontreeAction($id) {
        $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository('ApplicationToguApplicationModelsBundle:Section')->find($id);
        if ($entity === null) {
            return $this->handleView(View::create('', 404));
        }
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $entity = $serializer->deserialize(
            $this->getRequest()->getContent(),
            'Application\Togu\ApplicationModelsBundle\Document\Section',
            'json',
            DeserializationContext::create()->setGroups(array("Default", "put"))
        );
        $validator = $this->get('validator', array('Default', 'put'));
        $validations = $validator->validate($entity);
        if ($validations->count() === 0) {
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
                	"success" => true,
                	"records" => array($entity)
                ), 200)->setSerializationContext($this->getSerializerContext(array("get")))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Patch an existing Section record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function patchSectiontreeAction($id) {
        $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository('ApplicationToguApplicationModelsBundle:Section')->find($id);
        if ($entity === null) {
            return $this->handleView(View::create('', 404));
        }
        $content = json_decode($this->getRequest()->getContent(), true);
        $content['id'] = $id;
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $dContext = DeserializationContext::create()->setGroups(array("Default", "patch"));
        $dContext->attributes->set('related_action', 'merge');
        $entity = $serializer->deserialize(
            json_encode($content),
            'Application\Togu\ApplicationModelsBundle\Document\Section',
            'json',
            $dContext
        );
        $validator = $this->get('validator');
        $validations = $validator->validate($entity, array('Default', 'patch'));
        if ($validations->count() === 0) {
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
                	"success" => true,
                	"records" => array($entity)
                ), 200)->setSerializationContext($this->getSerializerContext(array("get")))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

    /**
     * Delete an existing Section record
     * @param $id
     *
     * @Route(requirements={"id"=".+"})
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function deleteSectiontreeAction($id) {
        $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
        $entity = $manager->getRepository('ApplicationToguApplicationModelsBundle:Section')->find($id);
        $manager->remove($entity);
        $manager->flush();
        return $this->handleView(View::create(null, 204));
    }

    protected function getSerializerContext($groups = array(), $version = null) {
        $serializeContext = SerializationContext::create();
        $serializeContext->enableMaxDepthChecks();
        $serializeContext->setGroups(array_merge(
            array(\JMS\Serializer\Exclusion\GroupsExclusionStrategy::DEFAULT_GROUP),
            $groups
        ));
        if ($version !== null) $serializeContext->setVersion($version);
        return $serializeContext;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: hua
 * Date: 2018/9/25
 * Time: 下午12:32
 */

namespace DdvPhp\DdvUtil\Laravel\Proxy\Traits;

use Closure;
use ReflectionMethod;
use ReflectionFunction;
use ReflectionParameter;
use ReflectionException;

trait Parameters
{
    /**
     * @var callable|array|string|Closure $handler
     */
    protected $handler;

    /**
     * 参数
     * @var array
     */
    protected $parameters;

    /**
     * 所有参数的反射
     * @var ReflectionParameter[] $reflectionParameters
     */
    protected $reflectionParameters = array();

    /**
     * 空参数反射
     * @var ReflectionParameter[] $reflectionParameters
     */
    protected $nullParameterReflections = array();

    /**
     * Parameters constructor.
     * @param callable|array|string|Closure $handler
     * @param $parameters
     * @throws ReflectionException
     */
    public function __construct($handler, $parameters)
    {
        // 存储监听
        $this->handler = $handler;
        // 参数存起来
        $this->parameters = &$parameters;
        unset($handler, $parameters);
        // 初始化
        $this->init();
    }

    /**
     * Notes:
     * User: yao
     * Date: 2018/9/18
     * Time: 15:49
     * @throws ReflectionException
     */
    protected function init()
    {
        // 存储参数
        $this->getReflectionParameters();
        // 空参数
        foreach ($this->reflectionParameters as $index => $parameter) {
            // 判断参数是否存在参数
            if (!isset($this->parameters[$index])){
                // 填充参数 为 null
                $this->parameters[$index] = null;
                // 填充反射
                $this->nullParameterReflections[$index] = $parameter;
            }
        };
        /**
         * 遍历所有没有设置的参数
         * 把$this设置进去
         */
        $this->mapNullParameters(function (&$value, $name, $index, ReflectionParameter $parameter) {
            $className = $parameter->getClass();
            $isSet = false;
            if (!empty($className)) {
                if ($className->isInstance($this)) {
                    // 返回控制器
                    $value = $this;
                    $isSet = true;
                }
            }
            unset($value, $name, $index, $className, $parameter);
            return $isSet;
        });
    }

    /**
     * 遍历空参数的反射
     * @param callable|array|string|Closure $handler
     * @return $this
     */
    public function mapNullParameters($hander)
    {
        foreach ($this->nullParameterReflections as $index => $parameter) {
            if (call_user_func_array($hander, [&$this->parameters[$index], $parameter->getName(), $index, $parameter])) {
                unset($this->nullParameterReflections[$index]);
            };
        }
        return $this;
    }

    /**
     * 遍历空参数的反射
     * @param callable|array|string|Closure $handler
     * @return $this
     */
    public function mapParameters($hander)
    {
        foreach ($this->reflectionParameters as $index => $parameter) {
            call_user_func_array($hander, [&$this->parameters[$index], $parameter->getName(), $index, $parameter]);
        }
        return $this;
    }

    /**
     * 把参数转数组
     * @return array
     */
    public function toArray()
    {
        $res = array();
        $this->mapParameters(function ($name, &$value, $parameter) use (&$res) {
            $res[$name] = $value;
        });
        return $res;
    }

    /**
     * 获取参数
     * @return array
     */
    public function &getParameters()
    {
        return $this->parameters;
    }

    /**
     * 获取一个反射参数数组
     * @param callable $handler
     * @return ReflectionParameter[] The parameters, as a ReflectionParameter objects.
     * @throws ReflectionException
     */
    public function getReflectionParameters()
    {
        if (!empty($this->reflectionParameters)) {
            return $this->reflectionParameters;
        }
        if (is_object($this->handler) && is_callable($this->handler)) {
            if ($this->handler instanceof Closure) {
                $this->reflectionParameters = (new ReflectionFunction($this->handler))->getParameters();
            }
        } elseif (is_string($this->handler)) {
            if (function_exists($this->handler)) {
                $this->reflectionParameters = (new ReflectionFunction($this->handler))->getParameters();
            } elseif (strpos($this->handler, '::') !== false) {
                list($className, $method) = explode('::', $this->handler, 2);
                if (method_exists($className, $method)) {
                    $this->reflectionParameters = (new ReflectionMethod($className, $method))->getParameters();
                }
            }
        } elseif (is_array($this->handler) && count($this->handler) === 2 && method_exists($this->handler[0], $this->handler[1])) {
            $this->reflectionParameters = (new ReflectionMethod($this->handler[0], $this->handler[1]))->getParameters();
        }
        return array();
    }
}


<?php
namespace Larakit\Twig;

class CommandNsView extends \Illuminate\Console\Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'larakit:show:ns-view';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Показать пространства имен View';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */

    public function handle() {
        //################################################################################
        // ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ
        //################################################################################
        $hints = app('view')->getFinder()->getHints();
        ksort($hints);
        $rows = [];
        foreach($hints as $k => $_hints) {
            foreach($_hints as $h) {
                $rows[] = [
                    $k,
                    larasafepath(realpath($h)),
                ];
            }

        }

        $this->table([
            'Ns',
            'Path',
        ], $rows);
        //        dd(Twig::$extensions,Twig::$filters,Twig::$functions,Twig::$globals,Twig::$tests);
    }

}


<?php
/**
 * Instaphp
 *
 * Copyright (c) 2011 randy sesser <randy@instaphp.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author randy sesser <randy@instaphp.com>
 * @copyright 2011, randy sesser
 * @license http://www.opensource.org/licenses/mit-license The MIT License
 * @package Instaphp
 * @filesource
 */

namespace Instaphp;

/**
 * The Response object.
 * This is the object passed back to the caller of this framework. It mimcs
 * Instagram's JSON objects returned from most (if not all) of its current
 * endpoints. Not all properties will be populated, so isset() should be used
 * when dealing with a response object's properties
 * @package Instaphp
 * @version 1.0
 * @author randy sesser <randy@instaphp.com>
 */
class Response
{
	/**
	 * Technical information about the http response
	 *
	 * @var array
	 * @access public
	 */
	public $info;
    /**
     * The meta "object" (contains a status code. 200 when successful)
     * @var object
     * @access public
     */
    public $meta = null;
    /**
     * The data "object" contains everything. Too much to list here.
     * See {@link https://api.instagram.com/developer/ Instagram Developer API}
     * @var object
     * @access public
     */
    public $data = null;
    /**
     * The pagination "object" is not your typical pagination
     * @var object
     * @access public
     */
    public $pagination = null;
    /**
     * If an error occurred, this will be populated. Check here first.
     *
     * if (!empty(\$response->error)) {
     *  echo \$response->error->message;
     * }
     *
     * @var Error
     * @access public
     */
    public $error = null;
    /**
     * When authenticating, this is populated with the access token and basic
     * user info returned from the API
     * @var object
     * @access public
     */
    public $auth = null;
	/**
	 * For embeded calls
	 *
	 * @var object
	 * @access public
	 **/
	public $embed = null;
    /**
     * This is the raw JSON response returned from the API. Usefull if
     * you just want a "passthrough" situation or perhaps you want to embed
     * the JSON string in the page and parse it with JavaScript.
     *
     * var response = JSON.parse('<?php echo \$response->json ?>');
     *
     * @var string
     * @access public
     */
    public $json = '';

    public function __construct()
    {

    }

    /**
     * A convenience method to parse the response text and build a Response object
     * @access public
     * @static
     * @param string $responseText The response from the API call
     * @param string $url The url used to generate the Response object
     * @return Response
     */
    public static function Create(Request $request, Response $response)
    {
        $obj = json_decode($response->json);

		//-- for embeded calls, just return the embeded object
		if (isset($obj->{'provider_url'}) && !empty($obj->{'provider_url'})) {
			$response->embed = $obj;
			return $response;
		}

        if (empty($obj)) {
			$error = new Error;
			$error->type = 'cURLResponseError';
			$error->code = $response->info['http_code'];
			$error->url = $response->info['url'];
			switch ($error->code)
			{
				case 505:
					$error->message = 'HTTP version not supported? Weird.';
					break;
				case 504:
					$error->message = 'Gateway timeout. Sorry.';
					break;
				case 503:
					$error->message = 'The API is currently unavailable';
					break;
				case 502:
					$error->message = 'Baaaaaaaaad gateway!';
					break;
				case 501:
					$error->message = 'Sorry, not implemented... YET.';
					break;
				case 500:
					$error->message = 'Whoops! API just barfed on your new shoes.';
					break;
				case 405:
					$error->message = 'Method not allowed.';
					break;
				case 404:
					$error->message = 'Received a 404 from the API';
					break;
				case 403:
					$error->message = 'The API says you are forbidden';
					break;
				case 402:
					$error->message = 'The API claims you own them money.';
					break;
				case 401:
					$error->message = 'The API says you are unauthorized.';
					break;
				case 400:
					$error->message = 'POBR... Plain Old Bad Request.';
					break;
				default:
					$error->message = 'Unknown error ocurred making this request';
					break;
			}
			$response->error = $error;
        }

        if (isset($obj->{'error_message'})) {
            $response->error = new Error($obj->{'error_type'}, $obj->{'code'}, $obj->{'error_message'}, $response->info['url']);
        }

        if (isset($obj->{'access_token'})) {
            $response->auth->access_token = $obj->{'access_token'};
            $response->auth->user = $obj->{'user'};
        }

        if (isset($obj->{'meta'}))
            $response->meta = $obj->{'meta'};

        if (isset($obj->{'meta'}) && $obj->{'meta'}->code !== 200) {
            $response->error = new Error($response->meta->error_type, $response->meta->code, $response->meta->error_message, $response->info['url']);
            $query = '';

        }

        if (isset($obj->{'data'}))
            $response->data = $obj->{'data'};

        if (isset($obj->{'pagination'}))
            $response->pagination = $obj->{'pagination'};

        return $response;
    }

	private static function fixNonUtf8Chars($data)
	{
	    $aux = str_split($data);
	    foreach($aux as $a) {
	        $a1 = urlencode($a);
	        $aa = explode("%", $a1);

	        foreach($aa as $v)
	            if($v!="")
	                if(hexdec($v)>127)
	                	$data = str_replace($a,"&#".hexdec($v).";",$data);

	    }

	    return $data;
	}
}


<?php
/**
 * OAuth 2.0 session entity
 *
 */

namespace OAuth2\Server\Entity;

use OAuth2\Server\AbstractServer;

/**
 * Session entity grant
 */
class SessionEntity
{
    /**
     * Session identifier
     *
     * @var string
     */
    protected $id;

    /**
     * Client identifier
     *
     * @var \OAuth2\Server\Entity\ClientEntity
     */
    protected $client;

    /**
     * Session owner identifier
     *
     * @var string
     */
    protected $ownerId;

    /**
     * Session owner type (e.g. "user")
     *
     * @var string
     */
    protected $ownerType;

    /**
     * Auth code
     *
     * @var \OAuth2\Server\Entity\AuthCodeEntity
     */
    protected $authCode;

    /**
     * Access token
     *
     * @var \OAuth2\Server\Entity\AccessTokenEntity
     */
    protected $accessToken;

    /**
     * Refresh token
     *
     * @var \OAuth2\Server\Entity\RefreshTokenEntity
     */
    protected $refreshToken;

    /**
     * Session scopes
     *
     * @var \Symfony\Component\HttpFoundation\ParameterBag
     */
    protected $scopes;

    /**
     * Authorization or resource server
     *
     * @var \OAuth2\Server\AuthorizationServer|\OAuth2\Server\ResourceServer
     */
    protected $server;

    /**
     * __construct
     *
     * @param \OAuth2\Server\AbstractServer $server
     *
     * @return self
     */
    public function __construct(AbstractServer $server)
    {
        $this->server = $server;

        return $this;
    }

    /**
     * Set the session identifier
     *
     * @param string $id
     *
     * @return self
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Return the session identifier
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Associate a scope
     *
     * @param \OAuth2\Server\Entity\ScopeEntity $scope
     *
     * @return self
     */
    public function associateScope(ScopeEntity $scope)
    {
        if (!isset($this->scopes[$scope->getId()])) {
            $this->scopes[$scope->getId()] = $scope;
        }

        return $this;
    }

    /**
     * Check if access token has an associated scope
     *
     * @param string $scope Scope to check
     *
     * @return bool
     */
    public function hasScope($scope)
    {
        if ($this->scopes === null) {
            $this->getScopes();
        }

        return isset($this->scopes[$scope]);
    }

    /**
     * Return all scopes associated with the session
     *
     * @return \OAuth2\Server\Entity\ScopeEntity[]
     */
    public function getScopes()
    {
        if ($this->scopes === null) {
            $this->scopes = $this->formatScopes($this->server->getSessionStorage()->getScopes($this));
        }

        return $this->scopes;
    }

    /**
     * Format the local scopes array
     *
     * @param  \OAuth2\Server\Entity\Scope[]
     *
     * @return array
     */
    private function formatScopes($unformatted = [])
    {
        $scopes = [];
        if (is_array($unformatted)) {
            foreach ($unformatted as $scope) {
                if ($scope instanceof ScopeEntity) {
                    $scopes[$scope->getId()] = $scope;
                }
            }
        }

        return $scopes;
    }

    /**
     * Associate an access token with the session
     *
     * @param \OAuth2\Server\Entity\AccessTokenEntity $accessToken
     *
     * @return self
     */
    public function associateAccessToken(AccessTokenEntity $accessToken)
    {
        $this->accessToken = $accessToken;

        return $this;
    }

    /**
     * Associate a refresh token with the session
     *
     * @param \OAuth2\Server\Entity\RefreshTokenEntity $refreshToken
     *
     * @return self
     */
    public function associateRefreshToken(RefreshTokenEntity $refreshToken)
    {
        $this->refreshToken = $refreshToken;

        return $this;
    }

    /**
     * Associate a client with the session
     *
     * @param \OAuth2\Server\Entity\ClientEntity $client The client
     *
     * @return self
     */
    public function associateClient(ClientEntity $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * Return the session client
     *
     * @return \OAuth2\Server\Entity\ClientEntity
     */
    public function getClient()
    {
        if ($this->client instanceof ClientEntity) {
            return $this->client;
        }

        $this->client = $this->server->getClientStorage()->getBySession($this);

        return $this->client;
    }

    /**
     * Set the session owner
     *
     * @param string $type The type of the owner (e.g. user, app)
     * @param string $id   The identifier of the owner
     *
     * @return self
     */
    public function setOwner($type, $id)
    {
        $this->ownerType = $type;
        $this->ownerId = $id;

        return $this;
    }

    /**
     * Return session owner identifier
     *
     * @return string
     */
    public function getOwnerId()
    {
        return $this->ownerId;
    }

    /**
     * Return session owner type
     *
     * @return string
     */
    public function getOwnerType()
    {
        return $this->ownerType;
    }

    /**
     * Save the session
     *
     * @return void
     */
    public function save()
    {
        // Save the session and get an identifier
        $id = $this->server->getSessionStorage()->create(
            $this->getOwnerType(),
            $this->getOwnerId(),
            $this->getClient()->getId(),
            $this->getClient()->getRedirectUri()
        );

        $this->setId($id);

        // Associate the scope with the session
        foreach ($this->getScopes() as $scope) {
            $this->server->getSessionStorage()->associateScope($this, $scope);
        }
    }
}


<?php
/**
 * PleasingMinifyFilter.php
 */

namespace XQ\Pleasing\Filter;

use Assetic\Asset\AssetInterface;
use Assetic\Filter\FilterInterface;
use JShrink\Minifier;

/**
 * Assetic filter to minify JS and CSS files.  CSS files are minified internally.  For JS files, JShrink is used.
 *
 * Class PleasingMinifyFilter
 *
 * @author  Aaron M Jones <am@jonesiscoding.com>
 * @version Pleasing Filters v1.0.18 (https://github.com/jonesiscoding/pleasing-filters)
 * @license MIT (https://github.com/jonesiscoding/pleasing-filters/blob/master/LICENSE)
 *
 * @package XQ\Pleasing\Assetic\Filter
 */
class PleasingMinifyFilter implements FilterInterface
{

  private $comments = null;

  public function filterLoad(AssetInterface $asset)
  {
  }

  public function filterDump(AssetInterface $asset)
  {
    $assetPath = $asset->getSourcePath();
    $ext = ($assetPath) ? pathinfo($assetPath, PATHINFO_EXTENSION) : false;

    $content = $asset->getContent();

    switch ($ext)
    {
      case "css":
      case "less":
      case "scss":
      case "sass":
        $output = $this->minifyCSS($content);
        break;
      case "js":
        $output = $this->minifyJS($content);
        break;
      default:
        // Extension not recognized, or could not be read.  Leave content alone
        $output = $content;
        break;
    }

    $asset->setContent($output);
  }

  /**
   * Minify JS using JShrink::Minifier.
   *
   * @param   string         $input  The JS code to minify.
   *
   * @return  bool|string            The minified JS code, or false if an error occurs.
   * @throws  \Exception             If the JS code cannot be minified, an Exception is thrown
   */
  private function minifyJS($input)
  {
    $input = $this->removeComments( $input );
    return Minifier::minify($input);
  }

  /**
   * Removes comments from a multi line string while preserving any comments that mention licenses, authors, copyrights
   * or the source URL of the code.  This ensures that minification does not break most open source licenses which
   * require attribution.
   *
   * @param  string  $input
   * @param  bool   $proxy
   *
   * @return string
   */
  private function removeComments( $input, $proxy = false )
  {
    if ( preg_match_all("/\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\//", $input, $comments) )
    {
      foreach ( $comments[ 0 ] as $comment )
      {
        $lines = explode(PHP_EOL, $comment);
        $newComment = implode(PHP_EOL,preg_grep("/copyright|license|author|preserve|credit|http|\/\*\!/i",$lines));

        if($newComment)
        {
          // Add proper comment encapsulation
          if ( count( $lines ) > 1 )
          {
            $prefix = (substr($newComment,0,3) == '/*!') ? '' : '/*!' . PHP_EOL;
            $newComment = $prefix . $newComment . PHP_EOL . " */";
          }
          else
          {
            $newComment = str_replace( array("/* ","/** "), "/*! ", $newComment );
          }

          if($proxy) { $this->comments[] = $newComment; }

          $input = str_replace( $comment, $newComment, $input );

        }
        else
        {
          $input = str_replace( $comment, "", $input );
        }
      }

    }

    return $input;
  }

  private function stashComments( $input )
  {
    $this->comments = array();
    $input = $this->removeComments( $input, true );
    foreach ( $this->comments as $key => $value )
    {
      $input = str_replace( $value, "||" . $key . "||", $input );
    }

    return $input;

  }

  private function retrieveComments( $input )
  {
    if ( !empty( $this->comments) && is_array( $this->comments ) )
    {
      foreach ( $this->comments as $key => $value )
      {
        $input = str_replace( "||" . $key . "||", $value . PHP_EOL, $input );
      }
    }

    $input = str_replace( "}/*", "}" . PHP_EOL . "/*", $input );

    return $input;
  }

  /**
   * Minify CSS by removing unneeded code.
   *
   * Regex references from:
   *    http://stackoverflow.com/questions/15195750/minify-compress-css-with-regex
   *    http://stackoverflow.com/questions/2167793/how-to-convert-all-color-code-xxyyzz-to-shorter-3-character-version-xyz-of-who
   *
   * @param  string $input  The string of CSS code to minify
   *
   * @return string         The minified CSS code.
   */
  private function minifyCSS($input)
  {
    $keepComments = null;
    $output = $this->stashComments( $input );

    // Remove Comments, preserving comments marked as important
    $output = preg_replace('!/\*[^*\!]*\*+([^/][^*]*\*+)*/!', '', $output);

    $output = $this->minifySpaceCSS($output);

    $output = $this->shortenHex($output);

    // Replace common units after 0's - they aren't needed
    $output = preg_replace('/((?<!\\\\)\:|\s)\-?0(?:em|cm|mm|in|px|pt|%)/iS', '${1}0', $output);

    // Remove Leading Zeros in Floats
    $output = preg_replace("/0\.([0-9]+)/", '.$1', $output);

    // Extra whitespace
    $output = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $output);

    // Add line breaks around remaining comments
    $output = $this->retrieveComments( $output );

    return $output;
  }

  /**
   * Shorthand hex color codes, for example #ffffff = #fff, or #112233 = #123
   *
   * Intended for use with CSS only.
   *
   * @param  string $input The CSS string in which to shorten hex codes.
   * @return string        The modified CSS code.
   */
  private function shortenHex($input)
  {
    $output = preg_replace('/(?<![\'"])#([a-z0-9])\\1([a-z0-9])\\2([a-z0-9])\\3(?![\'"])/i', '#$1$2$3', $input);
    return $output;
  }

  /**
   * Remove space from CSS files, including whitespaces around !important, parentheses, brackets, colons, and semicolons
   * (that are followed by a closing bracket).
   *
   * @param  string  $input  The CSS from which to remove spacing.
   *
   * @return string          The modified CSS.
   */
  private function minifySpaceCSS($input)
  {
    // Whitespace around !important;
    $output = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $input);
    // Whitespace around parenthesis and brackets.
    $output = preg_replace('/\s+([\]\)])/', '$1', $output);
    // Whitespace around :, except in selectors
    $output = preg_replace('/([\[(:])\s+/', '$1', $output);
    $output = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $output);
    // Whitespace & semicolon followed by closing bracket
    $output = preg_replace('/;}/', '}', $output);

    return $output;
  }

}


<?php

namespace Amcms\View;

use Amcms\Contracts\View as ViewContract;
use Slim\Views\Twig as SlimTwig;
use Slim\Views\TwigExtension as SlimTwigExtension;

class TwigView extends SlimTwig implements ViewContract
{
    /**
     * Adds global variable to view
     * @param string $name
     * @param string $value
     * @param array  $options
     */
    public function setGlobal($name, $value, $options = []) {
        if (isset($options['namespace'])) {
            $this->getEnvironment()->addGlobal($options['namespace'], [$name => $value]);
        } else {
            $this->getEnvironment()->addGlobal($name, $value);
        }
    }
}


<?php

namespace Simphotonics\Utils;

/**
 * @author D Reschner <d.reschner@simphotonics.com>
 * @copyright 2015 Simphotonics
 * Description: Utility functions for string manipulation.
 */

class StringUtils
{

    const OMIT_EMPTY_LINES = 0;

    const KEEP_EMPTY_LINES = 1;

    /**
     * Converts a boolean to a string.
     * @param  bool   $bool
     * @return string
     */
    public static function bool2str($bool = true)
    {
        if ($bool === false) {
            return 'FALSE';
        } else {
            return 'TRUE';
        }
    }

    /**
     * Encloses and input string with double quotes.
     * @param  string $val
     * @param  string $q
     * @return string
     */
    public static function quote($val = "", $q = "\"")
    {
        if (is_string($val)) {
            return $q . $val . $q;
        } elseif (is_numeric($val)) {
            return $val;
        } elseif (is_array($val)) {
            return "StringUtils::quote returned 'array'! ";
        } else {
            return $q . $val . $q;
        }
    }

    /**
     * Generic explode function.
     * @param  string $input
     * @param  array $delims Array containing delimiter characters.
     * @return array
     */
    public static function explodeGeneric($input = '', array $delims = [' '])
    {
        foreach ($delims as $delim) {
            $input = str_replace($delim, ' ', $input);
        }
        $input = preg_replace('/\s\s+/', ' ', $input);
        $input = trim($input);
        $out = explode(' ', $input);
        return $out;
    }

    /**
     * Explodes string into lines of text using
     * the characters: Windows \r\n, Unix \n, Mac \r.
     * @param  string  $input
     * @param  boolean $flag  OMIT_EMPTY_LINES|KEEP_EMPTY_LINES
     * @return array
     */
    public static function explodeTextlines(
        $input,
        $flag = SELF::OMIT_EMPTY_LINES
    ) {

        $out = explode(PHP_EOL, $input);
        if ($flag) {
            return $out;
        }
        // Reject empty words
        foreach ($out as $pos => $word) {
            if (empty($word)) {
                unset($out[$pos]);
            }
        }
        return $out;
    }

   /**
    * Converts preformatted text to pure html encoded text.
    * (Linebreaks =>
, Multiple spaces => n X  )
    * @param  string  $input
    * @param  boolean $decontaminate
    * @return string
    */
    public static function pre2html($input = '', $decontaminate = true)
    {
        // O) Decontaminate
        if ($decontaminate) {
            $input = htmlentities($input);
        }
        // I) Replace line breaks.
        $input = str_replace(PHP_EOL, '
', $input);
        // II) Replace space characters.
        $input = str_replace('  ', '  ', $input);
        // III) Replace tab characters.
        $input = str_replace("\t", '  ', $input);
        return $input;
    }
}