<?php

/**
 * Server object
 *
 * @package    RpkUtils\Sysinfo
 * @author     Repkit <repkit@gmail.com>
 * @copyright  2015 Repkit
 * @license    MIT <http://opensource.org/licenses/MIT>
 * @since      2015-11-12
 */

 namespace RpkUtils\Sysinfo;

 class Server
 {

    /**
     * Server name
     * @return string
     */
    public static function name()
    {
        if(!empty($_SERVER['SERVER_NAME'])){
            $name = $_SERVER['SERVER_NAME'];
        }else{
            $name = @gethostname();
        }

        return $name;
    }

    /**
     * Server ip
     * @return string
     */
    public static function ip()
    {
        if(!empty($_SERVER['SERVER_ADDR'])){
            $ip = $_SERVER['SERVER_ADDR'];
        }else{
            $ip = @gethostbyname(static::name());
        }

        return $ip;
    }

    /**
     * Server os
     * @param bool $Detalied
     * @return string
     */
    public static function os($Detalied = false)
    {
        //Kernel version: if('/'==DIRECTORY_SEPARATOR){echo $os[2];}else{echo $os[1];}
        if($Detalied){
            $os = @php_uname();
        }else{
            $os = PHP_OS;
        }

        return $os;
    }

    /**
     * Server kernel
     * @return string
     */
    public static function kernel()
    {
        if($os = static::os(true)){
            $os = explode(' ', $os);
            if('/' == DIRECTORY_SEPARATOR){
                $kernel = $os[2];
            }else{
                $kernel = $os[1];
            }
        }else{
            $kernel = '';
        }

        return $kernel;
    }

    /**
     * Server hostname
     * @return string
     */
    public static function hostname()
    {
        if($os = static::os(true)){
            $os = explode(' ', $os);
             if('/' == DIRECTORY_SEPARATOR ){
                $hostname = $os[1];
            }else{
                $hostname = $os[2];
            }
        }else{
            $hostname = '';
        }

        return $hostname;
    }

    /**
     * Server software
     * @return string
     */
    public static function software()
    {
        if(!empty($_SERVER['SERVER_SOFTWARE'])){
            $software = $_SERVER['SERVER_SOFTWARE'];
        }else{
            $software = '';
        }

        return $software;
    }

    /**
     * Server language
     * @return string
     */
    public static function language()
    {
        if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
            $language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
        }else{
            $language = '';
        }

        return $language;
    }

    /**
     * Server port
     * @return string
     */
    public static function port()
    {
        if(!empty($_SERVER['SERVER_PORT'])){
            $port = $_SERVER['SERVER_PORT'];
        }else{
            $port = '';
        }

        return $port;
    }

    /**
     * Server document root
     * @return string
     */
    public static function docroot()
    {
        if(!empty($_SERVER['DOCUMENT_ROOT'])){
            $docroot = str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']);
        }else{
            $docroot = str_replace('\\','/',dirname(__FILE__));
        }

        return $docroot;
    }

    /**
     * Server admin email
     * @return string
     */
    public static function adminmail()
    {
        if(!empty($_SERVER['SERVER_ADMIN'])){
            $adminmail = $_SERVER['SERVER_ADMIN'];
        }else{
            $adminmail = '';
        }

        return $adminmail;
    }

    /**
     * Server uptime
     * @return float seconds
     */
    public static function uptime()
    {
        $uptime = -1;
        if(false !== ($data = @file("/proc/uptime"))){
            $data   = explode(' ',reset($data));
            $uptime = reset($data);
        }

        return floatval($uptime);
    }

    /**
     * Server cpu
     * @return \StdClass
     */
    public static function cpu()
    {
        $cpu = new \StdClass();

        if(false !== ($data = @file('/proc/cpuinfo'))){

            $data = implode("", $data);

            // processing aka pre matching data
            @preg_match_all('/model\s+name\s{0,}\:+\s{0,}([\w\s\)\(\@.-]+)([\r\n]+)/s', $data, $model);
            @preg_match_all('/cpu\s+MHz\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/', $data, $mhz);
            @preg_match_all('/cache\s+size\s{0,}\:+\s{0,}([\d\.]+\s{0,}[A-Z]+[\r\n]+)/', $data, $cache);
            @preg_match_all('/bogomips\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/', $data, $bogomips);

        }

        if (false !== is_array($model[1])){

            $cpu->num = sizeof($model[1]);
            $x1 = '';
    		if($cpu->num != 1){
    		    $x1 = ' ×'.$cpu->num;
    		}

    		$cpu->frequency = $mhz[1][0];
    		$cpu->cache2    = $cache[1][0];
    		$cpu->bogomips  = $bogomips[1][0];
    		$cpu->model     = $model[1][0];
    		$cpu->summary   = 'Model: '.$model[1][0].' | Frequency: '.$mhz[1][0].' | Secondary cache: '.$cache[1][0].' | Bogomips: '.$bogomips[1][0].' '.$x1;

    	}

    	return $cpu;
    }

    /**
     * Server cpu cores information
     * @return array
     */
    public static function cpuCoreInfo()
    {
        $cores = array();
        if(false !== ($data = @file('/proc/stat'))){
            foreach($data as $line ) {
                if( preg_match('/^cpu[0-9]/', $line) ){
                    $info = explode(' ', $line);
                    $cores[]=array(
                        'user'      => $info[1],
                        'nice'      => $info[2],
                        'sys'       => $info[3],
                        'idle'      => $info[4],
                        'iowait'    => $info[5],
                        'irq'       => $info[6],
                        'softirq'   => $info[7]
                    );
                }
            }
        }

        return $cores;

    }

    /**
     * Server cpu percentages
     * @param cpuCoreInfo()
     * @param cpuCoreInfo()
     * @return array
     */
    public static function cpuPercentages($cpuCoreInfo1, $cpuCoreInfo2)
    {

        $cpus = array();
        foreach($cpuCoreInfo1 as $idx => $core){

            $dif = array();
            $cpu = array();

            $dif['user']    = $cpuCoreInfo2[$idx]['user'] - $cpuCoreInfo1[$idx]['user'];
            $dif['nice']    = $cpuCoreInfo2[$idx]['nice'] - $cpuCoreInfo1[$idx]['nice'];
            $dif['sys']     = $cpuCoreInfo2[$idx]['sys'] - $cpuCoreInfo1[$idx]['sys'];
            $dif['idle']    = $cpuCoreInfo2[$idx]['idle'] - $cpuCoreInfo1[$idx]['idle'];
            $dif['iowait']  = $cpuCoreInfo2[$idx]['iowait'] - $cpuCoreInfo1[$idx]['iowait'];
            $dif['irq']     = $cpuCoreInfo2[$idx]['irq'] - $cpuCoreInfo1[$idx]['irq'];
            $dif['softirq'] = $cpuCoreInfo2[$idx]['softirq'] - $cpuCoreInfo1[$idx]['softirq'];

            $total = array_sum($dif);

            foreach($dif as $x=>$y){
                $cpu[$x] = round($y / $total * 100, 2);
            }

            $cpus['cpu' . $idx] = $cpu;

        }

        return $cpus;

    }

    /**
     * Server hdd information
     * @return \StdClass
     *          ->total
     *          ->free
     */
    public static function hdd()
    {
        $hdd        = new \StdClass();
        $hdd->total = @disk_total_space(".");
        $hdd->free  = @disk_free_space(".");

        return $hdd;

    }

    /**
     * Server memory information
     * @return \StdClass
     *              ->total
     *              ->used
     *              ->free
     *              ->cached
     *              ->buffers
     *              ->real->used
     *              ->real->free
     *              ->swapo->used
     *              ->swapo->free
     * @important: all data is in bytes
     */
    public static function memory()
    {
        $memory         = new \StdClass();
        $memory->real   = new \StdClass();
        $memory->swap   = new \StdClass();

        if(false !== ($data = @file('/proc/meminfo'))){

            $data = implode("", $data);

            //processing and stuff aka preg matching
            preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $data, $meminfo);
    	    preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $data, $buffers);

    	    $memory->total          = $meminfo[1][0]*1024;
    	    $memory->free           = $meminfo[2][0]*1024;
    	    $memory->used           = $memory->total - $memory->free;
	        $memory->cached         = $meminfo[3][0]*1024;
    	    $memory->buffers        = $buffers[1][0]*1024;

    	    $memory->real->used     = $memory->total - $memory->free - $memory->cached - $memory->buffers;
    	    $memory->real->free     = $memory->total - $memory->real->used;

    	    $memory->swap->free     = $meminfo[5][0]*1024;
    	    $memory->swap->used     = $meminfo[4][0]*1024 - $memory->swap->free;

        }

        return $memory;

    }

    /**
     * Server average load info
     * @return \StdClass
     *              ->min1
     *              ->min5
     *              ->min15
     *              ->running
     *              ->exists
     *              ->recentPID
     */
    public static function avgload()
    {
        $avgload = new \StdClass();
        if(false !== ($data = @file('/proc/loadavg'))){
            $data               = explode(" ", implode("", $data));
            $data               = array_chunk($data, 4);
            $avgload->min1      = $data[0][0];
            $avgload->min5      = $data[0][1];
            $avgload->min15     = $data[0][2];
            $fourth             = explode('/',$data[0][3]);
            $avgload->running   = $fourth[0];
            $avgload->exists    = $fourth[1];
            $avgload->recentPID = $data[1][0];
        }

        return $avgload;

    }

    public static function network()
    {
        $network = array();
        if (false !== ($data = @file("/proc/net/dev"))){
            //first two fields are headers :)
            for ($i = 2; $i < count($data); $i++ ){
                //processing aka preg matching
                preg_match_all("/([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/", $data[$i], $netinfo);
                $network[$i]['name']    = $netinfo[1][0];
                $network[$i]['in']      = $netinfo[2][0];
                $network[$i]['out']     = $netinfo[10][0];
            }
        }

        return $network;
    }

    public static function devices()
    {
        $devices = array();
        if(false !== ($data = @file_get_contents('/proc/diskstats'))){
            // $data = file_get_contents('/proc/diskstats');
            $matches = array();
            preg_match_all('/^\s*\d+\s+\d+\s+(.*?)(\d+) (\d+) \d+ \d+ (\d+) (\d+) \d+ \d+ (\d+) \d+ \d+ \d+\s*$/m', $data, $matches, PREG_SET_ORDER);
            foreach ($matches as $set){
                $devices[$set[1]][$set[2]]['reads'] = $set[3];
                $devices[$set[1]][$set[2]]['readTime'] = $set[4];
                $devices[$set[1]][$set[2]]['writes'] = $set[5];
                $devices[$set[1]][$set[2]]['writeTime'] = $set[6];
            }
        }

        return $devices;
    }

 }


<?php

namespace Peyote;

/**
 * Building a DELETE query.
 *
 * See Select for the full rant, but the tl;dr is that php 4 is messing up my
 * classes, so I have to actually declare where() and limit() in this class
 * instead of just using the cool passthru functionality.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Delete extends \Peyote\Query
{
	/**
	 * @var \Peyote\Where  The where object
	 */
	protected $where = null;

	/**
	 * @var \Peyote\Order  The order object
	 */
	protected $order_by = null;

	/**
	 * @var \Peyote\Limit  The limit object
	 */
	protected $limit = null;

	/**
	 * @var array  A list of mixins that the query can passthru
	 */
	protected $mixins = array('where', 'order_by', 'limit');

	/**
	 * Optionally sets the table name and initializes the internal class
	 * properties.
	 *
	 * @param string $table  The name of the table
	 */
	public function __construct($table = null)
	{
		$this->where = new \Peyote\Where;
		$this->order_by = new \Peyote\Order;
		$this->limit = new \Peyote\Limit;

		parent::__construct($table);
	}

	/**
	 * Adds a WHERE clause.
	 *
	 * @param  string $column  The column name
	 * @param  string $op      The comparison operator
	 * @param  mixed  $value   The value to bind
	 * @return \Peyote\Delete
	 */
	public function where($column, $op, $value)
	{
		$this->where->andWhere($column, $op, $value);
		return $this;
	}

	/**
	 * Sets the limit.
	 *
	 * @param  int $num  The number to limit the queries to
	 * @return \Peyote\Select
	 */
	public function limit($num, $offset = 0)
	{
		$this->limit->setLimit($num, $offset);
		return $this;
	}

	/**
	 * Gets all of the bound parameters for this query.
	 *
	 * @return array
	 */
	public function getParams()
	{
		/**
		 * Instead of writing some crazy magic foo to pull the params
		 * automatically, I'm just overridding this function to get the
		 * correct params.
		 *
		 * Since where is the only clause that would have params, let's just
		 * fetch those
		 */
		return $this->where->getParams();
	}

	/**
	 * Compiles the query into raw SQL
	 *
	 * @return  string
	 */
	public function compile()
	{
		$sql = array("DELETE FROM");
		$sql[] = $this->table;

		$sql = \array_merge($sql, $this->compileMixins());

		return join(' ', $sql);
	}

}


<?php

namespace Orchid\Log\Utilities;

use Illuminate\Filesystem\Filesystem as IlluminateFilesystem;
use Orchid\Log\Contracts\Utilities\Filesystem as FilesystemContract;
use Orchid\Log\Exceptions\FilesystemException;

class Filesystem implements FilesystemContract
{
    /**
     * The filesystem instance.
     *
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $filesystem;

    /**
     * The base storage path.
     *
     * @var string
     */
    protected $storagePath;

    /**
     * The log files prefix pattern.
     *
     * @var string
     */
    protected $prefixPattern;

    /**
     * The log files date pattern.
     *
     * @var string
     */
    protected $datePattern;

    /**
     * The log files extension.
     *
     * @var string
     */
    protected $extension;

    /**
     * Filesystem constructor.
     *
     * @param \Illuminate\Filesystem\Filesystem $files
     * @param string                            $storagePath
     */
    public function __construct(IlluminateFilesystem $files, $storagePath)
    {
        $this->filesystem = $files;
        $this->setPath($storagePath);
        $this->setPattern();
    }

    /**
     * Set the log storage path.
     *
     * @param string $storagePath
     *
     * @return \Orchid\Log\Utilities\Filesystem
     */
    public function setPath($storagePath)
    {
        $this->storagePath = $storagePath;

        return $this;
    }

    /**
     * Set the log pattern.
     *
     * @param string $date
     * @param string $prefix
     * @param string $extension
     *
     * @return \Orchid\Log\Utilities\Filesystem
     */
    public function setPattern(
        $prefix = self::PATTERN_PREFIX,
        $date = self::PATTERN_DATE,
        $extension = self::PATTERN_EXTENSION
    ) {
        $this->setPrefixPattern($prefix);
        $this->setDatePattern($date);
        $this->setExtension($extension);

        return $this;
    }

    /**
     * Set the log prefix pattern.
     *
     * @param string $prefixPattern
     *
     * @return \Orchid\Log\Utilities\Filesystem
     */
    public function setPrefixPattern($prefixPattern)
    {
        $this->prefixPattern = $prefixPattern;

        return $this;
    }

    /**
     * Set the log date pattern.
     *
     * @param string $datePattern
     *
     * @return \Orchid\Log\Utilities\Filesystem
     */
    public function setDatePattern($datePattern)
    {
        $this->datePattern = $datePattern;

        return $this;
    }

    /**
     * Set the log extension.
     *
     * @param string $extension
     *
     * @return \Orchid\Log\Utilities\Filesystem
     */
    public function setExtension($extension)
    {
        $this->extension = $extension;

        return $this;
    }

    /**
     * Get the files instance.
     *
     * @return \Illuminate\Filesystem\Filesystem
     */
    public function getInstance()
    {
        return $this->filesystem;
    }

    /**
     * Get all log files.
     *
     * @return array
     */
    public function all()
    {
        return $this->getFiles('*'.$this->extension);
    }

    /**
     * Get all files.
     *
     * @param string $pattern
     *
     * @return array
     */
    private function getFiles($pattern)
    {
        $files = $this->filesystem->glob(
            $this->storagePath.DIRECTORY_SEPARATOR.$pattern, GLOB_BRACE
        );

        return array_filter(array_map('realpath', $files));
    }

    /**
     * List the log files (Only dates).
     *
     * @param bool $withPaths
     *
     * @return array
     */
    public function dates($withPaths = false)
    {
        $files = array_reverse($this->logs());
        $dates = $this->extractDates($files);

        if ($withPaths) {
            $dates = array_combine($dates, $files); // [date => file]
        }

        return $dates;
    }

    /**
     * Get all valid log files.
     *
     * @return array
     */
    public function logs()
    {
        return $this->getFiles($this->getPattern());
    }

    /**
     * Get the log pattern.
     *
     * @return string
     */
    public function getPattern()
    {
        return $this->prefixPattern.$this->datePattern.$this->extension;
    }

    /**
     * Extract dates from files.
     *
     * @param array $files
     *
     * @return array
     */
    private function extractDates(array $files)
    {
        return array_map(function ($file) {
            return extract_date(basename($file));
        }, $files);
    }

    /**
     * Read the log.
     *
     * @param string $date
     *
     * @throws \Orchid\Log\Exceptions\FilesystemException
     *
     * @return string
     */
    public function read($date)
    {
        try {
            $path = $this->getLogPath($date);

            return $this->filesystem->get($path);
        } catch (\Exception $e) {
            throw new FilesystemException($e->getMessage());
        }
    }

    /**
     * Get the log file path.
     *
     * @param string $date
     *
     * @throws \Orchid\Log\Exceptions\FilesystemException
     *
     * @return string
     */
    private function getLogPath($date)
    {
        $path = $this->storagePath.DIRECTORY_SEPARATOR.$this->prefixPattern.$date.$this->extension;

        if (!$this->filesystem->exists($path)) {
            throw new FilesystemException("The log(s) could not be located at : $path");
        }

        return realpath($path);
    }

    /**
     * Delete the log.
     *
     * @param string $date
     *
     * @throws \Orchid\Log\Exceptions\FilesystemException
     *
     * @return bool
     */
    public function delete($date)
    {
        $path = $this->getLogPath($date);

        // @codeCoverageIgnoreStart
        if (!$this->filesystem->delete($path)) {
            throw new FilesystemException('There was an error deleting the log.');
        }

        // @codeCoverageIgnoreEnd

        return true;
    }

    /**
     * Get the log file path.
     *
     * @param string $date
     *
     * @return string
     */
    public function path($date)
    {
        return $this->getLogPath($date);
    }
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * 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.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Markup;

/**
 * 与えられた Component を加工して HTML コードなどに変換するためのクラスです.
 */
abstract class Builder
{
    /**
     * 指定された Component を加工します. 返り値の型は具象クラスによって異なります.
     * @param  Component $c 加工対象の Component
     * @return mixed        加工した結果
     */
    public final function build(Component $c)
    {
        $context = $this->createContext();
        $context->handle($c);
        return $context->getResult();
    }

    /**
     * build を実行する際に用いる Context を初期化します.
     * @return Context
     */
    protected abstract function createContext();
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * 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.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\DT;
use Peach\Util\Map;
use Peach\Util\ArrayMap;

/**
 * DATETIME 型の時間オブジェクトです.
 * このクラスは年・月・日・時・分のフィールドをサポートします.
 */
class Datetime extends Date
{
    /**
     * 時を表す整数(0～23)です.
     * @var int
     * @ignore
     */
    protected $hour = 0;

    /**
     * 分を表す整数(0～59)です.
     * @var int
     * @ignore
     */
    protected $minute = 0;

    /**
     * 現在時刻の Datetime オブジェクトを返します.
     *
     * @param  Clock $clock 現在時刻を取得するための Clock オブジェクト
     * @return Datetime     現在時刻をあらわす Datetime
     */
    public static function now(Clock $clock = null)
    {
        if ($clock === null) {
            return self::now(DefaultClock::getInstance());
        }

        return $clock->getTimestamp()->toDatetime();
    }

    /**
     * 指定されたテキストを解析して Datetime オブジェクトに変換します.
     * $format が指定されていない場合は {@link W3cDatetimeFormat::getInstance}
     * を使って解析を行います.
     * ("YYYY-MM-DD hh:mm" 形式の文字列を受理します.
     * 日付と時刻のセパレータは, 数字以外の ASCII 1 文字であれば何でも構いません.)
     *
     * @param  string   $text   変換対象の文字列
     * @param  Format   $format 変換に使用するフォーマット
     * @return Datetime         変換結果
     */
    public static function parse($text, Format $format = null)
    {
        if (!isset($format)) {
            $format = W3cDatetimeFormat::getInstance();
        }
        return $format->parseDatetime($text);
    }

    /**
     * 与えられた時刻を表現する Datetime オブジェクトを構築します.
     *
     * @param int $year  年
     * @param int $month 月
     * @param int $date  日
     * @param int $hour  時
     * @param int $min   分
     */
    public function __construct($year, $month, $date, $hour, $min)
    {
        $fields = new ArrayMap();
        $fields->put(self::$YEAR,   intval($year));
        $fields->put(self::$MONTH,  intval($month));
        $fields->put(self::$DATE,   intval($date));
        $fields->put(self::$HOUR,   intval($hour));
        $fields->put(self::$MINUTE, intval($min));
        $this->init($fields);
    }

    /**
     * このオブジェクトの型 {@link Time::TYPE_DATETIME} を返します.
     * @return int Time::TYPE_DATETIME
     */
    public function getType()
    {
        return self::TYPE_DATETIME;
    }

    /**
     * @ignore
     */
    protected function init(Map $fields)
    {
        parent::init($fields);
        $this->hour   = $fields->get(self::$HOUR);
        $this->minute = $fields->get(self::$MINUTE);
    }

    /**
     * 時刻の不整合を調整します.
     * @ignore
     */
    protected function adjust(Map $fields)
    {
        parent::adjust($fields);
        $hourAd = $this->getHourAdjuster();
        $minAd  = $this->getMinuteAdjuster();
        $hour   = $fields->get(self::$HOUR);
        $min    = $fields->get(self::$MINUTE);

        if ($hour < 0) {
            $hourAd->moveDown($fields);
        } else if (23 < $hour) {
            $hourAd->moveUp($fields);
        } else if ($min < 0) {
            $minAd->moveDown($fields);
        } else if (59 < $min) {
            $minAd->moveUp($fields);
        } else {
            return;
        }

        $this->adjust($fields);
    }

    /**
     * (non-PHPdoc)
     *
     * @return Datetime
     * @see AbstractTime::newInstance
     * @ignore
     */
    protected function newInstance(Map $fields)
    {
        $year  = $fields->get(self::$YEAR);
        $month = $fields->get(self::$MONTH);
        $date  = $fields->get(self::$DATE);
        $hour  = $fields->get(self::$HOUR);
        $min   = $fields->get(self::$MINUTE);
        return new self($year, $month, $date, $hour, $min);
    }

    /**
     * この時間と指定された時間を比較します.
     *
     * この型の時間フィールドと引数の型の時間フィールドのうち,
     * 共通しているフィールド同士を比較します.
     *
     * 引数がこのクラスを継承したオブジェクトではない場合,
     * 引数のオブジェクトに対して get("year"), get("month"), get("date"), get("hour"), get("minute")
     * を呼び出した結果を比較対象のフィールドとします.
     *
     * @param  Time 比較対象の時間
     * @return int  この時間のほうが過去の場合は負の値, 未来の場合は正の値, それ以外は 0
     * @ignore
     */
    protected function compareFields(Time $time)
    {
        $c = parent::compareFields($time);
        if ($c !== 0) {
            return $c;
        }

        $className = __CLASS__;
        if ($time instanceof $className) {
            if ($this->hour   !== $time->hour) {
                return $this->hour   - $time->hour;
            }
            if ($this->minute !== $time->minute) {
                return $this->minute - $time->minute;
            }
            return 0;
        }
        else {
            $h = $time->get("hour");
            $m = $time->get("minute");
            if ($this->hour   !== $h) {
                return (isset($h) ? $this->hour   - $h : 0);
            }
            if ($this->minute !== $m) {
                return (isset($m) ? $this->minute - $m : 0);
            }
            return 0;
        }
    }

    /**
     * @ignore
     */
    protected function handleFormat(Format $format)
    {
        return $format->formatDatetime($this);
    }

    /**
     * このオブジェクトの時刻部分の文字列を "hh:mm" 形式で返します.
     *
     * @return string "hh:mm" 形式の文字列
     */
    public function formatTime()
    {
        $hour = str_pad($this->hour,   2, '0', STR_PAD_LEFT);
        $min  = str_pad($this->minute, 2, '0', STR_PAD_LEFT);
        return $hour . ":" . $min;
    }

    /**
     * このオブジェクトの文字列表現です.
     * "YYYY-MM-DD hh:mm" 形式の文字列を返します.
     *
     * @return string W3CDTF に則った文字列表現
     */
    public function __toString()
    {
        $date = parent::__toString();
        return $date . ' ' . $this->formatTime();
    }

    /**
     * このオブジェクトを Datetime 型にキャストします.
     * 返り値はこのオブジェクトのクローンです.
     *
     * @return Datetime このオブジェクトのクローン
     */
    public function toDatetime()
    {
        return new self($this->year, $this->month, $this->date, $this->hour, $this->minute);
    }

    /**
     * このオブジェクトを Timestamp 型にキャストします.
     * この時刻の 0 秒を表す Timestamp オブジェクトを返します.
     *
     * @return Timestamp このオブジェクトの timestamp 表現
     */
    public function toTimestamp()
    {
        return new Timestamp($this->year, $this->month, $this->date, $this->hour, $this->minute, 0);
    }

    /**
     * 「時」フィールドを調整する Adjuster です
     * @return FieldAdjuster
     * @codeCoverageIgnore
     */
    private function getHourAdjuster()
    {
        static $adjuster = null;
        if ($adjuster === null) {
            $adjuster = new FieldAdjuster(self::$HOUR, self::$DATE, 0, 23);
        }
        return $adjuster;
    }

    /**
     * 「分」フィールドを調整する Adjuster です
     * @return FieldAdjuster
     * @codeCoverageIgnore
     */
    private function getMinuteAdjuster()
    {
        static $adjuster = null;
        if ($adjuster === null) {
            $adjuster = new FieldAdjuster(self::$MINUTE, self::$HOUR, 0, 59);
        }
        return $adjuster;
    }
}


<?php

namespace GetOlympus\Field;

use GetOlympus\Zeus\Field\Controller\Field;
use GetOlympus\Zeus\Translate\Controller\Translate;

/**
 * Builds File field.
 *
 * @package Field
 * @subpackage File
 * @author Achraf Chouk <achrafchouk@gmail.com>
 * @since 0.0.1
 *
 * @see https://olympus.readme.io/v1.0/docs/file-field
 *
 */

class File extends Field
{
    /**
     * Prepare variables.
     */
    protected function setVars()
    {
        $this->getModel()->setFaIcon('fa-file-code-o');
        $this->getModel()->setHasId(false);
        $this->getModel()->setTemplate('file.html.twig');
    }

    /**
     * Prepare HTML component.
     *
     * @param array $content
     * @param array $details
     *
     * @since 0.0.1
     */
    protected function getVars($content, $details = [])
    {
        // Build defaults
        $defaults = [
            'title' => Translate::t('file.title', [], 'filefield'),
            'file' => false,
        ];

        // Build defaults data
        $vars = array_merge($defaults, $content);

        // Update vars
        $this->getModel()->setVars($vars);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: sicmouse
 * Date: 2018/8/31
 * Time: 下午5:18
 */

namespace DdvPhp\DdvRestfulApi\Lib;

use Closure;
use DdvPhp\DdvUrl;

class RequestContentDataInfo
{
    /**
     * @var array
     */
    protected $info = array();
    /**
     * @var array
     */
    protected $data = array();
    /**
     * 毁掉钩子
     * @var array
     */
    protected $hookCompleteds = array();

    public function __set($name, $value)
    {
        if ($name === 'data') {
            $this->data = $value;
        } elseif ($name === 'info') {
            $this->info = $value;
        } else {
            if (!isset($this->info)) {
                $this->info = array();
            }
            $this->info[$name] = $value;
        }
    }

    public function &__get($name)
    {
        $value = null;
        if ($name === 'data') {
            if (empty($this->data)) {
                $this->data = array();
            }
            $value = &$this->data;
        } elseif ($name === 'info') {
            if (empty($this->info)) {
                $this->info = array();
            }
            $value = &$this->info;
        } elseif ($name) {
            if (!isset($this->info[$name])) {
                $this->info[$name] = '';
            }
            $value = &$this->info[$name];
        }
        return $value;
    }

    public function __isset($name)
    {
        if ($name === 'data') {
            return true;
        }
        return isset($this->info[$name]);
    }

    public function onCompleted(Closure $fn)
    {
        if (!is_array($this->hookCompleteds)) {
            $this->hookCompleteds = [];
        }
        $this->hookCompleteds[] = $fn;
    }

    public function emitCompleted()
    {
        if (is_array($this->hookCompleteds)) {
            $fns = $this->hookCompleteds;
            foreach ($fns as $fn) {
                if ($fn instanceof Closure) {
                    $fn();
                }
            }
            unset($fns);
        }
        return $this;
    }

    /**
     * 重置
     */
    public function reset($name = null)
    {
        $this->info = array();
        $this->hookCompleteds = array();
        $this->resetValue($name);
        return $this;
    }
    protected function resetValue($key){
        if (empty($key)){
            return;
        }
        $key = preg_replace('/\+/', '%20', (string)$key);
        $key = DdvUrl::urlDecode(trim($key));
        $i = strpos($key, "\x00");
        if ($i!==false){
            $key = substr($key, 0, $i);
        }
        if (empty($key) || $key[0] === '['){
            return;
        }
        $keys = array();
        $postLeftBracketPos = 0;
        for ($i = 0; $i < strlen($key); $i++){
            if ($key[$i] === '[' && !$postLeftBracketPos){
                $postLeftBracketPos = $i + 1;
            }elseif($key[$i] === ']'){
                if ($postLeftBracketPos){
                    if (empty($keys)){
                        $keys[] = substr($key, 0, $postLeftBracketPos - 1);
                    }
                    $keys[] = substr($key, $postLeftBracketPos, $i - $postLeftBracketPos);
                    $postLeftBracketPos = 0;
                    if (isset($key[$i+1])&&$key[$i+1]!=='['){
                        break;
                    }
                }
            }
        }
        unset($postLeftBracketPos);
        if (empty($keys)){
            $keys[] = $key;
        }
        for ($i = 0; $i < strlen($keys[0]); $i++){
            $chr = $keys[0][$i];
            if ($chr === ' ' || $chr === '.' || $chr === '[') {
                $keys[0] = substr($keys[0], 0, $i) + '_' + substr($keys[0], $i + 1);
            }
            if ($chr === '[') {
                break;
            }
        }
        $data = &$this->data;
        for ($i = 0, $keysLen = count($keys); $i < $keysLen; $i++){
            $key = preg_replace('/[\'"]$/', '', preg_replace('/^[\'"]/', '', $keys[$i]));
            $lastData = &$data;
            if (($key !== '' && $key !== ' ') || $i === 0){
                if (!isset($data[$key])){
                    $data[$key] = array();
                }
                $data = &$data[$key];
            }else{
                $ct = -1;
                foreach ($data as $p => $pv){
                    if (is_numeric($p)){
                        $ct = (int)$p + 1;
                    }
                }
                $key = $ct + 1;
                unset($ct);
            }
        }
        $lastData[$key] = &$this->info['value'];
        unset($i, $key, $keys, $data, $lastData, $keysLen);
    }

    public function getData()
    {
        return $this->data;
    }

    public function destroy()
    {
        if (is_array($this->info)) {
            if (isset($this->info['value'])) {
                unset($this->info['value']);
            }
        }
        $this->data = null;
        $this->info = null;
        $this->hookCompleteds = null;
        return $this;
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\filters;

use Yii;
use yii\base\Action;
use yii\base\ActionFilter;
use yii\di\Instance;
use yii\web\User;
use yii\web\ForbiddenHttpException;

/**
 * AccessControl provides simple access control based on a set of rules.
 *
 * AccessControl is an action filter. It will check its [[rules]] to find
 * the first rule that matches the current context variables (such as user IP address, user role).
 * The matching rule will dictate whether to allow or deny the access to the requested controller
 * action. If no rule matches, the access will be denied.
 *
 * To use AccessControl, declare it in the `behaviors()` method of your controller class.
 * For example, the following declarations will allow authenticated users to access the "create"
 * and "update" actions and deny all other users from accessing these two actions.
 *
 * ```php
 * public function behaviors()
 * {
 *     return [
 *         'access' => [
 *             'class' => \yii\filters\AccessControl::className(),
 *             'only' => ['create', 'update'],
 *             'rules' => [
 *                 // deny all POST requests
 *                 [
 *                     'allow' => false,
 *                     'verbs' => ['POST']
 *                 ],
 *                 // allow authenticated users
 *                 [
 *                     'allow' => true,
 *                     'roles' => ['@'],
 *                 ],
 *                 // everything else is denied
 *             ],
 *         ],
 *     ];
 * }
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AccessControl extends ActionFilter
{
    /**
     * @var User|array|string the user object representing the authentication status or the ID of the user application component.
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
     */
    public $user = 'user';
    /**
     * @var callable a callback that will be called if the access should be denied
     * to the current user. If not set, [[denyAccess()]] will be called.
     *
     * The signature of the callback should be as follows:
     *
     * ```php
     * function ($rule, $action)
     * ```
     *
     * where `$rule` is the rule that denies the user, and `$action` is the current [[Action|action]] object.
     * `$rule` can be `null` if access is denied because none of the rules matched.
     */
    public $denyCallback;
    /**
     * @var array the default configuration of access rules. Individual rule configurations
     * specified via [[rules]] will take precedence when the same property of the rule is configured.
     */
    public $ruleConfig = ['class' => 'yii\filters\AccessRule'];
    /**
     * @var array a list of access rule objects or configuration arrays for creating the rule objects.
     * If a rule is specified via a configuration array, it will be merged with [[ruleConfig]] first
     * before it is used for creating the rule object.
     * @see ruleConfig
     */
    public $rules = [];

    /**
     * Initializes the [[rules]] array by instantiating rule objects from configurations.
     */
    public function init()
    {
        parent::init();
        $this->user = Instance::ensure($this->user, User::className());
        foreach ($this->rules as $i => $rule) {
            if (is_array($rule)) {
                $this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
            }
        }
    }

    /**
     * This method is invoked right before an action is to be executed (after all possible filters.)
     * You may override this method to do last-minute preparation for the action.
     * @param Action $action the action to be executed.
     * @return boolean whether the action should continue to be executed.
     */
    public function beforeAction($action)
    {
        $user = $this->user;
        $request = Yii::$app->getRequest();
        /* @var $rule AccessRule */
        foreach ($this->rules as $rule) {
            if ($allow = $rule->allows($action, $user, $request)) {
                return true;
            } elseif ($allow === false) {
                if (isset($rule->denyCallback)) {
                    call_user_func($rule->denyCallback, $rule, $action);
                } elseif ($this->denyCallback !== null) {
                    call_user_func($this->denyCallback, $rule, $action);
                } else {
                    $this->denyAccess($user);
                }
                return false;
            }
        }
        if ($this->denyCallback !== null) {
            call_user_func($this->denyCallback, null, $action);
        } else {
            $this->denyAccess($user);
        }
        return false;
    }

    /**
     * Denies the access of the user.
     * The default implementation will redirect the user to the login page if he is a guest;
     * if the user is already logged, a 403 HTTP exception will be thrown.
     * @param User $user the current user
     * @throws ForbiddenHttpException if the user is already logged in.
     */
    protected function denyAccess($user)
    {
        if ($user->getIsGuest()) {
            $user->loginRequired();
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
    }
}


<?php

/*
 * The MIT License
 *
 * Copyright 2018 Daniel Popiniuc
 *
 * 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 danielgp\io_operations;

trait InputOutputFiles
{

    use InputOutputFilePermissions;

    public function checkFileExistance($strFilePath, $strFileName)
    {
        $fName = $this->gluePathWithFileName($strFilePath, $strFileName);
        if (!file_exists($fName)) {
            throw new \RuntimeException(sprintf('File %s does not exists!', $fName));
        }
        return $fName;
    }

    /**
     * returns an array with non-standard holidays from a JSON file
     *
     * @param string $strFileName
     * @return mixed
     */
    public function getArrayFromJsonFile($strFilePath, $strFileName)
    {
        $jSonContent   = $this->getFileJsonContent($strFilePath, $strFileName);
        $arrayToReturn = json_decode($jSonContent, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            $fName = $this->gluePathWithFileName($strFilePath, $strFileName);
            throw new \RuntimeException(sprintf('Unable to interpret JSON from %s file...', $fName));
        }
        return $arrayToReturn;
    }

    /**
     * Returns the details about Communicator (current) file
     * w/o any kind of verification of file existence
     *
     * @param string $fileGiven
     * @return array
     */
    public function getFileDetailsRaw($fileGiven)
    {
        $info              = new \SplFileInfo($fileGiven);
        $aFileBasicDetails = [
            'File Extension'         => $info->getExtension(),
            'File Group'             => $info->getGroup(),
            'File Inode'             => $info->getInode(),
            'File Link Target'       => ($info->isLink() ? $info->getLinkTarget() : '-'),
            'File Name'              => $info->getBasename('.' . $info->getExtension()),
            'File Name w. Extension' => $info->getFilename(),
            'File Owner'             => $info->getOwner(),
            'File Path'              => $info->getPath(),
            'Name'                   => $info->getRealPath(),
            'Type'                   => $info->getType(),
        ];
        $aDetails          = array_merge($aFileBasicDetails, $this->getFileDetailsRawStatistic($info, $fileGiven));
        ksort($aDetails);
        return $aDetails;
    }

    private function getFileDetailsRawStatistic(\SplFileInfo $info, $fileGiven)
    {
        return [
            'File is Dir'        => $info->isDir(),
            'File is Executable' => $info->isExecutable(),
            'File is File'       => $info->isFile(),
            'File is Link'       => $info->isLink(),
            'File is Readable'   => $info->isReadable(),
            'File is Writable'   => $info->isWritable(),
            'File Permissions'   => $this->explainPerms($info->getPerms()),
            'Size'               => $info->getSize(),
            'Sha1'               => sha1_file($fileGiven),
            'Timestamp Accessed' => $this->getFileTimes($info->getATime()),
            'Timestamp Changed'  => $this->getFileTimes($info->getCTime()),
            'Timestamp Modified' => $this->getFileTimes($info->getMTime()),
        ];
    }

    public function getFileEntireContent($strInputFile)
    {
        $contentInputFile = file($strInputFile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
        if ($contentInputFile === false) {
            throw new \RuntimeException(sprintf('Unable to read file %s...', $strInputFile));
        }
        return $contentInputFile;
    }

    private function getFileTimes($timeAsPhpNumber)
    {
        return [
            'PHP number' => $timeAsPhpNumber,
            'SQL format' => date('Y-m-d H:i:s', $timeAsPhpNumber),
        ];
    }

    public function getMostRecentFile($strFileFirst, $strFileSecond)
    {
        $strFileNameFirst = $this->checkFileExistance('', $strFileFirst);
        $sReturn          = $strFileFirst;
        if (file_exists($strFileSecond)) {
            $infoFirst         = new \SplFileInfo($strFileNameFirst);
            $strFileNameSecond = $this->checkFileExistance('', $strFileSecond);
            $infoSecond        = new \SplFileInfo($strFileNameSecond);
            $sReturn           = $strFileFirst;
            if ($infoFirst->getMTime() <= $infoSecond->getMTime()) {
                $sReturn = $strFileSecond;
            }
        }
        return $sReturn;
    }

    public function getFileJsonContent($strFilePath, $strFileName)
    {
        $fName       = $this->checkFileExistance($strFilePath, $strFileName);
        $fJson       = $this->openFileSafelyAndReturnHandle($fName, 'r', 'read');
        $fileContent = fread($fJson, ((int) filesize($fName)));
        fclose($fJson);
        return $fileContent;
    }

    public function gluePathWithFileName($strFilePath, $strFileName)
    {
        $sReturn = $strFileName;
        if (strpos($strFileName, DIRECTORY_SEPARATOR) === false) {
            $sReturn = $strFilePath . DIRECTORY_SEPARATOR . $strFileName;
        }
        return $sReturn;
    }

    public function openFileSafelyAndReturnHandle($strFileName, $strFileOperationChar, $strFileOperationName)
    {
        $fHandle = fopen($strFileName, $strFileOperationChar);
        if ($fHandle === false) {
            throw new \RuntimeException(sprintf('Unable to open file %s for %s purposes!'
                    . '', $strFileName, $strFileOperationName));
        }
        return $fHandle;
    }
}


<?php

/*
 * This file is part of the Mamasu Framework package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Mmf\Event;

/**
 * The MmfEventObserver is a class used to observes event manage from
 * MmfEventManager
 *
 * @author Xavier Casahuga <xavier.casahuga@mamasu.es>
 *
 */

class EventObserver implements \SplObserver{

    public $isUpdate = false;

    /**
     * TEST
     *
     * @param SplSubject $eventManager
     */
    public function testEvent(\SplSubject $eventManager) {
        echo 'Event name capture:' . $eventManager->event->name     . PHP_EOL;
        echo 'Event name capture:' . $eventManager->event->function . PHP_EOL;
    }

    /**
     * TEST
     *
     * @param SplSubject $eventManager
     */
    public function testEventPropagation(\SplSubject $eventManager) {
        echo 'Propagation Event name capture:' . $eventManager->event->name     . PHP_EOL;
        echo 'Propagation Event name capture:' . $eventManager->event->function . PHP_EOL;
        $this->stopPropagation($eventManager);
    }

    /**
     * TEST
     *
     * @param SplSubject $eventManager
     */
    public function testEventProperties(\SplSubject $eventManager) {
        echo 'Properties Event name capture:' . $eventManager->event->name     . PHP_EOL;
        echo 'Properties Event name capture:' . $eventManager->event->function . PHP_EOL;
        $eventManager->event->properties['propertytochange'] = 'New Content';
    }

    /**
     * When observer wants to stop the further propagations of the event. It
     * requires the EventManager.
     *
     * @throws Exception
     */
    public function stopPropagation() {
        throw new \Exception('Event propagation stop in ' .  get_class(), '600');
    }

    /**
     * Is the function that Event manager will invoke, when the event subscribe
     * for this class will be dispatch.
     *
     * @param SplSubject $eventManager
     */
    public function update(\SplSubject $eventManager) {
        $this->isUpdate = true;
        if ($eventManager->event->function !== NULL) {
            $this->{$eventManager->event->function}($eventManager);
        }
    }

}


<?php

/**
 * This file is part of the Minion package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license MIT License
 */

namespace Minion;

use Knp\Provider\ConsoleServiceProvider;
use Minion\Service\Service;
use Minion\Service\ServiceConfig;
use Minion\Service\ServiceProviderInterface;
use Minion\Twig\AssetExtension;
use Minion\Twig\MiscExtension;
use Minion\Twig\TwigExtensionTagServiceProvider;
use Minion\Twig\UrlExtension;
use Monolog\Logger;
use Propel\Runtime\Exception\InvalidArgumentException;
use Propel\Silex\PropelServiceProvider;
use Silex\Application as SilexApp;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
use Silex\ServiceProviderInterface as SilexServiceProviderInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Yaml\Yaml;

/**
 * Class Application.
 *
 * Wrapper for Silex framework to improve it's flexibility and usability.
 *
 * @package Minion
 * @author Damian Szczerbiński <dszczer@gmail.com>
 */
class Application extends SilexApp
{
    const VERSION = '1.0.0';

    /** @var string Project root directory */
    protected $rootDir;
    /** @var string Package directory */
    protected $packageDir;
    /** @var string Project configuration path */
    protected $configPath;
    /** @var string Propel configuration file */
    protected $propelConfigPath;
    /** @var string Application namespace */
    protected $appNamespace;

    /**
     * Get application namespace.
     *
     * @return string
     */
    public function getAppNamespace() {
        return $this->appNamespace;
    }

    /**
     * Get project root directory.
     *
     * @return string
     */
    public function getRootDir() {
        return $this->rootDir;
    }

    /**
     * get Minion package directory.
     *
     * @return string
     */
    public function getPackageDir() {
        return $this->packageDir;
    }

    /**
     * Get default Propel configuration path.
     *
     * @return string
     */
    public function getPropelConfigPath() {
        return $this->propelConfigPath;
    }

    /**
     * Get configuration path relative to the root directory.
     *
     * @return string
     */
    public function getConfigPath() {
        return $this->configPath;
    }

    /**
     * Application constructor.
     *
     * @param string $appNamespace Application and/or vendor namespace, e.g. 'namespace', 'vendor\\namespace'
     * @param array  $values       Custom configuration
     * @param array  $fixPaths     Fix paths used to bootstrap files and directories
     *
     * @return Application
     *
     * @throws \InvalidArgumentException     Missing propel configuration file
     * @throws \InvalidArgumentException     Can not resolve project namespace
     * @throws InvalidConfigurationException Twig engine is not enabled, but extension configured in config.yml file
     * @throws \RuntimeException             File parameters.yml does not exist
     * @throws \Exception                    Throws raw exceptions in test environment
     */
    public function __construct($appNamespace = '', array $values = [], array $fixPaths = []) {
        // big error catch for nice debug
        try {
            $defaultValues = [
                'environment' => 'prod',
                'minion.usePropel' => true,
                'minion.useTwig' => true,
            ];

            // default configuration
            parent::__construct(\array_replace_recursive($defaultValues, $values));

            // error handler
            $this->error(function(\Exception $ex, $code) {
                return $this->minionError($ex, $code);
            });

            // calculate directories and paths
            $this->resolvePaths($fixPaths);

            // determine project namespace, if not defined
            $realNamespace = $appNamespace;
            $jsonPath = Utils::fixPath($this->getRootDir() . '/composer.json');
            if(!$appNamespace && \file_exists($jsonPath)) {
                $json = \json_decode(\file_get_contents($jsonPath), true);
                if(isset($json['autoload']) && \is_array($json['autoload']))
                    foreach($json['autoload'] as $psr)
                        if(\is_array($psr))
                            foreach($psr as $namespace => $path)
                                if(\preg_match('/^[\\/\\\\]?src[\\/\\\\]?/', $path))
                                    $realNamespace = $namespace;
            }
            if(!$realNamespace)
                throw new \InvalidArgumentException('Cannot resolve project namespace.');
            $this->appNamespace = $realNamespace;

            // register services
            $this->register(new MonologServiceProvider(), [
                'monolog.logfile' => $this->getRootDir() . Utils::fixPath('/var/log/') .
                    ($this['debug'] ? 'dev.log' : 'prod.log'),
                'monolog.name' => $this->getAppNamespace(),
                'monolog.level' => $this['debug'] ? Logger::DEBUG : Logger::WARNING
            ]);

            if($this['minion.useTwig']) {
                $this->register(new TwigServiceProvider(), [
                    'twig.path' => $this->getRootDir() . Utils::fixPath('/src/Resources/views'),
                    'twig.options' => [
                        'cache' => $this['debug'] ? false : $this->getRootDir() . Utils::fixPath('/var/cache/twig'),
                    ],
                ]);
                // load Twig Extensions
                $this['twig']->addExtension(new AssetExtension($this));
                $this['twig']->addExtension(new UrlExtension($this));
                $this['twig']->addExtension(new MiscExtension($this));
            }

            $this->register(new UrlGeneratorServiceProvider());

            if($this['minion.usePropel']) {
                $propelConfig = include Utils::fixPath($this->getPropelConfigPath());
                if(isset($propelConfig['propel']['paths']['phpConfDir'])
                    && \file_exists($propelCompiledCfg = Utils::fixPath($propelConfig['propel']['paths']['phpConfDir']
                        . '/config.php'))
                )
                    $this->register(new PropelServiceProvider(), [
                        'propel.config_file' => $propelCompiledCfg,
                    ]);
                else throw new InvalidArgumentException('Missing Propel compiled configuration file. Use "console propel:config:convert" in console');
            }

            $this->register(new ConsoleServiceProvider(), [
                    'console.name' => $this->getAppNamespace(),
                    'console.version' => self::VERSION,
                    'console.project_directory' => $this->getRootDir(),
                ]
            );

            // load configuration
            $loader = new YamlFileLoader(new FileLocator($this->getRootDir() . $this->getConfigPath()));
            /** @var RouteCollection $routes */
            $routes = $loader->load('routing.yml');
            // fix controller namespaces
            if(\count($routes) > 0)
                foreach($routes as $route)
                    /** @var Route $route */
                    if($route->hasDefault('_controller'))
                        $route->setDefault('_controller', $this->getAppNamespace() . '\\Controller\\'
                            . $route->getDefault('_controller')
                        );
            $this['routes']->addCollection($routes);

            $parametersFile = $this->getRootDir() . $this->getConfigPath() . 'parameters.yml';
            if(!\file_exists($parametersFile))
                throw new \RuntimeException('File parameters.yml does not exist or is not accessible');
            /** @var array $parameters */
            $parameters = Yaml::parse(\file_get_contents($parametersFile)) ?: [];
            $this['parameters'] = new ParameterBag($parameters);

            // load user-defined configuration and services
            $userConfigFile = $this->getRootDir() . $this->getConfigPath() . 'config.yml';
            if(\file_exists($userConfigFile)) {
                /** @var array $userConfig */
                $userConfig = Yaml::parse(\file_get_contents($userConfigFile) ?: '') ?: [];
                if(isset($userConfig['config']))
                    $this['config'] = $userConfig['config'];
                if(isset($userConfig['services']))
                    /**
                     * @var string $id
                     * @var array  $def
                     */
                    foreach($userConfig['services'] as $id => $def) {
                        $serviceConfig = new ServiceConfig($id, $def);
                        $class = $serviceConfig->getProviderClass();

                        if(\count($serviceConfig->getTags()) === 0) {
                            /** @var SilexServiceProviderInterface|ServiceProviderInterface $provider */
                            $provider = new $class;
                            if($provider instanceof ServiceProviderInterface)
                                $provider->setServiceConfig($serviceConfig);
                            $this->register($provider, $serviceConfig->getOptions());
                        } else {
                            $calledTags = [];
                            foreach($serviceConfig->getTags() as $tag) {
                                if(\in_array($tag, $calledTags)) continue;
                                switch($tag) {
                                    case 'twig.extension':
                                        $calledTags[] = $tag;
                                        if(!$this['minion.useTwig'])
                                            throw new InvalidConfigurationException(
                                                "Service '$id' uses 'twig.extension' tag when Twig Environment is not enabled");
                                        $provider = new TwigExtensionTagServiceProvider();
                                        $provider->setServiceConfig($serviceConfig);
                                        $this->register($provider, $serviceConfig->getOptions());
                                        break;
                                    case 'kernel.response':
                                        $calledTags[] = $tag;
                                        $this['event.listener.response'] = $class . '::' . $serviceConfig->getOption('method');
                                        break;
                                }
                            }
                        }
                    }
            }

            // register events
            // inject self to the controller automatically
            $this['dispatcher']->addListener(KernelEvents::CONTROLLER, function(FilterControllerEvent $event) {
                /** @var Controller $controller */
                $controller = $event->getController()[0];
                $controller->setContainer($this);
            });
        } catch(\Exception $ex) {
            if($this['environment'] == 'test')
                throw $ex;
            else
                $this->fastAbort($ex);
        }
    }

    public function run(Request $request = null) {
        if (null === $request) {
            $request = Request::createFromGlobals();
        }

        $response = $this->handle($request);
        $ret = call_user_func($this['event.listener.response'], $request, $response, $this);
        if($ret instanceof Response)
            $response = $ret;
        $response->send();
        $this->terminate($request, $response);
    }

    /**
     * @internal
     *
     * Handle errors and exceptions thrown by entire application.
     *
     * @param \Exception $ex   Any exception
     * @param integer    $code HTTP status code
     *
     * @return Response Response to the client with nice error page
     */
    public function minionError(\Exception $ex, $code) {
        $handler = new ExceptionHandler($this['debug']);
        $exception = FlattenException::create($ex);
        $response = Response::create($handler->getHtml($exception), $code, $exception->getHeaders())
            ->setCharset(\ini_get('default_charset'))
        ;

        if($this['debug'])
            return $response;
        else {
            $content = <<<HTML
<!DOCTYPE html>

    <title>Error $code</title>

Error {$exception->getMessage()} occured

HTML;

            if($this['minion.useTwig'] && isset($this['twig'])) {
                $twig = $this['twig'];
                $tpl = "Static/$code.html.twig";
                if(!Utils::templateExists($twig, $tpl))
                    $content = \str_replace('%d', $code, $content);
                else
                    $content = $twig->render($tpl, ['exception' => $ex]);
            } elseif(\file_exists($tpl = Utils::fixPath($this->getRootDir() . "/Static/$code.html.php")))
                $content = Utils::renderPhpTemplate($tpl, ['exception' => $ex]);

            $response->setStatusCode($code);
            $response->setContent($content);

            return $response;
        }
    }

    /**
     * @internal
     *
     * Terminate application immediately and show exception to the client. Does not trigger any events.
     *
     * @param \Exception $exception Exception instance
     * @param integer    $code      HTTP status code
     *
     * @return void
     */
    public function fastAbort(\Exception $exception, $code = 500) {
        $response = $this->minionError($exception, $code);
        $response->send();
        die;
    }

    /**
     * Resolve paths to navigate through project.
     *
     * @param array $fixPaths User-defined path fixes
     *
     * @return void
     *
     * @throws \InvalidArgumentException Some paths are invalid
     */
    protected function resolvePaths(array $fixPaths) {
        $this->rootDir = \realpath(isset($fixPaths['rootDir']) ? $fixPaths['rootDir'] : __DIR__ . '/../../../../');
        $this->packageDir = \realpath(isset($fixPaths['packageDir']) ? $fixPaths['packageDir'] : __DIR__ . '/../');
        $this->configPath = Utils::fixPath(isset($fixPaths['configPath']) ? $fixPaths['configPath'] : '/app/');

        if($this->rootDir === false || $this->packageDir === false)
            throw new \InvalidArgumentException('Bootstrap directories do not exists or are not accessible');

        if($this['minion.usePropel']) {
            $this->propelConfigPath = \realpath(isset($fixPaths['propelConfigPath']) ? $fixPaths['propelConfigPath']
                : Utils::fixPath($this->packageDir . '/propel.php')
            );
            if($this->propelConfigPath === false)
                throw new \InvalidArgumentException('Propel configuration file in vendor Minion not found');
        }
    }
}


<?php

/*
 * This file is part of the RollerworksCache component package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Cache;

use Doctrine\Common\Cache\CacheProvider;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Doctrine Session Cache-driver.
 *
 * Stores caching data in a Symfony Session.
 *
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class SessionCache extends CacheProvider
{
    protected $session;
    protected $bagName;

    /**
     * Constructor.
     *
     * @param Session              $session
     * @param string               $storageKey
     * @param SessionCacheBag|null $bag
     */
    public function __construct(Session $session, $storageKey = '_rollerworks_cache', SessionCacheBag $bag = null)
    {
        if (!$bag) {
            $bag = new SessionCacheBag($storageKey);
            $session->registerBag($bag);
        }

        $this->bagName = $bag->getName();
        $this->session = $session;
    }

    /**
     * {@inheritdoc}
     */
    protected function doFetch($id)
    {
        return $this->session->getBag($this->bagName)->get($id, false);
    }

    /**
     * {@inheritdoc}
     */
    protected function doContains($id)
    {
        return $this->session->getBag($this->bagName)->has($id);
    }

    /**
     * {@inheritdoc}
     */
    protected function doSave($id, $data, $lifeTime = 0)
    {
        $this->session->getBag($this->bagName)->set($id, $data, $lifeTime);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doDelete($id)
    {
        $this->session->getBag($this->bagName)->remove($id);

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doFlush()
    {
        $this->session->getBag($this->bagName)->clear();

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doGetStats()
    {
        return;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: christof
 * Date: 13.11.15
 * Time: 12:09.
 */
namespace MandarinMedien\MMMediaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\FileBag;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use MandarinMedien\MMMediaBundle\Model\MediaInterface;
use Gaufrette\Filesystem;
use Gaufrette\Adapter\Local as LocalAdapter;

class UploadController extends Controller
{
    /**
     * retrieves and handles the ajax upload action
     * to store uploaded files on file system.
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function uploadAction(Request $request)
    {

        //return new JsonResponse($request);
        #var_dump($request);
        // process the filebag

        $rawMedias = array_merge(
            $this->processUploadedFiles($request->files),
            $this->processUrls($request)
        );

        $em = $this->getDoctrine()->getManager();
        $mtm = $this->get('mm_media.mediatype.manager');

        $returnData = array();

        foreach ($rawMedias as $rawmedia) {
            if (null != ($mt = $mtm->getMediaTypeMatch($rawmedia))) {

                /** @var MediaInterface $ms */
                $ms = $mt->getEntity();
                $em->persist($ms);

                $em->flush();

                $returnData[] = array(
                    'id' => $ms->getId(),
                    'path' => $rawmedia,
                    'mediatype' => (string) $ms->getMediaType(),
                );
            }
        }

        return new JsonResponse(
            array(
                'success' => true,
                'data' => $returnData,
            )
        );
    }

    /**
     * gets the filebag and moves uploaded files to filesystem.
     *
     * @param FileBag $filebag
     *
     * @return array reference list of moved files
     */
    protected function processUploadedFiles(FileBag $filebag)
    {
        $adapter = new LocalAdapter($this->get('kernel')->getRootDir().'/../web/media');
        $filesystem = new Filesystem($adapter);

        $processed = array();

        if ($filebag->get('files')) {
            /*
             * @var UploadedFile
             */
            foreach ($filebag->get('files') as $file) {
                // get the unique filepath
                $dest = $this->createUniquePath($file);

                if ($filesystem->write($dest['path'], file_get_contents($file->getPathname()))) {
                    $processed[] = $dest['path'];
                };
            }
        }

        return $processed;
    }

    /**
     * process the given urls.
     *
     * @param Request $request
     *
     * @return array
     */
    protected function processUrls(Request $request)
    {
        $externalRawMediaUrls = array();

        if ($request->get('urls')) {
            foreach ($request->get('urls') as $url) {
                $externalRawMediaUrls[] = $url;
            }
        }

        return $externalRawMediaUrls;
    }

    /**
     * return a unique filepath.
     *
     * @param UploadedFile $file
     *
     * @return array
     */
    protected function createUniquePath(UploadedFile $file)
    {
        $dir = 'mmmb/'.mb_substr(mb_strtolower((string) $file->getClientOriginalName()), 0, 2);

        $filename = str_replace(array(' ', $file->getClientOriginalExtension()), '-', $file->getClientOriginalName());

        $name = mb_strtolower($filename.uniqid().'.'.$file->getClientOriginalExtension());

        return array(
            'dir' => $dir,
            'filename' => $name,
            'path' => $dir.'/'.$name,
        );
    }
}


<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * 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.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;
use Peach\DF\JsonCodec\Expression;
use Peach\DF\JsonCodec;

/**
 * JSON の BNF ルール number をあらわす Expression です.
 * RFC 7159 で定義されている以下のフォーマットを解釈します.
 *
 * <pre>
 * number = [ minus ] int [ frac ] [ exp ]
 *
 * decimal-point = %x2E       ; .
 *
 * digit1-9 = %x31-39         ; 1-9
 *
 * e = %x65 / %x45            ; e E
 *
 * exp = e [ minus / plus ] 1*DIGIT
 *
 * frac = decimal-point 1*DIGIT
 *
 * int = zero / ( digit1-9 *DIGIT )
 *
 * minus = %x2D               ; -
 *
 * plus = %x2B                ; +
 *
 * zero = %x30                ; 0
 * </pre>
 *
 * @ignore
 */
class Number implements Expression
{
    /**
     * handle() の解析結果です.
     *
     * @var string
     */
    private $result;

    /**
     * handle() の解析結果が float かどうかを判定します.
     *
     * @var bool
     */
    private $isFloat;

    /**
     * PHP の int 型変数で表現できない巨大整数について,
     * string 型に変換するかどうかを表すオプションです.
     *
     * @var bool
     */
    private $bigNumAsString;

    /**
     * 新しい Number インスタンスを構築します.
     */
    public function __construct()
    {
        $this->result         = "";
        $this->isFloat        = false;
        $this->bigNumAsString = false;
    }

    /**
     * number = [ minus ] int [ frac ] [ exp ]
     *
     * @param \Peach\DF\JsonCodec\Context $context
     */
    public function handle(Context $context)
    {
        $this->bigNumAsString = $context->getOption(JsonCodec::BIGINT_AS_STRING);
        $this->handleMinus($context);
        $this->handleIntegralPart($context);
        $this->handleFractionPart($context);
        $this->handleExponentPart($context);
    }

    /**
     * "-" 記号を読み込みます.
     *
     * @param Context $context
     */
    private function handleMinus(Context $context)
    {
        if ($context->current() === "-") {
            $this->result .= "-";
            $context->next();
        }
    }

    /**
     * 数値部分 (以下の BNF 記法) を読み込みます.
     *
     * int = zero / ( digit1-9 *DIGIT )
     *
     * @param Context $context
     */
    private function handleIntegralPart(Context $context)
    {
        // check zero
        if ($context->current() === "0") {
            if (preg_match("/^0[0-9]$/", $context->getSequence(2))) {
                throw $context->createException("Integral part must not start with 0");
            }
            $this->result .= "0";
            $context->next();
            return;
        }

        // check ( digit1-9 *DIGIT )
        $this->handleFirstDigit($context);
        $this->handleDigitSequence($context);
    }

    /**
     * 1 文字目の数字を読み込みます.
     *
     * @param Context $context
     */
    private function handleFirstDigit(Context $context)
    {
        if (self::checkDigit($context)) {
            $this->result .= $context->current();
            $context->next();
        } else {
            throw $context->createException("Invalid number format");
        }
    }

    /**
     * 2 文字目以降の数字列を読み込みます.
     *
     * @param Context $context
     */
    private function handleDigitSequence(Context $context)
    {
        while ($context->hasNext()) {
            if (self::checkDigit($context)) {
                $this->result .= $context->current();
                $context->next();
            } else {
                break;
            }
        }
    }

    /**
     * frac = decimal-point 1*DIGIT
     *
     * @param Context $context
     */
    private function handleFractionPart(Context $context)
    {
        if ($context->current() !== ".") {
            return;
        }

        $this->result .= ".";
        $this->isFloat = true;
        $context->next();
        $this->handleFirstDigit($context);
        $this->handleDigitSequence($context);
    }

    /**
     * exp = e [ minus / plus ] 1*DIGIT
     *
     * @param Context $context
     */
    private function handleExponentPart(Context $context)
    {
        // e = %x65 / %x45
        $current = $context->current();
        if ($current !== "e" && $current !== "E") {
            return;
        }

        $this->result .= "e";
        $this->isFloat = true;
        $next = $context->next();

        // [ minus / plus ]
        if ($next === "+" || $next === "-") {
            $this->result .= $next;
            $context->next();
        }

        // 1*DIGIT
        $this->handleFirstDigit($context);
        $this->handleDigitSequence($context);
    }

    /**
     * 現在の文字が数字 ("0" から "9") かどうかを調べます.
     *
     * @param  Context $context 解析対象の Context
     * @return bool             現在の文字が 0 から 9 のいずれかの場合のみ true
     */
    public static function checkDigit(Context $context)
    {
        $code  = $context->currentCodePoint();
        return (0x30 <= $code && $code <= 0x39);
    }

    /**
     * 解析結果を返します.
     * 返り値の型は解析内容に応じて整数, 文字列, float のいずれかとなります.
     *
     * @return numeric
     */
    public function getResult()
    {
        $num = floatval($this->result);
        if ($this->isFloat) {
            return $num;
        }

        $border = pow(2, 32);
        if (-$border <= $num && $num < $border) {
            return intval($num);
        } else {
            return $this->bigNumAsString ? $this->result : $num;
        }
    }
}


<?php
/**
 * AnimeDb package.
 *
 * @author    Peter Gribanov <info@peter-gribanov.ru>
 * @copyright Copyright (c) 2014, Peter Gribanov
 * @license   http://opensource.org/licenses/MIT
 */

namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver;

class Memcache extends BaseDriver
{
    /**
     * @var \Memcache
     */
    protected $memcache;

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

    /**
     * @param \Memcache $memcache
     * @param string $prefix
     */
    public function __construct(\Memcache $memcache, $prefix)
    {
        $this->memcache = $memcache;
        $this->prefix = $prefix;
    }

    /**
     * @param string $key
     *
     * @return \DateTime|null
     */
    public function get($key)
    {
        $key = $this->prefix.$key;
        if ($time = $this->memcache->get($key)) {
            return (new \DateTime())->setTimestamp($time);
        }

        return null;
    }

    /**
     * @param string $key
     * @param \DateTime $time
     *
     * @return bool
     */
    public function set($key, \DateTime $time)
    {
        $key = $this->prefix.$key;
        if (!($old_time = $this->memcache->get($key)) || $old_time < $time->getTimestamp()) {
            return $this->memcache->set($key, $time->getTimestamp());
        }

        return true;
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function remove($key)
    {
        return $this->memcache->delete($this->prefix.$key);
    }
}


<?php

namespace Peyote;

/**
 * A class to build WHERE clauses.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Where extends \Peyote\Condition implements \Peyote\Mixin
{
	/**
	 * Gets the type of sorting query we are running.
	 *
	 * @return string
	 */
	public function getType()
	{
		return "WHERE";
	}

	/**
	 * Builds an AND WHERE clause.
	 *
	 * @param  string  $column  The column name
	 * @param  string  $op      The comparison operator
	 * @param  mixed   $value   The value to bind
	 * @param  boolean $isParam Is this a parameter (replace value with ? if true)
	 * @return \Peyote\Where
	 */
	public function andWhere($column, $op, $value, $isParam = true)
	{
		$this->clauses[] = array("AND", $column, $op, $value, $isParam);
		return $this;
	}

	/**
	 * Builds an OR WHERE clause.
	 *
	 * @param  string  $column  The column name
	 * @param  string  $op      The comparison operator
	 * @param  mixed   $value   The value to bind
	 * @param  boolean $isParam Is this a parameter (replace value with ? if true)
	 * @return \Peyote\Where
	 */
	public function orWhere($column, $op, $value, $isParam = true)
	{
		$this->clauses[] = array("OR", $column, $op, $value, $isParam);
		return $this;
	}

	/**
	 * Gets all of the methods that should be passed as "mixin" methods.
	 *
	 * @return array
	 */
	public function getMethods()
	{
		return array('andWhere', 'orWhere');
	}

}


<?php

namespace sndsgd\fs\entity;

/**
 * Base class for filesystem entities
 */
abstract class EntityAbstract implements EntityInterface
{
    use \sndsgd\ErrorTrait;

    /**
     * The path as provided to the constructor
     *
     * @var string
     */
    protected $path;

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

    /**
     * Get the path as a string
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->path;
    }

    /**
     * Determine whether the entity is a directory
     *
     * @return bool
     */
    public function isDir(): bool
    {
        return ($this instanceof \sndsgd\fs\entity\DirEntity);
    }

    /**
     * Determine whether the entity is a file
     *
     * @return bool
     */
    public function isFile(): bool
    {
        return ($this instanceof \sndsgd\fs\entity\FileEntity);
    }

    /**
     * Get the path as a string
     *
     * @return string
     */
    public function getPath(): string
    {
        return $this->path;
    }

    /**
     * Get the parent directory name
     *
     * @return string
     */
    public function getDirname(): string
    {
        return dirname($this->path);
    }

    /**
     * Retrieve the basename of the entity
     *
     * @return string
     */
    public function getBasename(): string
    {
        return basename($this->path);
    }

    /**
     * Perform type/permissions tests on an entity
     *
     * @param int $opts
     * @return bool
     */
    public function test(int $opts): bool
    {
        if ($opts & \sndsgd\Fs::EXISTS && file_exists($this->path) === false) {
            $this->error = "'{$this->path}' does not exist";
            return false;
        }
        else if ($opts & \sndsgd\Fs::FILE && is_file($this->path) === false) {
            $this->error = "'{$this->path}' is not a file";
            return false;
        }
        else if ($opts & \sndsgd\Fs::DIR && is_dir($this->path) === false) {
            $this->error = "'{$this->path}' is not a directory";
            return false;
        }
        else if ($opts & \sndsgd\Fs::READABLE && is_readable($this->path) === false) {
            $this->error = "'{$this->path}' is not readable";
            return false;
        }
        else if ($opts & \sndsgd\Fs::WRITABLE && is_writable($this->path) === false) {
            $this->error = "'{$this->path}' is not writable";
            return false;
        }
        else if ($opts & \sndsgd\Fs::EXECUTABLE && is_executable($this->path) === false) {
            $this->error = "'{$this->path}' is not executable";
            return false;
        }
        return true;
    }

    /**
     * Get the parent directory
     *
     * @return \sndsgd\fs\entity\DirEntity|null
     */
    public function getParent()
    {
        if ($this->path === "/" || ($path = dirname($this->path)) === ".") {
            return null;
        }

        return new DirEntity($path);
    }

    /**
     * @inheritDoc
     */
    public function isAbsolute(): bool
    {
        return $this->path{0} === "/";
    }

    /**
     * @inheritDoc
     */
    public function normalize(): EntityInterface
    {
        $path = rtrim($this->path, "/");

        if ($path[0] === ".") {
            $path = $this->normalizeLeadingDots($path);
        }

        # if the first char is not a dot or a directory separator, assume
        # the path is to file or directory in the current working directory
        elseif ($path[0] !== "/") {
            $path = getcwd()."/$path";
        }

        $parts = explode("/", $path);
        $isAbsolute = ($parts[0] === "");
        $temp = [];
        foreach ($parts as $part) {
            if ($part === "." || $part === "") {
                continue;
            }
            elseif ($part === "..") {
                array_pop($temp);
            }
            else {
                $temp[] = $part;
            }
        }
        $temp = implode("/", $temp);
        $this->path = ($isAbsolute) ? "/$temp" : $temp;
        return $this;
    }

    private function normalizeLeadingDots($path)
    {
        if ($path === ".") {
            return getcwd();
        }
        elseif ($path === "..") {
            return dirname(getcwd());
        }
        elseif ($path[0] === "." && $path[1] !== "." && $path[1] !== "/") {
            return getcwd()."/".$path;
        }
        elseif ($path[1] === "/") {
            $path = getcwd().substr($path, 1);
        }
        elseif ($path[1] === ".") {
            $path = dirname(getcwd()).substr($path, 2);
        }
        return $path;
    }

    /**
     * @inheritDoc
     */
    public function normalizeTo($dir)
    {
        if ($this->isAbsolute()) {
            return $this->path;
        }
        $this->path = "$dir/$this->path";
        return $this->normalize();
    }

    /**
     * Get the relative path from the current path to another
     *
     * @param string $path
     * @return string
     */
    public function getRelativePath(string $path): string
    {
        $from = $this->path;

        $fromParts = explode("/", $from);
        $toParts = explode("/", $path);
        $max = max(count($fromParts), count($toParts));
        for ($i=0; $i<$max; $i++) {
            if (
                !isset($fromParts[$i]) ||
                !isset($toParts[$i]) ||
                $fromParts[$i] !== $toParts[$i]
            ) {
                break;
            }
        }

        $len = count($fromParts) - $i - 1;
        $path = array_slice($toParts, $i);
        if ($len < 0) {
            return implode("/", $path);
        }

        return str_repeat("../", $len).implode("/", $path);
    }
}


<?php

/**
 * @author      José Lorente <jose.lorente.martin@gmail.com>
 * @license     The MIT License (MIT)
 * @copyright   José Lorente
 * @version     1.0
 */

namespace jlorente\location\controllers;

use Yii;
use jlorente\location\models\SearchCountry;
use jlorente\location\db\Country;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\helpers\ArrayHelper;

/**
 * CountryController implements the CRUD actions for Country model.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class CountryController extends CrudController
{

    /**
     * Lists all Country models.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SearchCountry();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Country model.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Country model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Country();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Country model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Country model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

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

    /**
     * Finds the Country model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return Country the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Country::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Gets a json list of the countries in the database.
     *
     * @return array
     */
    public function actionList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $searchModel = new SearchCountry();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->setPagination(false);
        $dataProvider->getSort()->defaultOrder = ['name' => SORT_ASC];
        return ArrayHelper::map($dataProvider->getModels(), 'id', 'name');
    }

}


<?php
namespace Gmedia\PipedriveFinisher\Utility;

use Neos\Flow\Annotations as Flow;

class Api
{

  /**
   * @var array
   */
  protected $settings;

  /**
   * Company domain used to build the URI
   * @Flow\InjectConfiguration(path="Api.Domain")
   * @var String
   */
  protected $companyDomain = '';

  /**
   * Token used for authenticating to the API
   * @Flow\InjectConfiguration(path="Api.Token")
   * @var String
   */
  protected $apiToken = '';

  /**
   * Endpoint to be called
   * @var String
   */
  protected $apiEndpoint = '';

  /**
   * Endpoint to be called
   * @var array
   */
  protected $data = array();

  /**
   * @param String $endpoint
   * @return void
  */
  public function __construct(String $endpoint)
  {
    $this->apiEndpoint = $endpoint;
  }

  /**
   * Inject the settings
   *
   * @param array $settings
   * @return void
   */
  public function injectSettings(array $settings) {
      $this->settings = $settings;
  }

  /**
   * Setter function for the data
   *
   * @param array $data
   * @return void
   */
  public function setData(array $data) {
      $this->data = $data;
  }

  /**
   * Builds the complete URI to the API endpoint
   * @return void
   */
  public function execute()
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->getURI());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);

    $response = curl_exec($ch);
    $result = json_decode($response);
    curl_close($ch);

    if (empty($result) || !$result->success) {
      throw new \Exception("Pipedrive API error!");
    }

    return $result;
  }

  /**
   * Builds the complete URI to the API endpoint
   * @return String
   */
  protected function getURI()
  {
    return "https://" . $this->companyDomain . ".pipedrive.com/v1/" .
      $this->apiEndpoint . "?api_token=" . $this->apiToken;
  }
}


<?php

namespace Peyote;

/**
 * A class to define columns
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Column implements Builder
{
	/**
	 * @var string  The name of the column.
	 */
	private $name;

	/**
	 * @var string  The data type for the column.
	 */
	private $type;

	/**
	 * @var boolean  Can this column be null?
	 */
	private $is_null = null;

	/**
	 * @var string  The length of a field
	 */
	private $length = null;

	/**
	 * @var array    Column options (UNSIGNED, ZEROFILL, etc...)
	 */
	private $options = array();

	/**
	 * @var boolean  Is this an auto increment column?
	 */
	private $auto_increment = false;

	/**
	 * @var string   The default value
	 */
	private $default = null;

	/**
	 * @var boolean  Is this column a primary key?
	 */
	private $primary_key = false;

	/**
	 * Below are the keys that can be used in the options parameters
	 *
	 * Key            | Type    | Description
	 * ---------------|---------|-----------------------------------
	 * is_null        | boolean | Can this column be null?
	 * length         | string  | The length of a field (number fields)
	 * options        | array   | A list of data type options (UNSIGNED, ZEROFILL, etc...)
	 * auto_increment | boolean | Auto Increment the column?
	 * default        | string  | The default value for the column
	 *
	 * @param string $name    The name of the column
	 * @param string $type    The type of column
	 * @param array  $options See above for column options that can be set.
	 */
	public function __construct($name, $type, array $options = array())
	{
		if ( ! empty($options))
		{
			$list = array(
				'is_null' => 'setIsNull',
				'length' => 'setLength',
				'options' => 'setOptions',
				'auto_increment' => 'setAutoIncrement',
				'default' => 'setDefault',
			);

			foreach ($list as $key => $fn)
			{
				if (isset($options[$key]))
				{
					$this->{$fn}($options[$key]);
				}
			}
		}

		$this->setName($name);
		$this->setType($type);
	}

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

	/**
	 * @param  string $name    The new column name
	 * @return \Peyote\Column  $this
	 */
	public function setName($name)
	{
		$this->name = $name;
		return $this;
	}

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

	/**
	 * @param  string $type    The data type
	 * @return \Peyote\Column  $this
	 */
	public function setType($type)
	{
		if (\strtolower($type) === 'serial')
		{
			$type = "INT";
			$this->primary_key = true;
			$this->setIsNull(false);
			$this->setAutoIncrement(true);
			$this->addOption('UNSIGNED');
		}

		$this->type = $type;

		return $this;
	}

	/**
	 * @return boolean|null
	 */
	public function getIsNull()
	{
		return $this->is_null;
	}

	/**
	 * @param  boolean $is_null  Should this column be null?
	 * @return \Peyote\Column
	 */
	public function setIsNull($is_null)
	{
		$this->is_null = (boolean) $is_null;
		return $this;
	}

	/**
	 * @return string  The length of the column
	 */
	public function getLength()
	{
		return $this->length;
	}

	/**
	 * @param  string $length  The field length
	 * @return \Peyote\Column  $this
	 */
	public function setLength($length)
	{
		$this->length = $length;
		return $this;
	}

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

	/**
	 * @param  array $options  The column options.
	 * @return \Peyote\Column  $this
	 */
	public function setOptions(array $options)
	{
		$this->options = $options;
		return $this;
	}

	/**
	 * @param  string $option The option to add
	 * @return \Peyote\Column
	 */
	public function addOption($option)
	{
		if ( ! \in_array($option, $this->options))
		{
			$this->options[] = $option;
		}

		return $this;
	}

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

	/**
	 * @param  boolean $flag  Set auto increment?
	 * @return \Peyote\Column
	 */
	public function setAutoIncrement($flag)
	{
		$this->auto_increment = (boolean) $flag;
		return $this;
	}

	/**
	 * @return mixed  The default value or null if it hasn't been set
	 */
	public function getDefault()
	{
		return $this->default;
	}

	/**
	 * @param  string $value The default value
	 * @return \Peyote\Column
	 */
	public function setDefault($value)
	{
		$this->default = $value;
		return $this;
	}

	/**
	 * @return boolean  Is this a primary key column?
	 */
	public function isPrimaryKey()
	{
		return $this->primary_key;
	}

	/**
	 * {@inheritDoc}
	 */
	public function compile()
	{
		$sql = array($this->name);

		$sql[] = $this->length !== null ?
			$this->type."(".$this->length.")" :
			$this->type;

		if ( ! empty($this->options))
		{
			$sql = \array_merge($sql, $this->options);
		}

		if ($this->is_null !== null)
		{
			$sql[] = $this->is_null === true ? "NULL" : "NOT NULL";
		}

		if ($this->default !== null)
		{
			$sql[] = "DEFAULT {$this->default}";
		}

		if ($this->auto_increment === true)
		{
			$sql[] = "AUTO_INCREMENT";
		}

		return join(' ', $sql);
	}
}