<?php
/**
 * PX Commands "clearcache"
 */
namespace picklesFramework2\commands;

/**
 * PX Commands "clearcache"
 *
 *

 *
PX=clearcache

 *
Pickles Framework 2 が生成したキャッシュファイルを削除します。

 *
PX=clearcache.version

 *
Pickles Framework のバージョン番号を JSON 形式の文字列で返します。

 *

 */
class clearcache{

	/**
	 * Picklesオブジェクト
	 */
	private $px;

	/**
	 * ディレクトリ設定
	 */
	private $path_homedir, $path_docroot, $path_public_caches;

	/**
	 * パブリッシュロックファイルのパス
	 */
	private $path_lockfile;

	/**
	 * Starting function
	 * @param object $px Picklesオブジェクト
	 */
	public static function register( $px ){
		$px->pxcmd()->register('clearcache', function($px){
			(new self( $px ))->kick();
			exit;
		});
	}

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 */
	public function __construct( $px ){
		$this->px = $px;
		$this->path_homedir = $this->px->fs()->get_realpath( $this->px->get_realpath_homedir().'/' );
		$this->path_docroot = $this->px->fs()->get_realpath( $this->px->get_realpath_docroot().$this->px->get_path_controot().'/' );
		$this->path_public_caches = $this->px->fs()->get_realpath( $this->px->get_realpath_docroot().$this->px->get_path_controot().@$this->px->conf()->public_cache_dir.'/' );

		$this->path_lockfile = $this->px->fs()->get_realpath( $this->px->get_realpath_homedir().'_sys/ram/publish/applock.txt' );
	}

	/**
	 * kick
	 */
	private function kick(){
		$pxcmd = $this->px->get_px_command();

		if( @$pxcmd[1] == 'version' ){
			// 命令が clearcache.version の場合、バージョン番号を返す。
			$val = $this->px->get_version();
			@header('Content-type: application/json; charset=UTF-8');
			print json_encode($val);
			exit;
		}
		if( @strlen($pxcmd[1]) ){
			// 命令が不明の場合、エラーを表示する。
			if( $this->px->req()->is_cmd() ){
				header('Content-type: text/plain;');
				print $this->px->pxcmd()->get_cli_header();
				print 'execute PX command => "?PX=clearcache"'."\n";
				print $this->px->pxcmd()->get_cli_footer();
			}else{
				$html = '
Go to PX=clearcache to clear caches.
'."\n";
				print $this->px->pxcmd()->wrap_gui_frame($html);
			}
			exit;
		}

		print $this->px->pxcmd()->get_cli_header();
		print 'pickles home directory: '.$this->path_homedir."\n";
		print 'pickles docroot directory: '.$this->path_docroot."\n";
		print 'pickles public cache directory: '.$this->path_public_caches."\n";
		print '------------------------'."\n";
		print "\n";
		if( $this->is_publish_locked() ){
			print 'publish is now locked.'."\n";
			print '  (lockfile updated: '.@date('Y-m-d H:i:s', filemtime($this->path_lockfile)).')'."\n";
			print 'Try again later...'."\n";
			print 'exit.'."\n";
			print $this->px->pxcmd()->get_cli_footer();
			exit;
		}
		$this->exec();
		print "\n";
		print $this->px->pxcmd()->get_cli_footer();
		exit;
	}

	/**
	 * execution: clearcache
	 * 外部から直接呼び出すときはこちら。
	 */
	public function exec(){
		print '-- cleaning "caches"'."\n";
		if( $this->px->site() ){
			$this->px->site()->__destruct(); // sitemap.sqlite を開放 (Windowsで、排他ロックされるためパブリッシュでエラーが起きる問題を回避するため)
		}
		print $this->cleanup_dir( $this->path_homedir.'_sys/ram/caches/' ).' items done.'."\n";
		print "\n";
		print '-- cleaning "publish"'."\n";
		print $this->cleanup_dir( $this->path_homedir.'_sys/ram/publish/' ).' items done.'."\n";
		print "\n";
		if( strlen( @$this->px->conf()->public_cache_dir ) ){
			print '-- cleaning "public caches"'."\n";
			print $this->cleanup_dir( $this->path_public_caches ).' items done.'."\n";
			print "\n";
		}
		return true;
	}

	/**
	 * ディレクトリをクリーニング
	 * @param string $path クリーニング対象のパス
	 * @param string $localpath $pathの仮想のパス (再帰処理のために使用)
	 */
	private function cleanup_dir( $path, $localpath = null ){
		$count = 0;
		$ls = $this->px->fs()->ls($path.$localpath);
		foreach( $ls as $basename ){
			if( $localpath.$basename == '.gitkeep' ){
				continue;
			}
			if( $this->px->fs()->is_dir($path.$localpath.$basename) ){
				$count += $this->cleanup_dir( $path, $localpath.$basename.DIRECTORY_SEPARATOR );

				$i = 0;
				print 'rmdir '.$this->px->fs()->get_realpath( $path.$localpath.$basename );
				while(1){
					$i ++;
					if( $this->px->fs()->rmdir($path.$localpath.$basename) ){
						break;
					}
					if($i > 5){
						print ' [FAILED]';
						break;
					}
					sleep(1);
				}
				print "\n";
				$count ++;

			}else{
				clearstatcache();
				if( $this->px->fs()->get_realpath($path.$localpath.$basename) == $this->path_lockfile ){
					// パブリッシュロックファイルは消さない
				}else{
					$i = 0;
					print 'rm '.$this->px->fs()->get_realpath( $path.$localpath.$basename );
					while(1){
						$i ++;
						if( $this->px->fs()->rm($path.$localpath.$basename) ){
							break;
						}
						if($i > 5){
							print ' [FAILED]';
							break;
						}
						sleep(1);
					}
					print "\n";
					$count ++;
				}
			}
		}

		if( is_null($localpath) ){
			$this->px->fs()->save_file( $path.$localpath.'.gitkeep', '' );
		}
		return $count;
	}

	/**
	 * パブリッシュがロックされているか確認する。
	 *
	 * @return bool ロック中の場合に `true`、それ以外の場合に `false` を返します。
	 */
	private function is_publish_locked(){
		$lockfilepath = $this->path_lockfile;
		$lockfile_expire = 60*30;//有効期限は30分

		#	PHPのFileStatusCacheをクリア
		clearstatcache();

		if( $this->px->fs()->is_file($lockfilepath) ){
			if( ( time() - filemtime($lockfilepath) ) > $lockfile_expire ){
				#	有効期限を過ぎていたら、ロックは成立する。
				return false;
			}
			return true;
		}
		return false;
	}//is_publish_locked()

}


<?php

namespace Owl\Service;

if (!extension_loaded('mongo')) {
    throw new \Exception('Require "mongo" extension');
}

class Mongodb extends \Owl\Service
{
    private $client;

    public function __construct(array $config = [])
    {
        parent::__construct(static::normalizeConfig($config));
    }

    public function __call($method, array $args)
    {
        return call_user_func_array([$this->connect(), $method], $args);
    }

    public function disconnect()
    {
        if ($this->isConnected()) {
            $this->client->close();
        }

        $this->client = null;

        return true;
    }

    public function connect()
    {
        if (!$this->client) {
            $this->client = new \MongoClient($this->getConfig('dsn'), $this->getConfig('options') ?: []);
        } elseif (!$this->client->connected) {
            $this->client->connect();
        }

        return $this->client;
    }

    public function isConnected()
    {
        return $this->client && $this->client->connected;
    }

    /**
     * @example
     * $collection = $mongo->getCollection('db', 'collection');
     * $collection = $mongo->getCollection('db.collection');
     * $collection = $mongo->getCollection(['db', 'collection']);
     */
    public function getCollection($db, $collection = null)
    {
        if ($db instanceof \MongoCollection) {
            return $db;
        }

        if ($collection === null) {
            if (is_array($db)) {
                $collection = $db[1];
                $collection = $db[0];
            } else {
                $target = explode('.', $db, 2);
                list($db, $collection) = $target;
            }
        }

        return $this->selectCollection($db, $collection);
    }

    public function find($collection, array $query = [], array $fields = [])
    {
        return $this->getCollection($collection)->find($query, $fields);
    }

    public function findOne($collection, array $query = [], array $fields = [])
    {
        return $this->getCollection($collection)->findOne($query, $fields);
    }

    public function insert($collection, array $record, array $options = [])
    {
        return $this->getCollection($collection)->insert($record, $options);
    }

    public function save($collection, array $record, array $options = [])
    {
        return $this->getCollection($collection)->save($record, $options);
    }

    public function update($collection, array $criteria, array $record, array $options = [])
    {
        return $this->getCollection($collection)->update($criteria, $record, $options);
    }

    public function remove($collection, array $criteria, $options = [])
    {
        return $this->getCollection($collection)->remove($criteria, $options);
    }

    /**
     * 格式化配置数据.
     *
     * @param array $config
     * @static
     *
     * @return array
     */
    public static function normalizeConfig(array $config)
    {
        $config = array_merge([
            'dsn' => sprintf('mongodb://%s:%s', ini_get('mongo.default_host'), ini_get('mongo.default_port')),
        ], $config);

        if (!isset($config['options'])) {
            $config['options'] = [];
        }

        $config['options'] = array_merge([
            'connectTimeoutMS' => 3000,
            'socketTimeoutMS' => 3000,
        ], $config['options']);

        return $config;
    }
}


<?php

namespace Fracture\Routing;

class Route implements Matchable
{

    protected $name;

    protected $pattern;

    protected $defaults;

    public function __construct($pattern, $name, $defaults = [])
    {
        $this->name = $name;
        $this->pattern = $pattern;
        $this->defaults = $defaults;
    }

    /**
     * Method attempts to apply the generated regexp to the URI
     * and, if successful, returns a list of parsed parameters.
     *
     * @param string $uri
     *
     * @return array|false
     */
    public function getMatch($uri)
    {
        $expression = $this->pattern->getExpression();
        $matches = [];

        if (preg_match($expression, $uri, $matches) === 0) {
            return false;
        }

        $matches = $this->cleanMatches($matches);
        $matches = $this->removeNoise($matches);
        return $matches + $this->defaults;
    }

    protected function cleanMatches($matches)
    {
        $list = [];

        foreach ($matches as $key => $value) {
            if (is_numeric($key) === false && $value !== '') {
                $list[$key] = $value;
            }
        }

        return $list;
    }

    protected function removeNoise($matches)
    {
        foreach ($matches as $key => $value) {
            $matches[$key] = str_replace(['_', '-'], '', $value);
        }

        return $matches;
    }
}


<?php

namespace Clio\Styling\Markup;

/**
 * This class is part of the Clio Open Source project, Clio.1happyplace.com
 * Copyright, Katie Ayres, katie@1happyplace.com
 *
 * Available through the MIT license
 * @license MIT
 *
 * The Justification class is a simple class allowing for a variety of ways
 * to specify justification, either Justification::LEFT, etc, or the word
 * "Left", "right", etc
 *
 */
class Justification
{
    /**
     * Justification constants
     */
    const NONE   = 200;
    const LEFT   = 201;
    const CENTER = 202;
    const RIGHT  = 203;

    /**
     * Used to look up strings that can be used instead of the justification constants
     * @var array
     */
    public static $justificationConstants =  [
        "NONE"   => 200,
        "LEFT"   => 201,
        "CENTER" => 202,
        "RIGHT"  => 203
    ];

    /**
     * Lookup table for the correct padding for a particular justification
     * @var array
     */
    public static $paddingLookup = [
        self::LEFT      => STR_PAD_RIGHT,
        self::CENTER    => STR_PAD_BOTH,
        self::RIGHT     => STR_PAD_LEFT,
        self::NONE      => STR_PAD_RIGHT];

    /**
     * Function to take a value and turn it into a justification constant
     *
     * @param string | int $value - if a string, it can be "left", "RIGHT", etc..., if an int, just needs to be a constant
     * @return int - the constant it represents or LEFT if it is garbage
     */
    public static function getJustificationConstant($value) {

        // if the value coming in, is a integer, ensure it is one of the constants
        if (is_int($value)) {

            // get the justification integer values
            $values = array_values(self::$justificationConstants);

            // if the integer submitted is one of those values, return it
            if (in_array($value, $values)) {

                // return the valid value
                return $value;
            }

        }
        // if the value coming in is a string
        else if (is_string($value)) {

            // trim the string
            $value = trim($value);

            // transform to uppercase
            $value = strtoupper($value);

            // if it is in the array of string values
            if (isset(self::$justificationConstants[$value])) {

                // return the matching integer value
                return self::$justificationConstants[$value];

            } else {

                // not a valid string
                return self::LEFT;
            }

        } else {

            // something went wrong, return left
            return self::LEFT;
        }

        return self::LEFT;
    }

}


<?php
/**
 * Created by Pangodream.
 * User: Development
 * Date: 30/10/2018
 * Time: 12:32
 */

namespace Dominia;

use GuzzleHttp\Client;

class Crawler
{
    private $uriBase = null;
    private $excludes = array("Estad",
                              "Dominios ",
                              "Dominios%20",
                              "Presentac",
                              "Agentes",
                              "_dominios_",
                              "estad%C3%ADsticas",
                              "Caracterizaci",
                              "folleto",
                              "certificado", );
    private $mainPage = "/dominios/es/todo-lo-que-necesitas-saber/estadisticas";
    private $client = null;
    private $docsHome = null;

    /**
     * Crawler constructor.
     *
     * @param string $uriBase          Base of dominios.es uri (def: https://www.dominios.es)
     * @param float $requestTimeout    Request timeout in seconds (def: 30.0)
     */
    public function __construct($uriBase = "https://www.dominios.es", $requestTimeout = 30.0){
        $this->uriBase = $uriBase;
        $this->client = new Client(['base_uri' => $uriBase,
            'timeout' => $requestTimeout, ]);
    }

    /**
     * Main crawler function.
     * It retrieves the content of the main dominios.es page to extract the links to pdf documents
     * It returns the number of processed files (the previously downloaded files are skipped)
     * @return int   Processed files
     */
    public function extract(){
        $count = 0;
        if ($this->docsHome == null){
            die('Error. You must first set documents home (setDocsHome)');
        }
        $mainContent = $this->getMainPage();
        $documentsLink = $this->extractDocumentsLink($mainContent);
        foreach($documentsLink as $link){
            $processed = $this->processLink($link);
            if($processed == true){
                $count++;
            }
        }
        return $count;
    }

    /**
     * Establish the folder where files will be stored
     * @param $docsHome   Path to docs home, the folder where pdf files will be downloaded to
     */
    public function setDocsHome($docsHome){
        $this->docsHome = $docsHome;
    }

    /**
     * List the local pdf files stored in Docs Home
     * @return array Array containing the pdf files entries. Each entry is an associative array
     *               of type ('path'=>docs home folder, 'fileName'=>nameOfFile.pdf)
     */
    public function listLocalFiles(){
        $files = array();
        $dir = dir($this->docsHome);
        while (false !== ($file = $dir->read())) {
            if(substr($file, -4)==".pdf"){
                $files[] = array('path'=>$this->docsHome, 'fileName'=>$file);
            }
        }
        return $files;
    }

    /**
     * Returns the main page content (html)
     * @return \Psr\Http\Message\StreamInterface
     */
    private function getMainPage(){
        $mainContent = $this->getDocument($this->mainPage);
        return $mainContent;
    }

    /**
     * Retrieves the content of the document specified by the $query parameter
     * @param $query   QueryString of pdf document
     * @return \Psr\Http\Message\StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function getDocument($query){
        $response = $this->client->request('GET', $query);
        $content = $response->getBody();
        return $content;
    }

    /**
     * Parses the main page html to extract the links to pdf documents
     * @param $html   html content of the main page
     * @return array  Array containing all the pdf documents links
     */
    private function extractDocumentsLink($html){
        $links = array();
        //preg_match_all("#<a\ href=\"(.*)\.pdf\"#", $html, $matches);
        preg_match_all("#<a\ href=\"(.*)\"#", $html, $matches);
        foreach($matches[1] as $f) {
            $pospdf = strpos($f,".pdf");
            if($pospdf !== false) {
                $f = substr($f, 0, $pospdf + 4);
                if (!$this->excludeLink($f)) {
                    $links[] = $f;
                }
            }
        }
        return $links;
    }

    /**
     * Evaluates if a link to a pdf document is not a valid domains document pdf and should be excluded
     * @param $href   Link to the pdf document
     * @return bool   Evaluation result
     */
    private function excludeLink($href)
    {
        //If href string contains any of the 'words' in $excludes array, return true
        $excluded = false;
        foreach ($this->excludes as $word) {
            if (strpos($href, $word) !== false) {
                $excluded = true;
                break;
            }
        }
        return $excluded;
    }

    /**
     * Retrieve and save a pdf document specified by $link parameter
     * @param $link   QueryString to pdf document
     * @return bool   True if the document is new and not skipped
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function processLink($link){
        $processed = false;
        $hash = md5($link);
        $filename = $this->getFilename($link);
        if(!$this->existePdf($filename, $hash)){
            //echo $link . "\n";
            $content = $this->getDocument($link);
            $this->saveFile($filename, $content, $hash);
            $processed = true;
            echo $link . "\n";
        }else{
            echo "Skipped\n";
        }
        return $processed;
    }

    /**
     * Extracts the filename of the pdf document from the specified link
     * @param $link
     * @return mixed
     */
    private function getFilename($link){
        $parts = explode("/", $link);
        return $parts[sizeof($parts)-1];
    }

    /**
     * Calculates a hash for the file and stores the content in docs home folder
     * @param $filename
     * @param $content
     * @param $hash
     */
    private function saveFile($filename, $content, $hash){
        $ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
        file_put_contents($ruta, $content);
    }

    /**
     * Checks if a file exists in docs home folder
     * @param $filename
     * @param $hash
     * @return bool
     */
    private function existePdf($filename, $hash){
        $ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
        return file_exists($ruta);
    }
}


<?php

namespace Clio\Widgets\Lists;

class OrderedList extends BulletedList
{

    /**
     * Keeps track of bullet numbers between calls to li
     * @var array - holds one index for each nesting level to keep separate counts
     */
    protected $orderedNumbers = [];

    /**
     * This returns the correct number for a list item depending on the current nesting level
     * @return string
     */
    protected function getNextOrderedNumber() {

        // see if the current nesting has an entry in the orderedNumbers array
        if (array_key_exists($this->nesting, $this->orderedNumbers)) {

            // it does, so increase the number by 1
            $this->orderedNumbers[$this->nesting] = $this->orderedNumbers[$this->nesting] + 1;

        } else {

            // it doesn't, so start a new index and initialize the number at 1
            $this->orderedNumbers[$this->nesting] = 1;
        }

        // if this is the second level nesting...
        if ($this->nesting === 2) {

            // return a character starting with a
            return chr(96 + $this->orderedNumbers[$this->nesting]);

            // if this is the fourth level nesting
        } else if ($this->nesting === 4) {

            // return a character starting with A
            return chr(64 + $this->orderedNumbers[$this->nesting]);

            // otherwise use numbers for nesting level 1,3,5 and greater
        } else {

            // return the current number for this nesting
            return $this->orderedNumbers[$this->nesting];
        }

    }

    /**
     * Display a list item
     * @param $text - the item
     * @return $this
     */
    public function li($text) {

        $this->drawListItem($this->getNextOrderedNumber() . ". ", $text);

        // chaining
        return $this;
    }

    /**
     * End the current ordered or unordered list
     */
    public function end() {

        // remove this ordered number tracking for this nesting
        if (array_key_exists($this->nesting, $this->orderedNumbers)) {

            // remove the item off the array
            unset ($this->orderedNumbers[$this->nesting]);
        }

        // close the start
        parent::end();

        // chaining
        return $this;
    }

}


<?php

namespace Clio\Layout;

use Clio\Clio;
use Clio\Styling\Style;

/**
 * This class is part of the Clio Open Source project, Clio.1happyplace.com
 * Copyright, Katie Ayres, katie@1happyplace.com
 *
 * Available through the MIT license
 * @license MIT
 *
 * This class displays text in paragraph form.
 *
 */
class Paragraph
{

    /**
     * The clio object that handles the output to the terminal
     * @var Clio|null
     */
    public $clio = null;

    /**
     * The style for the paragraph, if defined
     * @var Style | null
     */
    public $style = null;

    /**
     * The number of lines after the paragraph
     * @var int
     */
    protected $spaceAfter = 1;

    /**
     * Whether to trim the incoming text
     * @var bool
     */
    protected $trim = true;

    /**
     * ModernParagraph constructor.
     * @param Clio $clio -the Clio object, generally want just one instance to represent the current terminal
     * @param Style | null $style
     * @param int $spaceAfter
     * @param bool $trim - whether to trim text coming in
     */
    public function __construct($clio, $style = null, $spaceAfter = 1, $trim = true)
    {
        // save the clio object
        $this->clio = $clio;

        // save the style object
        $this->style = $style;

        // save the number of empty lines to show after the paragraph
        $this->spaceAfter = $spaceAfter;

        // save whether to trim the incoming text
        $this->trim = $trim;

    }

    /**
     * Helper function to display a line with styling (if it has been specified)
     */
    private function displayWithStyling($text) {

        // create an empty line for space after
        $emptyLine = str_pad(" ",$this->clio->getWidth());

        // if the style was defined
        if ($this->style) {

            // set the style
            $this->clio->style($this->style);
        }

        // display the text on multiple lines
        $this->clio->display($text);

        // if there is a style
        if ($this->style) {

            // clear the styling
            $this->clio->clear();
        }
    }

    /**
     * Display one paragraph, which will be word-wrapped according
     * to the left margin and width specified in the HTML object.
     *
     * Additionally, any markup will trigger styles. If the markup
     * isn't closed, it will continue across multiple paragraphs.
     * @param $text
     * @return $this
     */
    public function display($text) {

        // if trimming was desired
        if ($this->trim) {

            // trim any front or ending spaces
            $text = trim($text);
        }

        // if there is no text, no need to continue
        if (strlen($text) == 0) {

            // no need to continue
            return $this;
        }

        // wordwrap to the width of the html screen
        $text = $this->clio->wordwrap($text, $this->clio->getWidth(), false);

        // now get the lines that have been wordwrapped
        $lines = explode("\n",$text);

        // shortcut to the width
        $width = $this->clio->getWidth();

        // start the justified version of the wrapped text
        $justifiedText = "";

        // create an empty line for space after
        $emptyLine = str_pad(" ",$this->clio->getWidth());

        // shortcut
        $numLines = count($lines);

        // go through each line
        for ($i=0; $i<$numLines; ++$i) {

            // get the next line
            $next = $lines[$i];

            // ask Clio to justify the text and pad to the edge
            $justifiedText .= $this->clio->justify($next,"left",$width) . "\n";

            // if this is not the last line
//            if ($i < ($numLines-1)) {
//
//                // add a new line (the last one is left for space after
//                $justifiedText .= "\n";
//            }n

        }

        // now display the text
        $this->displayWithStyling($justifiedText);

        $this->nl($this->spaceAfter);

        // chaining
        return $this;
    }

    /**
     * Create a new line with the styling of the paragraph
     * @param int $count
     */
    public function nl($count = 1) {

        // create an empty line for space after
        $emptyLine = str_pad(" ",$this->clio->getWidth()) . "\n";

        // go through each line
        for ($i=0; $i<$count; ++$i) {

            // display an empty line, so the styling carries through to the right edge
            $this->displayWithStyling($emptyLine);

        }
    }

}


<?php
/**
 * class bowl
 *
 * Pickles 2 のコアオブジェクトの1つ `$bowl` のオブジェクトクラスを定義します。
 *
 * @author Tomoya Koyanagi <tomk79@gmail.com>
 */
namespace picklesFramework2;

/**
 * Bowl
 *
 * Pickles 2 のコアオブジェクトの1つ `$bowl` のオブジェクトクラスです。
 * このオブジェクトは、Pickles 2 の初期化処理の中で自動的に生成され、`$px` の内部に格納されます。
 *
 * メソッド `$px->bowl()` を通じてアクセスします。
 *
 * @author Tomoya Koyanagi <tomk79@gmail.com>
 */
class bowl{

	/**
	 * コンテンツボウル
	 */
	private $contents_bowl = array(
		// 'main'=>'', // メインコンテンツ
		// 'head'=>'', // ヘッドセクションに追記
		// 'foot'=>''  // body要素の最後に追記
	);

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

	/**
	 * コンテンツボウルにコンテンツを入れる。
	 *
	 * ソースコードを `$px` オブジェクトに預けます。
	 * このメソッドから預けられたコードは、同じ `$content_name` 値 をキーにして、
	 * `$px->bowl()->get()` または `$px->bowl()->get_clean()` から引き出すことができます。
	 *
	 * この機能は、コンテンツからテーマへコンテンツを渡すために使用されます。
	 *
	 * 同じ名前(`$content_name`値)で複数回ソースを送った場合、後方に追記されます。
	 *
	 * @param string $src 入れるHTMLソース
	 * @param string $content_name ボウルの格納名。(省略時 `main`)
	 * `$px->bowl()->get()` で取り出す際に使用する名称です。
	 * 任意の名称が利用できます。 Pickles 2 の標準状態では、
	 * 無名(空白文字列) = `main` = メインコンテンツ、
	 * `head` = HEADセクション内コンテンツ(CSS等)、
	 * `foot` = BODYセクション末尾コンテンツ(JavaScript等)、
	 * の3種類が定義されています。
	 *
	 * @return bool 成功時 true、失敗時 false
	 */
	public function put( $src, $content_name = 'main' ){
		if( !strlen($content_name) ){ $content_name = 'main'; }
		if( !is_string($content_name) ){ return false; }
		if( !array_key_exists($content_name, $this->contents_bowl) ){
			$this->contents_bowl[$content_name] = '';
		}
		$this->contents_bowl[$content_name] .= $src;
		return true;
	}

	/**
	 * コンテンツボウルにコンテンツを送る。 (deprecated)
	 *
	 * このメソッドは非推奨です。 代わりに、 `$px->bowl()->put()` を使用してください。
	 *
	 * @param string $src 入れるHTMLソース
	 * @param string $content_name ボウルの格納名。(省略時 `main`)
	 * `$px->bowl()->get()` で取り出す際に使用する名称です。
	 * 任意の名称が利用できます。 Pickles 2 の標準状態では、
	 * 無名(空白文字列) = `main` = メインコンテンツ、
	 * `head` = HEADセクション内コンテンツ(CSS等)、
	 * `foot` = BODYセクション末尾コンテンツ(JavaScript等)、
	 * の3種類が定義されています。
	 *
	 * @return bool 成功時 true、失敗時 false
	 */
	public function send( $src, $content_name = 'main' ){
		return $this->put( $src, $content_name );
	}

	/**
	 * コンテンツボウルのコンテンツを置き換える。
	 *
	 * ソースコードを$pxオブジェクトに預けます。
	 * `$px->bowl()->put()` と同じですが、複数回送信した場合に、このメソッドは追記ではなく上書きする点が異なります。
	 *
	 * @param string $src 送るHTMLソース
	 * @param string $content_name ボウルの格納名。(省略時 'main')
	 * `$px->bowl()->get_clean()` から取り出す際に使用する名称です。
	 * 任意の名称が利用できます。PxFWの標準状態では、無名(空白文字列) = メインコンテンツ、'head' = ヘッダー内コンテンツ の2種類が定義されています。
	 *
	 * @return bool 成功時 true、失敗時 false
	 */
	public function replace( $src, $content_name = 'main' ){
		if( !strlen($content_name) ){ $content_name = 'main'; }
		if( !is_string($content_name) ){ return false; }
		@$this->contents_bowl[$content_name] = $src;
		return true;
	}

	/**
	 * コンテンツボウルからコンテンツを取り出す。
	 *
	 * 取り出したコンテンツは、ボウルから削除されます。
	 *
	 * @param string $content_name ボウルの格納名。(省略時 `main`)
	 * @return mixed 成功時、ボウルから得られたHTMLソースを返す。失敗時、false
	 */
	public function get_clean( $content_name = 'main' ){
		if( !strlen($content_name) ){ $content_name = 'main'; }
		if( !is_string($content_name) ){ return false; }
		if( !array_key_exists($content_name, $this->contents_bowl) ){ return null; }

		$content = $this->contents_bowl[$content_name];
		unset( $this->contents_bowl[$content_name] );// コンテンツを取り出したら、ボウル上にはなくなる。

		return $content;
	}

	/**
	 * コンテンツボウルからコンテンツの複製を取り出す。
	 *
	 * 取り出したコンテンツは、ボウル内にも残ります。
	 *
	 * @param string $content_name ボウルの格納名。(省略時 `main`)
	 * @return mixed 成功時、ボウルから得られたHTMLソースを返す。失敗時、false
	 */
	public function get( $content_name = 'main' ){
		if( !strlen($content_name) ){ $content_name = 'main'; }
		if( !is_string($content_name) ){ return false; }
		if( !array_key_exists($content_name, $this->contents_bowl) ){ return null; }

		$content = $this->contents_bowl[$content_name];

		return $content;
	}

	/**
	 * コンテンツボウルからコンテンツを引き出す。(deprecated)
	 *
	 * このメソッドは非推奨です。 代わりに `$px->bowl()->get_clean()` を使用してください。
	 *
	 * @param string $content_name ボウルの格納名。(省略時 `main`)
	 * @return mixed 成功時、ボウルから得られたHTMLソースを返す。失敗時、false
	 */
	public function pull( $content_name = 'main' ){
		return $this->get_clean( $content_name );
	}

	/**
	 * コンテンツボウルにあるコンテンツの索引を取得する。
	 *
	 * @return array ボウルのキーの一覧
	 */
	public function get_keys(){
		$keys = array_keys( $this->contents_bowl );
		return $keys;
	}

	/**
	 * 全ボウルのコンテンツに同じ加工を施す。
	 *
	 * @param callback $func 加工処理関数
	 * @return object $bowlオブジェクト
	 */
	public function each( $func ){
		foreach( $this->get_keys() as $key ){
			$src = $this->get_clean( $key );
			$src = call_user_func( $func, $src );
			$src = $this->replace( $src, $key );
		}
		return $this;
	}

}


<?php

namespace Zeeml\Algorithms\Prediction\Linear;

use Zeeml\Algorithms\AlgorithmsInterface;
use Zeeml\Algorithms\Exceptions\WrongUsageException;
use Zeeml\Algorithms\Formulas\Mean;
use Zeeml\Algorithms\Formulas\MultipleLinearCoefficients;
use Zeeml\Algorithms\Formulas\SimpleLinearCoefficients;
use Zeeml\Algorithms\Prediction\Prediction;
use Zeeml\DataSet\DataSet;
use Zeeml\Algorithms\Formulas\Benchmark;
use Zeeml\Algorithms\Formulas\LinearPrediction;

/**
 * Class LinearRegression that trains the dataSet following either the simple or multiple linear regression
 *  - Simple Linear Regression : if the number of dimension is 1
 *  - Multiple Linear Regression : if the number of dimension is greater than 1
 *
 * The number of outputs must always be equal to 1 (an exception is thrown otherwise)
 */
class LinearRegression extends Prediction
{
    protected $coefficients = [];

    /**
     * Trains the dataSet following the Linear Regression Algorithm
     * @param DataSet $dataSet
     * @param float $learningRate
     * @return AlgorithmsInterface
     * @throws WrongUsageException
     */
    public function fit(DataSet $dataSet, float $learningRate = 0.0): AlgorithmsInterface
    {
        $outputSize = count($dataSet->getMapper()->getOutputKeys());
        if ($outputSize !== 1) {
            throw new WrongUsageException('Linear regression assumes only one output, ' . $outputSize . ' given');
        }

        if (count($dataSet->getMapper()->getDimensionKeys()) === 1) {
            $this
                ->calculator
                ->using($dataSet)
                ->calculate(new Mean())
                ->then(new SimpleLinearCoefficients());
            ;
        } else {
            $this->coefficients = $this
                ->calculator
                ->using($dataSet)
                ->calculate(new MultipleLinearCoefficients())
                ->getResult()
                ->last()
            ;
        }

        $this->coefficients = $this->calculator->getResult()->last();

        return $this;
    }

    /**
     * tests the dataSet using the intercept and slope found during the fit and returns the accuracy of the algorithm
     * Takes the dataSet by reference and fills it with prediction
     *
     * @param DataSet $dataSet
     * @throws WrongUsageException
     */
    public function test(DataSet $dataSet)
    {
        if (empty($this->coefficients)) {
            throw new WrongUsageException('Test can not be run after fit');
        }

        $this->predict($dataSet);
    }

    /**
     * Makes a linear prediction of input based on coefficients
     * @param DataSet $dataSet
     * @throws WrongUsageException
     */
    public function predict(DataSet $dataSet)
    {
        foreach ($dataSet as $instance) {
            $prediction = $this
                ->calculator
                ->calculate(new LinearPrediction($instance->getDimensions(), $this->coefficients))
                ->getResult()
                ->last()
            ;
            $instance->addResult(
                static::class,
                [
                    'type'   => self::PREDICTION,
                    'result' => $prediction
                ]
            );
        }

        $this->calculator->using($dataSet)->calculate(new Benchmark(LinearRegression::class));
        $results = $this->calculator->getResult()->of(Benchmark::class);

        $this->accuracy = $results[Benchmark::ACCURACY] ?? 0;
        $this->rmse = $results[Benchmark::RMSE] ?? 0;
    }

    /**
     * Gets the coefficients
     * @return array
     */
    public function getCoefficients(): array
    {
        return $this->coefficients;
    }
}


<?php
namespace Skillberto\SonataPageMenuBundle\DependencyInjection\Compiler;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Skillberto\SonataPageMenuBundle\DependencyInjection\Configuration;

class GlobalVariablesCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $configs = $container->getExtensionConfig('skillberto_sonata_page_menu');
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->getDefinition('twig')
            ->addMethodCall('addGlobal', ['sonata_page_menu', $config]);
    }

    private function processConfiguration(ConfigurationInterface $configuration, array $configs)
    {
        $processor = new Processor();

        return $processor->processConfiguration($configuration, $configs);
    }
}


<?php
namespace Owl\Service\DB;

abstract class Table
{
    protected $adapter;
    protected $table_name;
    protected $columns;
    protected $indexes;
    protected $foreign_keys;

    /**
     * @return array
     *
     * [
     *     (string) => [
     *         'primary_key' => (boolean),
     *         'type' => (string),
     *         'sql_type' => (string),
     *         'character_max_length' => (integer),
     *         'numeric_precision' => (integer),
     *         'numeric_scale' => (integer),
     *         'default_value' => (mixed),
     *         'not_null' => (boolean),
     *         'comment' => (string),
     *     ],
     *     ...
     * ]
     */
    abstract protected function listColumns();

    /**
     * @return array
     *
     * [
     *     [
     *         'name' => (string),
     *         'columns' => [(string), ...],
     *         'is_primary' => (boolean),
     *         'is_unique' => (boolean),
     *     ],
     *     ...
     * ]
     */
    abstract protected function listIndexes();

    /**
     * @return array
     *
     * [
     *     [
     *         'name' => (string),
     *         'reference_table' => (string),
     *         'reference_columns' => [
     *             (string) => (string),    // local column => reference column
     *             ...
     *         ],
     *     ],
     * ]
     */
    abstract protected function listForeignKeys();

    public function __construct(Adapter $adapter, $table_name)
    {
        $this->adapter = $adapter;
        $this->table_name = $table_name;
    }

    public function __clone()
    {
        $this->reset();
    }

    public function reset()
    {
        $this->columns = null;
        $this->indexes = null;
        $this->foreign_keys = null;
    }

    /**
     * 获得表名.
     *
     * @return string
     */
    public function getName()
    {
        return $this->table_name;
    }

    /**
     * 获得数据库连接对象
     *
     * @return \Owl\Service\DB\Adapter
     */
    public function getAdapter()
    {
        return $this->adapter;
    }

    /**
     * 获得所有的字段信息.
     *
     * @return array
     */
    public function getColumns()
    {
        if ($this->columns === null) {
            $this->columns = $this->listColumns();
        }

        return $this->columns;
    }

    /**
     * 获得指定字段的信息.
     *
     * @return array
     */
    public function getColumn($column_name)
    {
        $columns = $this->getColumns();

        return isset($columns[$column_name]) ? $columns[$column_name] : [];
    }

    /**
     * 获得所有的索引信息.
     *
     * @return array
     */
    public function getIndexes()
    {
        if ($this->indexes === null) {
            $this->indexes = $this->listIndexes();
        }

        return $this->indexes;
    }

    /**
     * 检查字段是否存在.
     *
     * @param string $column_name
     *
     * @return bool
     */
    public function hasColumn($column_name)
    {
        $columns = $this->getColumns();

        return isset($columns[$column_name]);
    }

    /**
     * 检查索引是否存在.
     *
     * @param string $index_name
     *
     * @return bool
     */
    public function hasIndex($index_name)
    {
        foreach ($this->getIndexes() as $index) {
            if ($index['name'] === $index_name) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获得外键关联定义.
     *
     * @see Table::listForeignKeys()
     *
     * @return array
     */
    public function getForeignKeys()
    {
        if ($this->foreign_keys === null) {
            $this->foreign_keys = $this->listForeignKeys();
        }

        return $this->foreign_keys;
    }

    /**
     * 获得有关键关联的表，返回Table对象数组.
     *
     * @return array
     */
    public function getReferenceTables()
    {
        $tables = [];

        foreach ($this->getForeignKeys() as $foreign_key) {
            $table_name = $foreign_key['reference_table'];

            $tables[$table_name] = new static($this->adapter, $table_name);
        }

        return array_values($tables);
    }

    /**
     * 获得指定字段上的索引.
     *
     * @param string $column_name
     *
     * @return array
     */
    public function getIndexesOfColumn($column_name)
    {
        $result = [];

        foreach ($this->getIndexes() as $index) {
            if (in_array($column_name, $index['columns'])) {
                $result[] = $index;
            }
        }

        return $result;
    }

    /**
     * 创建查询对象
     *
     * @return \Owl\Service\DB\Select
     */
    public function select()
    {
        return $this->adapter->select($this->table_name);
    }

    /**
     * 插入一条记录，返回插入的行数.
     *
     * @param array $row
     *
     * @return int
     */
    public function insert(array $row)
    {
        return $this->adapter->insert($this->table_name, $row);
    }

    /**
     * 更新记录，允许指定条件
     * 返回被更新的行数.
     *
     * @param array  $row
     * @param string $where
     * @param mixed  $parameters
     *
     * @return int
     */
    public function update(array $row/*, $where = null, $parameters = null*/)
    {
        $args = func_get_args();
        array_unshift($args, $this->table_name);

        return call_user_func_array([$this->adapter, 'update'], $args);
    }

    /**
     * 删除记录，允许指定条件.
     *
     * @param string $where
     * @param mixed  $parameters
     *
     * @return int
     */
    public function delete(/*$where = null, $parameters = null*/)
    {
        $args = func_get_args();
        array_unshift($args, $this->table_name);

        return call_user_func_array([$this->adapter, 'delete'], $args);
    }
}


<?php
/**
 * theme "pickles"
 */
namespace picklesFramework2\theme;

/**
 * theme "pickles" class
 */
class theme_top{
	/**
	 * objects
	 */
	private $px, $theme;

	/**
	 * constructor
	 * @param object $px $px object
	 * @param object $theme $theme object
	 */
	public function __construct( $px, $theme ){
		$this->px = $px;
		$this->theme = $theme;
		// $this->px->path_theme_files('css/common.css');
		// $this->px->path_theme_files('css/layout.css');
		// $this->px->path_theme_files('css/modules_custom.css');
	}//__construct()

	/**
	 * カラースキームを取得
	 * @return array カラースキーム
	 */
	public function get_color_scheme(){
		$colors = array();
		$colors['main'] = '#00a0e6';
		$hsb = [
			"h"=>198,
			"s"=>100,
			"b"=>90
		];
		$colors['thin'] = "#bae5f8";

		$colors['link'] = $colors['main'];
		$colors['text'] = '#333';
		$colors['white'] = '#fff';
		$colors['black'] = '#333';

		if( $hsb['s'] < 50 && $hsb['b'] > 50 ){
			// $colors['link'] = '#00f';
			$colors['thin'] = $colors['main'];
			$colors['link'] = '#000';
			$colors['white'] = '#333';
			$colors['black'] = '#fff';
		}
		return $colors;
	}//get_color_scheme()

	/**
	 * リンクアイコンのSVGロゴソースを返す。
	 * @param array $type アイコンの種類
	 *
	 * blank, download, pdf, up, down, back, icon(default) のいずれかを指定。
	 * @param array $opt オプション
	 * @return string SVGソース
	 */
	public function create_src_link_icon_uri($type, $opt = array()){
		$colors = $this->get_color_scheme();
		if( is_array(@$opt['colors']) ){
			foreach( $opt['colors'] as $key=>$val ){
				$colors[$key] = $val;
			}
		}
		$colors['linkx'] = '#fff';
		$tpl = null;
		switch($type){
			case 'blank':
				$tpl = 'blank';
				break;
			case 'download':
				$tpl = 'download';
				break;
			case 'pdf':
				$tpl = 'pdf';
				break;
			case 'up':
				$points = '3.631,9.183 7.001,3.817 10.369,9.183';
				break;
			case 'down':
				$points = '10.369,3.817 6.999,9.183 3.631,3.817';
				break;
			case 'back':
				$points = '9.683,9.869 4.317,6.499 9.683,3.131';
				break;
			case 'icon':
			default:
				$type = 'icon';
				$tpl = 'icon';
				$points = '4.317,3.131 9.683,6.501 4.317,9.869';
				break;
		}
		ob_start();
		if( $tpl == 'blank' ){?>
<svg version="1.1" id="link_<?php print htmlspecialchars($type); ?>" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="14px" height="13px" viewBox="0 0 14 13" enable-background="new 0 0 14 13" xml:space="preserve">
<g><path fill="<?php print htmlspecialchars($colors['link']); ?>" d="M0,3v10h10V3H0z M9,12H1V6h8V12z"/><rect x="1" y="6" fill="<?php print htmlspecialchars($colors['linkx']); ?>" width="8" height="6" /></g>
<g><path fill="<?php print htmlspecialchars($colors['link']); ?>" d="M4,0v10h10V0H4z M13,9H5V3h8V9z"/><rect x="5" y="3" fill="<?php print htmlspecialchars($colors['linkx']); ?>" width="8" height="6" /></g>
</svg>
<?php }elseif( $tpl == 'download' ){ ?>
<svg version="1.1" id="link_<?php print htmlspecialchars($type); ?>" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="14px" height="13px" viewBox="0 0 14 13" enable-background="new 0 0 14 13" xml:space="preserve">
<polygon fill="<?php print htmlspecialchars($colors['link']); ?>" points="13,8 13,12 1,12 1,8 0,8 0,13 14,13 14,8 "/>
<polygon fill="<?php print htmlspecialchars($colors['link']); ?>" points="10.062,7.093 10.062,0.968 3.938,0.968 3.938,7.093 1.824,7.093 7,11.031 12.176,7.093 "/>
</svg>
<?php }elseif( $tpl == 'pdf' ){ ?>
<svg version="1.1" id="link_<?php print htmlspecialchars($type); ?>" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 width="14px" height="13px" viewBox="0 0 14 13" enable-background="new 0 0 14 13" xml:space="preserve">
<path fill="<?php print htmlspecialchars($colors['link']); ?>" d="M1,0v13h12V0H1z"/>
<g>
	<path fill="<?php print htmlspecialchars($colors['linkx']); ?>" d="M2.021,8.398V4.602h1.433c0.252,0,0.444,0.012,0.578,0.036C4.218,4.669,4.375,4.729,4.5,4.814
		c0.126,0.088,0.227,0.21,0.304,0.367C4.882,5.34,4.92,5.512,4.92,5.7c0,0.321-0.103,0.595-0.308,0.82
		C4.406,6.743,4.035,6.855,3.498,6.855H2.524v1.543H2.021z M2.524,6.407h0.982c0.324,0,0.555-0.062,0.691-0.183
		s0.205-0.29,0.205-0.51c0-0.159-0.04-0.295-0.12-0.408C4.201,5.194,4.096,5.12,3.964,5.083C3.88,5.061,3.723,5.049,3.496,5.049
		H2.524V6.407z"/>
	<path fill="<?php print htmlspecialchars($colors['linkx']); ?>" d="M5.56,8.398V4.602h1.308c0.295,0,0.521,0.018,0.676,0.054c0.218,0.051,0.403,0.141,0.557,0.272
		c0.2,0.168,0.351,0.385,0.449,0.649c0.1,0.264,0.149,0.563,0.149,0.901c0,0.288-0.033,0.545-0.101,0.768
		C8.531,7.468,8.445,7.653,8.34,7.799S8.118,8.061,7.993,8.144S7.717,8.292,7.54,8.333C7.363,8.378,7.16,8.398,6.93,8.398H5.56z
		 M6.062,7.95h0.811c0.25,0,0.447-0.023,0.59-0.069s0.256-0.113,0.341-0.197c0.118-0.119,0.211-0.279,0.277-0.481
		c0.067-0.201,0.101-0.444,0.101-0.731c0-0.396-0.065-0.701-0.196-0.915C7.855,5.343,7.697,5.2,7.51,5.127
		C7.376,5.075,7.159,5.049,6.86,5.049H6.062V7.95z"/>
	<path fill="<?php print htmlspecialchars($colors['linkx']); ?>" d="M9.417,8.398V4.602h2.562v0.447H9.92v1.176h1.782v0.448H9.92v1.726H9.417z"/>
</g>
</svg>
<?php }else{ ?>
<svg version="1.1" id="link_<?php print htmlspecialchars($type); ?>" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="14px" height="13px" viewBox="0 0 14 13" enable-background="new 0 0 14 13" xml:space="preserve">
<rect y="2" width="14" height="9" fill="<?php print htmlspecialchars($colors['link']); ?>" />
<polygon fill="<?php print htmlspecialchars($colors['linkx']); ?>" points="<?php print htmlspecialchars($points); ?>"/>
</svg>
<?php
		}
		return 'data:image/svg+xml;base64,'.base64_encode( ob_get_clean() );
	}//create_src_link_icon_uri()

	/**
	 * welcomeイメージのソースを返す。
	 * @param array $opt オプション
	 * @return string SVGソース
	 */
	public function create_src_welcome_svg($opt = array()){
		$colors = $this->get_color_scheme();
		if( @strlen($opt['color']) ){
			$colors['mainx'] = $opt['color'];
		}
		$svg_src = file_get_contents( __DIR__.'/svg/welcome.svg' );
		$svg_src = str_replace( '#0000ff', htmlspecialchars($colors['link']), $svg_src );
		return $svg_src;
	}//create_src_welcome_svg()

	/**
	 * セットアップを検証する
	 * @return array エラーの一覧。エラーがない場合は、空白の配列 `array()` が返ります。
	 */
	public function setup_test(){
		$errors = array();

		// システムディレクトリの確認
		$sysdirs = array(
			'_sys/ram/' ,
			'_sys/ram/applock/' ,
			'_sys/ram/caches/' ,
			'_sys/ram/publish/' ,
			'_sys/ram/data/' ,
		);
		foreach( $sysdirs as $sysdir ){
			$realpath = $this->px->fs()->get_realpath( $this->px->get_path_homedir().$sysdir );
			if( !is_dir( $realpath ) ){
				array_push( $errors, 'システムディレクトリ '.htmlspecialchars($realpath).' が存在しません。' );
			}elseif( !is_writable( $realpath ) ){
				array_push( $errors, 'システムディレクトリ '.htmlspecialchars($realpath).' に書き込み許可がありません。' );
			}
		}

		// 公開キャッシュディレクトリの確認
		$realpath = $this->px->fs()->get_realpath( './'.$this->px->conf()->public_cache_dir.'/' );
		if( !is_dir( $realpath ) ){
			array_push( $errors, '公開キャッシュディレクトリ '.htmlspecialchars($realpath).' が存在しません。' );
		}elseif( !is_writable( $realpath ) ){
			array_push( $errors, '公開キャッシュディレクトリ '.htmlspecialchars($realpath).' に書き込み許可がありません。' );
		}
		return $errors;
	}

	/**
	 * セットアップ検証結果を表示する
	 * @param array $errors `setup_test()` が返したエラー一覧
	 * @return string HTMLソース
	 */
	public function mk_setup_test( $errors = array() ){
		// 結果のエラーメッセージ(または成功メッセージ)を生成して返す。
		$rtn = '';
		if( count($errors) ){
			$rtn .= '
エラー
';
			$rtn .= '
Pickles Framework のセットアップに、一部不備があります。
次の項目を確認してください。
';
			$rtn .= '
';
			foreach( $errors as $error ){
				$rtn .= '
'.htmlspecialchars($error).'
';
			}
			$rtn .= '
';

		}else{
			$rtn .= '
おめでとうございます！
Pickles Framework のセットアップは正常に完了しました。
';
		}
		return $rtn;
	}
}


<?php
namespace Addons\Core;

use Addons\Core\Cache\RWRedis;
use Addons\Core\Middleware\Encrypt;
use Addons\Core\Http\ResponseFactory;
use Addons\Core\Middleware\CrossDomain;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
	/**
	 * 指定是否延缓提供者加载。
	 *
	 * @var bool
	 */
	protected $defer = false;
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton(RWRedis::class, function ($app) {
			return new RWRedis();
		});
		//replace class
		$this->app->bind('Illuminate\Contracts\Routing\ResponseFactory', ResponseFactory::class);

		$this->mergeConfigFrom(__DIR__ . '/../config/mimes.php', 'mimes');
		$this->mergeConfigFrom(__DIR__ . '/../config/output.php', 'output');

		//register router middleware
		$router = $this->app['router'];
		$router->aliasMiddleware('cross-domain', CrossDomain::class);
		$router->aliasMiddleware('encrypt', Encrypt::class);

		$this->app->instance('path.vendor', realpath(__DIR__.'/../../../'));
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->publishes([__DIR__ . '/../config/mimes.php' => config_path('mimes.php')], 'config');

		$this->app['translator']->addNamespace('core', realpath(__DIR__.'/../resources/lang/'));
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['core'];
	}
}


<?php

namespace JetFire\Framework\Log;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;
use PDO;
use PDOStatement;
/**
 * This class is a handler for Monolog, which can be used
 * to write records in a MySQL table
 *
 * Class MySQLHandler
 */
class PDOHandler extends AbstractProcessingHandler
{
    /**
     * @var bool defines whether the MySQL connection is been initialized
     */
    private $initialized = false;
    /**
     * @var PDO pdo object of database connection
     */
    protected $pdo;
    /**
     * @var PDOStatement statement to insert a new record
     */
    private $statement;
    /**
     * @var string the table to store the logs in
     */
    private $table = 'logs';
    /**
     * @var string[] additional fields to be stored in the database
     *
     * For each field $field, an additional context field with the name $field
     * is expected along the message, and further the database needs to have these fields
     * as the values are stored in the column name $field.
     */
    private $additionalFields = array();
    /**
     * Constructor of this class, sets the PDO and calls parent constructor
     *
     * @param PDO $pdo                  PDO Connector for the database
     * @param bool $table               Table in the database to store the logs in
     * @param array $additionalFields   Additional Context Parameters to store in database
     * @param bool|int $level           Debug level which this handler should store
     * @param bool $bubble
     */
    public function __construct(
        PDO $pdo = null,
        $table,
        $additionalFields = array(),
        $level = Logger::DEBUG,
        $bubble = true
    ) {
        if (!is_null($pdo)) {
            $this->pdo = $pdo;
        }
        $this->table = $table;
        $this->additionalFields = $additionalFields;
        parent::__construct($level, $bubble);
    }
    /**
     * Initializes this handler by creating the table if it not exists
     */
    private function initialize()
    {
        $this->pdo->exec(
            'CREATE TABLE IF NOT EXISTS `'.$this->table.'` '
            .'(id INTEGER PRIMARY KEY AUTO_INCREMENT, channel VARCHAR(255),level_name VARCHAR(255), level INTEGER, message LONGTEXT, date DATETIME)'
        );
        //Read out actual columns
        $actualFields = array();
        $rs = $this->pdo->query('SELECT * FROM `'.$this->table.'` LIMIT 0');
        for ($i = 0; $i < $rs->columnCount(); $i++) {
            $col = $rs->getColumnMeta($i);
            $actualFields[] = $col['name'];
        }
        //Calculate changed entries
        $removedColumns = array_diff(
            $actualFields,
            $this->additionalFields,
            array('id', 'channel', 'level','level_name', 'message', 'date')
        );
        $addedColumns = array_diff($this->additionalFields, $actualFields);
        //Remove columns
        if (!empty($removedColumns)) {
            foreach ($removedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` DROP `'.$c.'`;');
            }
        }
        //Add columns
        if (!empty($addedColumns)) {
            foreach ($addedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` add `'.$c.'` TEXT NULL DEFAULT NULL;');
            }
        }
        //Prepare statement
        $columns = "";
        $fields = "";
        foreach ($this->additionalFields as $f) {
            $columns.= ", $f";
            $fields.= ", :$f";
        }
        $this->statement = $this->pdo->prepare(
            'INSERT INTO `'.$this->table.'` (channel, level, level_name, message, date'.$columns.')
            VALUES (:channel, :level, :level_name, :message, :date'.$fields.')'
        );
        $this->initialized = true;
    }
    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param  $record[]
     * @return void
     */
    protected function write(array $record)
    {
        if (!$this->initialized) {
            $this->initialize();
        }
        //'context' contains the array
        $contentArray = array_merge(array(
            'channel' => $record['channel'],
            'level' => $record['level'],
            'level_name' => $record['level_name'],
            'message' => $record['message'],
            'date' => $record['datetime']->format('Y-m-d H:i:s')
        ), $record['context']);
        //Fill content array with "null" values if not provided
        $contentArray = $contentArray + array_combine(
                $this->additionalFields,
                array_fill(0, count($this->additionalFields), null)
            );
        $this->statement->execute($contentArray);
    }
}


<?php

namespace Clio\Widgets\Lists;

use Clio\Clio;

/**
 * This class is part of the Clio Open Source project, Clio.1happyplace.com
 * Copyright, Katie Ayres, katie@1happyplace.com
 *
 * Available through the MIT license
 * @license MIT
 *
 * The BulletedList class generates a list
 *      - such as this one, which is unordered
 *      - It can be ordered
 *          1. Like this
 *          2. As well as nested
 *
 * The bullet can also be defined to any string.  The end() method must be called if nesting is used to indicate
 * the end of a level.
 *
 */
abstract class BulletedList
{

    /**
     * The number of blank spaces to indent
     * @var int
     */
    protected $indentation = 3;

    /**
     * Used for ordered and unordered lists, keeping track of current nesting level
     * 0 is used to indicate that no ul or ol is in progress
     * @var int
     */
    protected $nesting = 0;

    /**
     * The clio object that handles the output to the terminal
     * @var Clio|null
     */
    protected $clio = null;

    /**
     * BulletedList constructor.
     * @param Clio $clio -the Clio object, generally want just one instance to represent the current terminal
     */
    public function __construct($clio)
    {
        // save the clio html object
        $this->clio = $clio;
    }

    /**
     * Based on the current nesting, return a string to move text to the right
     * @return string
     */
    protected function createIndentation() {

        // determine the indentation based on the current level of nesting
        $indentation = $this->indentation * ($this->nesting);

        // return a blank string of that length
        return str_pad("",$indentation);
    }

    /**
     * Helper function to draw one list item
     *
     * @param string $bullet - the bullet plus any white space to the right
     * @param string $text
     */
    protected function drawListItem($bullet, $text) {

        // determine the blank space indentation
        $indentation = $this->createIndentation();

        // In unordered list, the bullet can be specified
        $left = $indentation . $bullet;

        // determine the width of the bullet text
        $bulletTextArea = $this->clio->getWidth() - strlen($left);

        // word wrap the rest of the bullet
        $text = $this->clio->wordwrap($text,$bulletTextArea, false);

        // create an empty string that is the same with of the bullet
        $emptyBullet = str_pad("",strlen($bullet));

        // replace all newlines with a newline then indentation, then an empty bullet
        $text = str_replace("\n", "\n" . $indentation . $emptyBullet, $text);

        // show the bullet and text on multiple lines (if needed)
        $this->clio->display($left . $text)->newLine();

    }

    /////////////////////////////////////////////////////////////////////////////////////////
    //                                 List Generation                                     //
    /////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Start an ordered list
     * @param $text String | null - text to show on the very first line, will not work for anything nested
     * @return $this
     */
    public function start($text = null) {

        // if text was defined and it the first level of nesting
        if ($text && ($this->nesting === 0)) {

            // display the text with any markup
            $this->clio->display($text)->newLine();

        }

        // add one to the nesting
        ++$this->nesting;

        // chaining
        return $this;
    }

    /**
     * Generate a list item in the list
     *
     * @param string $text
     */
    abstract public function li($text);

    /**
     * End the current ordered or unordered list
     */
    public function end() {

        // subtract one from the nesting level
        --$this->nesting;

        // chaining
        return $this;
    }

}


<?php

namespace JetFire\Framework\Providers;

use InvalidArgumentException;

/**
 * Class CacheProvider
 * @package JetFire\Framework\Providers
 */
class CacheProvider extends Provider
{

    /**
     * @var array
     */
    protected $config;
    /**
     * @var mixed
     */
    protected $cache;
    /**
     * @var array
     */
    protected $cacheDrivers = [
        'Doctrine\Common\Cache\ArrayCache' => 'getNativeCache',
        'Doctrine\Common\Cache\ApcCache' => 'getNativeCache',
        'Doctrine\Common\Cache\XcacheCache' => 'getNativeCache',
        'Doctrine\Common\Cache\FilesystemCache' => 'getFileCache'
    ];

    /**
     * CacheProvider constructor.
     * @param array $config
     * @param $use
     * @throws \Exception
     */
    public function init($config = [], $use)
    {
        $this->config = $config;
        $this->cache = $this->getCache($use);
        $this->app->addAlias($use, $config['drivers'][$use]['class']);
    }

    /**
     * @param null $key
     * @return mixed
     * @throws \Exception
     */
    public function getCache($key = null)
    {
        if (is_null($key)) {
            return $this->cache;
        }elseif (isset($this->cacheDrivers[$this->config['drivers'][$key]['class']])) {
            return call_user_func_array([$this, $this->cacheDrivers[$this->config['drivers'][$key]['class']]], [$this->config['drivers'][$key]]);
        } elseif (isset($this->config['drivers'][$key]['callback'])) {
            $callback = $this->config['drivers'][$key]['callback'];
            if (!$this->app->has($callback)) {
                throw new \Exception('Callback : ' . $callback . ' not found in DI.');
            }
            if (!method_exists(($provider = $this->app->get($callback)), 'getCache')) {
                throw new \Exception('Method "getCache" not found in ' . get_class($provider));
            }
            return $provider->getCache($this->config['drivers'][$key]);
        }
        return null;
    }

    /**
     * @param $driver
     * @return mixed
     */
    private function getNativeCache($driver)
    {
        $this->app->addRule($driver['class'], [
            'shared' => true
        ]);
        return $this->app->get($driver['class']);
    }

    /**
     * @param $driver
     * @return mixed
     */
    private function getFileCache($driver)
    {
        if (!isset($driver['args'][0]) || !isset($driver['args'][1])) {
            throw new InvalidArgumentException('Arguments for file cache driver missing');
        }
        $this->app->addRule($driver['class'], [
            'shared' => true,
            'construct' => [$driver['args'][0], $driver['args'][1]]
        ]);
        return $this->app->get($driver['class']);
    }

}


<?php
/**
 * @author Andrey Samusev <Andrey.Samusev@exigenservices.com>
 * @copyright andrey 9/18/13
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FDevs\Photatoes;

class ImageSize
{
    const SIZE_ORIG = 'orig';
    const SIZE_XXS = 'XXS';
    const SIZE_XL = 'XL';
    const SIZE_XXL = 'XXL';
    const SIZE_M = 'M';
    const SIZE_L = 'L';
    const SIZE_XXXS = 'XXXS';
    const SIZE_S = 'S';
    const SIZE_XS = 'XS';

    private static $allowedSize = array(
        self::SIZE_L => 'L',
        self::SIZE_M => 'M',
        self::SIZE_ORIG => 'orig',
        self::SIZE_S => 'S',
        self::SIZE_XL => 'XL',
        self::SIZE_XXL => 'XXL',
        self::SIZE_XS => 'XS',
        self::SIZE_XXS => 'XXS',
        self::SIZE_XXXS => 'XXXS',
    );

    /**
     * @var array
     */
    private static $size = array(
        self::SIZE_L => array(
            'width' => 500,
            'height' => 500,
        ),
        self::SIZE_M => array(
            'width' => 300,
            'height' => 300,
        ),
        self::SIZE_ORIG => array(
            'width' => 0,
            'height' => 0,
        ),
        self::SIZE_S => array(
            'width' => 150,
            'height' => 150,
        ),
        self::SIZE_XL => array(
            'width' => 800,
            'height' => 800,
        ),
        self::SIZE_XXL => array(
            'width' => 1024,
            'height' => 765,
        ),
        self::SIZE_XS => array(
            'width' => 100,
            'height' => 75,
        ),
        self::SIZE_XXS => array(
            'width' => 75,
            'height' => 75,
        ),
        self::SIZE_XXXS => array(
            'width' => 50,
            'height' => 50,
        ),
    );

    /**
     * get name allowed return
     *
     * @param  string      $name
     * @return string|null
     */
    public static function get($name)
    {
        $name = (strtolower($name) === self::SIZE_ORIG) ? self::SIZE_ORIG : strtoupper($name);

        return isset(self::$allowedSize[$name]) ? self::$allowedSize[$name] : null;
    }

    /**
     * has size
     *
     * @param  string $name
     * @return bool
     */
    public static function has($name)
    {
        return isset(self::$allowedSize[$name]);
    }

    /**
     * @param  int    $width
     * @param  int    $height
     * @return string
     */
    public static function getSize($width = 0, $height = 0)
    {
        $size = 'orig';
        $array = array_filter(self::$size, function ($var) use ($width, $height) {
            return ($var['width'] >= $width && $var['height'] >= $height);
        });
        if (count($array)) {
            asort($array);
            $size = key($array);
        }

        return $size;
    }
}


<?php

/*
 * This file is part of the SexyField package.
 *
 * (c) Dion Snoeijen <hallo@dionsnoeijen.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare (strict_types=1);

namespace Tardigrades\SectionField\Form;

use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Form\Forms;
use Tardigrades\Entity\FieldInterface;
use Tardigrades\Entity\SectionInterface;
use Tardigrades\FieldType\FieldTypeInterface;
use Tardigrades\SectionField\Form\FormInterface as SectionFormInterface;
use Tardigrades\SectionField\Generator\CommonSectionInterface;
use Tardigrades\SectionField\Service\ReadSectionInterface;
use Tardigrades\SectionField\Service\SectionManagerInterface;
use Tardigrades\SectionField\ValueObject\FullyQualifiedClassName;
use Tardigrades\SectionField\ValueObject\Id;
use Tardigrades\SectionField\Service\ReadOptions;
use Tardigrades\SectionField\ValueObject\SectionConfig;
use Tardigrades\SectionField\ValueObject\SectionFormOptions;
use Tardigrades\SectionField\ValueObject\Slug;

class Form implements SectionFormInterface
{
    /** @var SectionManagerInterface */
    private $sectionManager;

    /** @var FormFactory */
    private $formFactory;

    /** @var ReadSectionInterface */
    private $readSection;

    public function __construct(
        SectionManagerInterface $sectionManager,
        ReadSectionInterface $readSection,
        FormFactory $formFactory = null
    ) {
        $this->sectionManager = $sectionManager;
        $this->readSection = $readSection;
        $this->formFactory = $formFactory;
    }

    /**
     * This method generates a form based on the section config.
     * The for handle contains the section handle, or the FQCN of the section entity.
     * By pasing along SectionFormOptions this method can determine of the form
     * is meanth to update or create new data.
     *
     * @param string $forHandle
     * @param RequestStack $requestStack
     * @param SectionFormOptions|null $sectionFormOptions
     * @param bool $csrfProtection
     * @return FormInterface
     */
    public function buildFormForSection(
        string $forHandle,
        RequestStack $requestStack,
        SectionFormOptions $sectionFormOptions = null,
        bool $csrfProtection = true
    ): FormInterface {

        $sectionConfig = $this->getSectionConfig($forHandle);
        $section = $this->getSection($sectionConfig->getFullyQualifiedClassName());

        // If we have a slug, it means we are updating something.
        // Prep so we can get the correct $sectionEntity
        $slug = null;
        if ($sectionFormOptions !== null) {
            try {
                $slug = $sectionFormOptions->getSlug();
            } catch (\Exception $exception) {
                $slug = null;
            }
        }

        // If we hava an id, it means we are updating something.
        // Prep so we can get the correct $sectionEntity
        $id = null;
        if ($sectionFormOptions !== null) {
            try {
                $id = $sectionFormOptions->getId();
            } catch (\Exception $exception) {
                $id = null;
            }
        }

        $sectionEntity = $this->getSectionEntity(
            $sectionConfig->getFullyQualifiedClassName(),
            $section,
            $slug,
            $id
        );

        $factory = $this->getFormFactory($requestStack);

        $form = $factory
            ->createBuilder(
                FormType::class,
                $sectionEntity,
                [
                    'method' => 'POST',
                    'attr' => [
                        'novalidate' => 'novalidate'
                    ],
                    'csrf_protection' => $csrfProtection,
                    'csrf_field_name' => 'token',
                    'csrf_token_id'   => 'tardigrades',
                    'allow_extra_fields' => true // We need to allow extra fields for extra section fields (ignored in the generators)
                ]
            );

        /** @var FieldInterface $field */
        foreach ($section->getFields() as $field) {
            $fieldTypeFullyQualifiedClassName = (string) $field
                ->getFieldType()
                ->getFullyQualifiedClassName();

            /** @var FieldTypeInterface $fieldType */
            $fieldType = new $fieldTypeFullyQualifiedClassName;
            $fieldType->setConfig($field->getConfig());
            $fieldType->addToForm(
                $form,
                $section,
                $sectionEntity,
                $this->sectionManager,
                $this->readSection,
                $requestStack->getCurrentRequest()
            );
        }

        $form->add('save', SubmitType::class);
        return $form->getForm();
    }

    /**
     * A section can be summoned by either it's handle: 'someCoolHandle'
     * or it's fully qualified class name: 'Vendor\Entity\SomeCoolEntity'
     * Make sure we fetch the entity config so we can get the FQCN from there
     * @param string $forHandle
     * @return SectionConfig
     */
    private function getSectionConfig(string $forHandle): SectionConfig
    {
        return $this->sectionManager->readByHandle(
            FullyQualifiedClassName::fromString($forHandle)->toHandle()
        )->getConfig();
    }

    /**
     * If you use SexyField with symfony you might want to inject the formFactory from the framework
     * If you use it stand-alone this will build a form factory right here.
     * @return FormFactory
     */
    private function getFormFactory(RequestStack $requestStack): FormFactory
    {
        $factory = $this->formFactory;
        if (empty($this->formFactory)) {
            $validatorBuilder = Validation::createValidatorBuilder();
            // Loads validator metadata from entity static method
            $validatorBuilder->addMethodMapping('loadValidatorMetadata');
            $validator = $validatorBuilder->getValidator();
            if (!$session = $requestStack->getCurrentRequest()->getSession()) {
                $session = new Session();
            }
            $csrfGenerator = new UriSafeTokenGenerator();
            $csrfStorage = new SessionTokenStorage($session);
            $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
            $factory = Forms::createFormFactoryBuilder()
                ->addExtension(new CsrfExtension($csrfManager))
                ->addExtension(new ValidatorExtension($validator))
                ->getFormFactory();
        }
        return $factory;
    }

    private function getSection(
        FullyQualifiedClassName $forHandle
    ): SectionInterface {
        return $this->sectionManager->readByHandle(
            $forHandle->toHandle()
        );
    }

    private function getSectionEntity(
        FullyQualifiedClassName $forHandle,
        SectionInterface $section,
        Slug $slug = null,
        Id $id = null
    ): CommonSectionInterface {

        if (!empty($slug)) {
            $sectionEntity = $this->readSection->read(ReadOptions::fromArray([
                ReadOptions::SECTION => $forHandle,
                ReadOptions::SLUG => $slug
            ]))->current();
        }

        else if (!empty($id)) {
            $sectionEntity = $this->readSection->read(ReadOptions::fromArray([
                ReadOptions::SECTION => $forHandle,
                ReadOptions::ID => $id->toInt()
            ]))->current();
        }

        if (empty($sectionEntity)) {
            $sectionFullyQualifiedClassName = (string) $section->getConfig()->getFullyQualifiedClassName();
            $sectionEntity = new $sectionFullyQualifiedClassName;
        }

        return $sectionEntity;
    }
}


<?php

namespace Greg\Support\Http;

use Greg\Support\Arr;
use Greg\Support\Server;

trait RequestStaticTrait
{
    protected static $isHumanReadableFiles = false;

    protected static $checkFileUpload = true;

    protected static $DS = DIRECTORY_SEPARATOR;

    private static $disableCliChecks = false;

    private static $originalServer;

    public static function protocol()
    {
        return Server::get('SERVER_PROTOCOL');
    }

    public static function clientHost()
    {
        return Server::get('HTTP_HOST');
    }

    public static function serverHost()
    {
        return Server::get('SERVER_NAME');
    }

    public static function serverAdmin()
    {
        return Server::get('SERVER_ADMIN');
    }

    public static function secured()
    {
        return Server::get('HTTPS');
    }

    public static function isSecured()
    {
        return static::secured() == 'on';
    }

    public static function with()
    {
        return Server::get('HTTP_X_REQUESTED_WITH');
    }

    public static function port()
    {
        return Server::get('SERVER_PORT');
    }

    public static function agent()
    {
        return Server::get('HTTP_USER_AGENT');
    }

    public static function ip()
    {
        return Server::get('REMOTE_ADDR');
    }

    public static function uri()
    {
        return Server::get('REQUEST_URI');
    }

    public static function method()
    {
        return Server::get('REQUEST_METHOD');
    }

    public static function baseUri()
    {
        if (!self::$disableCliChecks and php_sapi_name() === 'cli') {
            return null;
        }

        $scriptName = Server::scriptName();

        $baseUri = pathinfo($scriptName, PATHINFO_DIRNAME);

        if (static::$DS != '/') {
            $baseUri = str_replace(static::$DS, '/', $baseUri);
        }

        if ($baseUri[0] == '.') {
            $baseUri[0] = '/';
        }

        if ($baseUri[0] != '/') {
            $baseUri = '/' . $baseUri;
        }

        if ($baseUri == '/') {
            $baseUri = null;
        }

        return $baseUri;
    }

    public static function uriPath()
    {
        list($path) = explode('?', static::uri(), 2);

        return $path;
    }

    public static function uriQuery()
    {
        list($path, $query) = array_pad(explode('?', static::uri(), 2), 2, null);

        unset($path);

        return $query;
    }

    public static function relativeUri()
    {
        $uri = static::uri();

        $baseUri = static::baseUri();

        return $baseUri !== '/' ? mb_substr($uri, mb_strlen($baseUri)) : $uri;
    }

    public static function relativeUriPath()
    {
        list($path) = explode('?', static::relativeUri(), 2);

        return $path;
    }

    public static function referrer()
    {
        return Server::get('HTTP_REFERER');
    }

    public static function modifiedSince()
    {
        return Server::get('HTTP_IF_MODIFIED_SINCE');
    }

    public static function match()
    {
        return Server::get('HTTP_IF_NONE_MATCH');
    }

    public static function time()
    {
        return Server::requestTime();
    }

    public static function microTime()
    {
        return Server::requestMicroTime();
    }

    public static function isAjax()
    {
        return static::with() == 'XMLHttpRequest';
    }

    public static function header($header)
    {
        $header = strtoupper($header);

        $header = str_replace('-', '_', $header);

        return Server::get('HTTP_' . $header);
    }

    public static function humanReadableFiles()
    {
        $_FILES = static::humanReadableData($_FILES);

        static::$isHumanReadableFiles = true;

        return $_FILES;
    }

    // $_REQUEST

    public static function has($key = null)
    {
        return func_num_args() ? Arr::has($_REQUEST, $key) : (bool) $_REQUEST;
    }

    public static function hasIndex($index, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::hasIndex($_REQUEST, $index, $delimiter);
    }

    public static function param($key = null, $else = null)
    {
        return func_num_args() ? Arr::get($_REQUEST, $key, $else) : $_REQUEST;
    }

    public static function paramArray($key, $else = null)
    {
        return Arr::getArray($_REQUEST, $key, $else);
    }

    public static function paramIndex($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndex($_REQUEST, $index, $else, $delimiter);
    }

    public static function paramIndexArray($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndexArray($_REQUEST, $index, $else, $delimiter);
    }

    // $_GET

    public static function hasGet($key = null)
    {
        return func_num_args() ? Arr::has($_GET, $key) : (bool) $_GET;
    }

    public static function hasIndexGet($index, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::hasIndex($_GET, $index, $delimiter);
    }

    public static function get($key = null, $else = null)
    {
        return func_num_args() ? Arr::get($_GET, $key, $else) : $_GET;
    }

    public static function getArray($key, $else = null)
    {
        return Arr::getArray($_GET, $key, $else);
    }

    public static function getIndex($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndex($_GET, $index, $else, $delimiter);
    }

    public static function getIndexArray($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndexArray($_GET, $index, $else, $delimiter);
    }

    // $_POST

    public static function hasPost($key = null)
    {
        return func_num_args() ? Arr::has($_POST, $key) : (bool) $_POST;
    }

    public static function hasIndexPost($index, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::hasIndex($_POST, $index, $delimiter);
    }

    public static function post($key = null, $else = null)
    {
        return func_num_args() ? Arr::get($_POST, $key, $else) : $_POST;
    }

    public static function postArray($key, $else = null)
    {
        return Arr::getArray($_POST, $key, $else);
    }

    public static function postIndex($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndex($_POST, $index, $else, $delimiter);
    }

    public static function postIndexArray($index, $else = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        return Arr::getIndexArray($_POST, $index, $else, $delimiter);
    }

    // $_FILES

    public static function hasFile($key = null)
    {
        return func_num_args() ? Arr::has($_FILES, $key) : (bool) $_FILES;
    }

    public static function hasIndexFile($index, $delimiter = Arr::INDEX_DELIMITER)
    {
        if (!static::$isHumanReadableFiles) {
            throw new RequestException('You cannot use indexes for $_FILES if `humanReadableFiles` method is not enabled.');
        }

        return Arr::hasIndex($_FILES, $index, $delimiter);
    }

    public static function file($key = null, $mime = null)
    {
        if (func_num_args()) {
            $file = Arr::get($_FILES, $key);

            if (is_array($key)) {
                return Arr::mapRecursive($file, function ($file) use ($mime) {
                    return static::checkFile($file, $mime);
                }, 1);
            }

            return static::checkFile($file, $mime);
        }

        if (!static::$isHumanReadableFiles) {
            $files = [];

            foreach ($_FILES as $key => $value) {
                if (is_array($value['name'])) {
                    $files[$key] = static::checkFiles($value, $mime);
                } else {
                    $files[$key] = static::checkFile($value, $mime);
                }
            }

            return $files;
        }

        return $_FILES;
    }

    public static function fileArray($key, $mime = null)
    {
        $files = Arr::get($_FILES, $key);

        if (static::$isHumanReadableFiles) {
            if (array_key_exists('name', $files)) {
                $files = [$files];
            }
        } else {
            if (!is_array($files['name'])) {
                $files['name'] = (array) $files['name'];
                $files['type'] = (array) $files['type'];
                $files['size'] = (array) $files['size'];
                $files['tmp_name'] = (array) $files['tmp_name'];
                $files['error'] = (array) $files['error'];
            }
        }

        return static::checkFiles($files, $mime);
    }

    public static function fileIndex($index, $mime = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        if (!static::$isHumanReadableFiles) {
            throw new RequestException('You cannot use indexes for $_FILES if `humanReadableFiles` is disabled.');
        }

        $file = Arr::getIndex($_FILES, $index, null, $delimiter);

        if (is_array($index)) {
            return static::checkFiles($file, $mime);
        }

        return static::checkFile($file, $mime);
    }

    public static function fileIndexArray($index, $mime = null, $delimiter = Arr::INDEX_DELIMITER)
    {
        if (!static::$isHumanReadableFiles) {
            throw new RequestException('You cannot use indexes for $_FILES if `humanReadableFiles` is disabled.');
        }

        $files = Arr::getIndex($_FILES, $index, null, $delimiter);

        if (array_key_exists('name', $files)) {
            $files = [$files];
        }

        return static::checkFiles($files, $mime);
    }

    public static function mockHttpMode()
    {
        self::$disableCliChecks = true;

        self::$originalServer = $_SERVER;

        $_SERVER['SERVER_PROTOCOL'] = 'http';
        $_SERVER['HTTP_HOST'] = 'localhost';
        $_SERVER['SERVER_NAME'] = 'localhost';
        $_SERVER['SERVER_ADMIN'] = get_current_user();
        $_SERVER['SERVER_PORT'] = 80;
        $_SERVER['HTTP_USER_AGENT'] = 'Mozilla';
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
        $_SERVER['REQUEST_URI'] = '/';

        $_SERVER['SCRIPT_NAME'] = '/index.php';

        $_SERVER['HTTP_IF_MODIFIED_SINCE'] = null;
        $_SERVER['HTTP_IF_NONE_MATCH'] = null;
        $_SERVER['HTTP_REFERER'] = null;
        $_SERVER['REQUEST_METHOD'] = 'GET';

        return true;
    }

    public static function restoreHttpMode()
    {
        if (self::$disableCliChecks) {
            self::$disableCliChecks = false;

            $_SERVER = self::$originalServer;
        }
    }

    protected static function checkHumanReadableFiles(array $files, $mime = null)
    {
        foreach ($files as &$file) {
            if (is_array(current($file))) {
                $file = static::checkHumanReadableFiles($file, $mime);
            } else {
                $file = static::checkFile($file, $mime);
            }
        }

        return $files;
    }

    protected static function checkFiles(array $files, $mime = null)
    {
        if (static::$isHumanReadableFiles) {
            return static::checkHumanReadableFiles($files, $mime);
        }

        $names = Arr::packIndexes($files['name'], '&');
        $types = Arr::packIndexes($files['type'], '&');
        $sizes = Arr::packIndexes($files['size'], '&');
        $tmpNames = Arr::packIndexes($files['tmp_name'], '&');
        $errors = Arr::packIndexes($files['error'], '&');

        $indexFiles = [];

        foreach ($names as $index => $name) {
            $indexFiles['name'][$index] = $name;
            $indexFiles['type'][$index] = $types[$index];
            $indexFiles['size'][$index] = $sizes[$index];
            $indexFiles['tmp_name'][$index] = $tmpNames[$index];
            $indexFiles['error'][$index] = $errors[$index];
        }

        foreach ($indexFiles['error'] as $key => $error) {
            static::checkFile([
                'name'     => $indexFiles['name'][$key],
                'type'     => $indexFiles['type'][$key],
                'size'     => $indexFiles['size'][$key],
                'tmp_name' => $indexFiles['tmp_name'][$key],
                'error'    => $indexFiles['error'][$key],
            ], $mime);
        }

        return $files;
    }

    protected static function checkFile(array $file, $mime = null)
    {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new RequestException('File upload error: ' . Request::UPLOAD_ERROR[$file['error']]);
        }

        if (static::$checkFileUpload && !is_uploaded_file($file['tmp_name'])) {
            throw new RequestException('Possible file upload attack.');
        }

        if ($mime = (array) $mime and !in_array($file['type'], $mime)) {
            throw new RequestException('Wrong file type was uploaded. Valid types are: ' . implode(', ', $mime) . '.');
        }

        return $file;
    }

    protected static function humanReadableData($data)
    {
        foreach ($data as &$item) {
            if (is_array(current($item))) {
                $newItem = [];

                foreach ($item as $key => $value) {
                    static::addNewArrayLevel($value, $key);

                    $newItem = array_replace_recursive($newItem, $value);
                }

                $item = $newItem;
            }
        }

        unset($item);

        return $data;
    }

    protected static function addNewArrayLevel(&$array, $key)
    {
        foreach ($array as &$item) {
            if (is_array($item)) {
                static::addNewArrayLevel($item, $key);
            } else {
                $item = [$key => $item];
            }
        }

        unset($item);

        return true;
    }
}


<?php

namespace Addons\Core\Middleware;

use Closure;
use Illuminate\Http\Response;

class NoCache
{
	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		$response = $next($request);

		$response->headers->set('P3P','CP="CAO PSA OUR"');
		if(in_array(strtoupper($request->method()), ['POST', 'PUT', 'DELETE'])){
			//header no cache when post
			foreach([
				'Expires' => '0',
				'Cache-Control' => 'no-store,private, post-check=0, pre-check=0, max-age=0',
				'Pragma' => 'no-cache',
			] as $k => $v)
				$response->headers->set($k, $v);
		}

		return $response;
	}
}


<?php

namespace Zeeml\Algorithms\Formulas;

use NumPHP\Core\NumArray;
use NumPHP\LinAlg\Exception\SingularMatrixException;
use NumPHP\LinAlg\LinAlg;
use Zeeml\Algorithms\Exceptions\AlgorithmNotApplicable;
use Zeeml\Algorithms\Exceptions\MissingResultException;
use Zeeml\Algorithms\Exceptions\WrongUsageException;
use Zeeml\DataSet\DataSet;

class MultipleLinearCoefficients extends Formulas
{
    /**
     * Calculating the coefficients (slopes and intercept) of the dataSet following the formula:
     *
     *    y1 = B0 * 1 + B1 * X11 + B2 * X21 + ...
     *    y2 = B0 * 1 + B1 * X12 + B2 * X22 + ...
     *
     *          [                         [                               [
     *            y1                        1 X11 X21 ...                   B0
     *    So Y =  y2          and     X =   1 X21 X22 ...     and Coeffs =  B1
     *            ...                       1 ...                           B2
     *          ]                         ]                                 ...
     *                                                                    ]
     *   Then
     *
     *        coeffs = ((X'.X)^-1).(X'.Y)
     *
     *
     *  Where X' is the transposed matrix of X
     *  ^-1 is the inverse of matrix X (if the matrix can be inverted)
     *  . (dot) is the multiplication sign for matrices
     *
     * @return FormulasInterface
     * @throws MissingResultException
     * @throws WrongUsageException
     * @throws AlgorithmNotApplicable
     */
    public function calculate(): FormulasInterface
    {
        if (! $this->dataSet instanceof DataSet) {
            throw new WrongUsageException('DataSet was not provided for slope calculus');
        }

        try {
            $dimensions = $this->dataSet->getRawDimensions();
            array_walk(
                $dimensions,
                function(&$row) {
                    array_unshift($row, 1);
                }
            );
            $x = new NumArray($dimensions);
            $y = new NumArray($this->dataSet->getRawOutputs());

            $xTransposed = $x->getTranspose();
            $inverse = LinAlg::inv((clone $xTransposed)->dot($x));
            $xTransposedY = (clone $xTransposed)->dot($y);
            $data = ($inverse->dot($xTransposedY))->getData();

            $this->result = [];
            array_walk_recursive($data, function ($elem) {
                $this->result[] = $elem;
            });
        } catch (SingularMatrixException $e) {
            $this->result = [];
            throw new AlgorithmNotApplicable('Can not use multiple linear regression for the given data');
        }

        return $this;
    }
}


<?php

namespace Skillberto\SonataPageMenuBundle\Site;

use Skillberto\SonataPageMenuBundle\Exception\SiteNotFoundException;
use Sonata\PageBundle\Model\SiteInterface;
use Sonata\PageBundle\Model\SiteManagerInterface;
use Sonata\PageBundle\Site\SiteSelectorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class OptionalSite implements OptionalSiteInterface
{
    protected
        $siteSelectorInterface,
        $siteManagerInterface,
        $requestStack;

    public function __construct(SiteSelectorInterface $siteSelectorInterface, SiteManagerInterface $siteManagerInterface, RequestStack $requestStack)
    {
        $this->siteSelectorInterface = $siteSelectorInterface;
        $this->siteManagerInterface  = $siteManagerInterface;
        $this->requestStack          = $requestStack;
    }

    /**
     * {@inheritdoc}
     */
    public function getChosenSite()
    {
        $currentRequest = $this->requestStack->getCurrentRequest();

        if ($siteId = $currentRequest->get('site')) {
            if ($site = $this->getSiteById($siteId)) {
                return $site;
            }

            throw new SiteNotFoundException(sprintf("Can't find site by %s Site ID.", $siteId));
        }

        return $this->getOriginalSite();
    }

    /**
     * {@inheritdoc}
     */
    public function getOriginalSite()
    {
        if ($site = $this->siteSelectorInterface->retrieve()) {
            return $site;
        }

        $sites = $this->getSites();

        if ($site = $this->getDefaultSite($sites)) {
            return $site;
        }

        if (count($sites) == 1) {
            return $sites[0];
        }

        throw new SiteNotFoundException(sprintf("Can't find any site in the system."));
    }

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

    /**
     * @param  int $siteId
     * @return SiteInterface|null
     */
    protected function getSiteById($siteId)
    {
        return $this->siteManagerInterface->find($siteId);
    }

    /**
     * @return array|null
     */
    protected function getSites()
    {
        return $this->siteManagerInterface->findAll();
    }

    /**
     * @param  SiteInterface[] $sites
     * @return SiteInterface|null
     */
    protected function getDefaultSite(array $sites)
    {
        foreach ($sites as $site) {
            if ($site->getIsDefault()) {
                return $site;
            }
        }

        return null;
    }
}


<?php

namespace Bezhanov\Silex\AliceDataFixtures;

use Doctrine\Common\DataFixtures\Loader as DoctrineLoader;
use Faker\Generator as FakerGenerator;
use Nelmio\Alice\Loader\NativeLoader;

/**
 * @method DoctrineLoader getDoctrineLoader()
 */
class FixturesLoader extends NativeLoader
{
    private $doctrineLoader;

    public function __construct(DoctrineLoader $doctrineLoader = null, FakerGenerator $fakerGenerator = null)
    {
        $this->doctrineLoader = (null === $doctrineLoader) ? $this->getDoctrineLoader() : $doctrineLoader;
        parent::__construct($fakerGenerator);
    }

    /**
     * Scans a given directory for YML files containing fixtures, and loads them.
     *
     * @param string $dir
     */
    public function loadFromDirectory(string $dir)
    {
        if (!is_dir($dir)) {
            throw new \InvalidArgumentException(sprintf('"%s" does not exist', $dir));
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($dir),
            \RecursiveIteratorIterator::LEAVES_ONLY
        );
        $this->loadFromIterator($iterator);
    }

    /**
     * Loads fixture data from a given YML file
     *
     * @param string $fileName
     */
    public function loadFromFile(string $fileName)
    {
        if (!is_readable($fileName)) {
            throw new \InvalidArgumentException(sprintf('"%s" does not exist or is not readable', $fileName));
        }
        $iterator = new \ArrayIterator(array(new \SplFileInfo($fileName)));
        $this->loadFromIterator($iterator);
    }

    /**
     * Load fixtures from YML files contained in iterator.
     *
     * @param \Iterator $iterator Iterator over files from which fixtures should be loaded.
     */
    private function loadFromIterator(\Iterator $iterator)
    {
        /* @var \SplFileInfo[] $iterator */
        foreach ($iterator as $file) {
            if ($file->getFilename() === 'fixtures.yml') {
                $this->addFixture($file->getPathname());
            }
        }
    }

    protected function addFixture(string $fileName)
    {
        $this->doctrineLoader->addFixture(new GenericAliceFixture($this, $fileName));
    }

    public function getFixtures()
    {
        return $this->doctrineLoader->getFixtures();
    }

    protected function createDoctrineLoader(): DoctrineLoader
    {
        return new DoctrineLoader();
    }
}