<?php

namespace ASM\File;

use ASM\Driver;
use ASM\FailedToAcquireLockException;
use ASM\File\SessionFilePath;
use ASM\Serializer;
use ASM\IdGenerator;
use ASM\AsmException;
use ASM\SessionManager;
use ASM\SessionConfig;
use ASM\LostLockException;
use ASM\Session;
use ASM\Serializer\JsonSerializer;

/**
 * Class FileDriver
 * @package ASM\File
 *
 * This uses the modified time
 *
 */
class FileDriver implements Driver
{
    const DATA_FILE = 'data_file';

    const ZOMBIE_FILE = 'zombie_file';

    private $path;

    /**
     * @var Serializer
     */
    private $serializer;

    /**
     * @var IdGenerator
     */
    private $idGenerator;

    /**
     * @param string $path The path to write data and lock files to. This must be a path that
     * supports flock`ing properly i.e. not a NFS path.
     *
     * @param Serializer $serializer
     * @param IdGenerator $idGenerator
     * @throws AsmException
     */
    public function __construct(
        SessionFilePath $path,
        Serializer $serializer = null,
        IdGenerator $idGenerator = null
    ) {
        $this->path = $path->getPath();

        if ($serializer) {
            $this->serializer = $serializer;
        }
        else {
            $this->serializer = new JsonSerializer();
        }

        if ($idGenerator) {
            $this->idGenerator = $idGenerator;
        }
        else {
            $this->idGenerator = new \ASM\IdGenerator\RandomLibIdGenerator();
        }
    }

    /**
     * Open an existing session. Returns either the session data or null if
     * the session could not be found.
     * @param Session $session
     * @param SessionManager $sessionManager
     * @param null $userProfile
     * @return null|string
     */
    public function openSessionByID($sessionId, SessionManager $sessionManager, $userProfile = null)
    {
        $filename = $this->generateFilenameForDataFile($sessionId);
        $fileHandle = @fopen($filename, 'r+');

        if ($fileHandle == false) {
            return null;
        }

        $lockToken = null;
        $lockFileHandle = null;

        if ($sessionManager->getLockMode() == SessionConfig::LOCK_ON_OPEN) {
            $lockFileHandle = $this->acquireLock(
                $sessionId,
                $sessionManager->getSessionConfig()->getLockMilliSeconds(),
                $sessionManager->getSessionConfig()->getMaxLockWaitTimeMilliseconds()
            );
        }

        list($data, $existingProfiles) = $this->read($fileHandle);

        $existingProfiles = $sessionManager->performProfileSecurityCheck(
            $userProfile,
            $existingProfiles
        );

        $fileInfo = new FileInfo($lockFileHandle);

        return new FileSession(
            $sessionId,
            $data,
            $this,
            $sessionManager,
            $existingProfiles,
            $fileInfo,
            true
        );
    }

    /**
     * Create a new session.
     * @param SessionManager $sessionManager
     * @param null $userProfile
     * @throws AsmException
     * @return string The newly created session ID.
     */
    public function createSession(SessionManager $sessionManager, $userProfile = null)
    {
        list($sessionId, $fileHandle) = $this->createNewSessionFile();

        $lockFileHandle = null;
        if ($sessionManager->getLockMode() == SessionConfig::LOCK_ON_OPEN) {
            $lockFileHandle = $this->acquireLock(
                $sessionId,
                $sessionManager->getSessionConfig()->getLockMilliSeconds(),
                $sessionManager->getSessionConfig()->getMaxLockWaitTimeMilliseconds()
            );
        }

        $existingProfiles = [];
        if ($userProfile !== null) {
            $existingProfiles[] = $userProfile;
        }

        $fileInfo = new FileInfo($lockFileHandle);
        $this->save($sessionId, [], $existingProfiles,  $fileInfo);
        // fclose($fileHandle); umm.

        return new FileSession(
            $sessionId,
            [],
            $this,
            $sessionManager,
            $existingProfiles,
            $fileInfo,
            false
        );
    }

    /**
     * Create a new file safely.
     *
     * @return array
     * @throws AsmException
     */
    private function createNewSessionFile()
    {
        for ($count=0 ; $count<10 ; $count++) {
            $sessionId = $this->idGenerator->generateSessionID();
            $filename = $this->generateFilenameForDataFile($sessionId);
            //TODO remove? - the user should create the directory themselves
            $dirname = dirname($filename);
            @mkdir($dirname);
            //This only succeeds if the file doesn't already exist
            $fileHandle = @fopen($filename, 'x+');
            if ($fileHandle != false) {
                return [$sessionId, $fileHandle];
            }
        };

        throw new AsmException(
            "Failed to open a new session file with random name.",
            AsmException::ID_CLASH
        );
    }

    /**
     * Generate a consistent filename for a sessionID
     *
     * @param $sessionID
     * @internal param $type
     * @return string
     */
    private function generateFilenameForDataFile($sessionID)
    {
        return $this->path.'/'.$sessionID.".data";
    }

    /**
     * Generate a consistent filename for a sessionID
     *
     * @param $sessionID
     * @internal param $type
     * @return string
     */
    private function generateFilenameForLockFile($sessionID)
    {
        return $this->path.'/'.$sessionID.".lock";
    }

    /**
     * Saves the data for the sessionID atomically.
     *
     * @param $sessionId
     * @param $data
     * @param $existingProfiles
     * @param FileInfo $fileInfo
     * @return resource
     * @throws AsmException
     * @throws FailedToAcquireLockException
     */
    public function save($sessionId, $data, $existingProfiles, FileInfo $fileInfo)
    {
        $rawData = [];
        $rawData['data'] = $data;
        $rawData['profiles'] = $existingProfiles;

        $dataString = $this->serializer->serialize($rawData);
        $filename = $this->generateFilenameForDataFile($sessionId);

        $tempFilename = tempnam(dirname($filename), basename($filename));
        $writeResult = @file_put_contents($tempFilename, $dataString);
        if ($writeResult === false) {
            throw new AsmException(
                "Failed to write session data.",
                AsmException::IO_ERROR
            );
        }
        $tempLockFileHandle = null;

        if ($fileInfo->lockFileHandle) {
            $this->validateLock($sessionId, $fileInfo);
        }
        else {
            $tempLockFileHandle = $this->acquireLock(
                $sessionId,
                5000,
                1000
            );
        }

        //We have the lock - it's safe to replace the datafile
        $renamed = rename($tempFilename, $filename);

        if ($tempLockFileHandle) {
            fclose($tempLockFileHandle);
        }

        if (!$renamed) {
            throw new AsmException(
                "Failed to save session data during rename of file",
                AsmException::IO_ERROR
            );
        }
    }

    /**
     * @param $sessionID
     * @return mixed
     * @throws AsmException
     */
    function read($fileHandle)
    {
        $dataString = stream_get_contents($fileHandle);
        $rawData = $this->serializer->unserialize($dataString);

        $data = null;
        $existingProfiles = null;
        $lockToken = null;

        if (array_key_exists('data', $rawData)) {
            $data = $rawData['data'];
        }
        if (array_key_exists('profiles', $rawData)) {
            $existingProfiles = $rawData['profiles'];
        }

        return [$data, $existingProfiles];
    }

    /**
     * @param $sessionId
     * @param FileInfo $fileInfo
     * @return bool
     * @throws AsmException
     */
    function validateLock($sessionId, FileInfo $fileInfo)
    {
        $lockFilename = $this->generateFilenameForLockFile($sessionId);
        $originalInode = null;
        $currentInode = null;

        if ($fileInfo->lockFileHandle == null) {
            return false;
        }

        $originalStat = fstat($fileInfo->lockFileHandle);
        if($originalStat && array_key_exists('ino', $originalStat)) {
            $originalInode = $originalStat['ino'];
        }

        $currentStat = @stat($lockFilename);
        if($currentStat && array_key_exists('ino', $currentStat)) {
            $currentInode = $currentStat['ino'];
        }

        if ($currentInode === null) {
            return false;
        }
        else if ($originalInode === null) {
            return false;
        }
        else if ($currentInode !== $originalInode) {
            return false;
        }

        if (array_key_exists('mtime', $currentStat) == false) {
            throw new AsmException(
                "Cannot validate lock mtime is not valid.",
                AsmException::IO_ERROR
            );
        }

        return true;
    }

    /**
     * @param $sessionID
     * @return mixed
     */
    function forceReleaseLockByID($sessionID) {
        $filename = $this->generateFilenameForLockFile($sessionID);
        unlink($filename);
    }

//    /**
//     * @param $sessionID
//     * @return mixed
//     */
//    function findSessionIDFromZombieID($zombieSessionID) {
//        $filename = $this->generateFilename($zombieSessionID, self::ZOMBIE_FILE);
//        $fileContents = @file_get_contents($filename);
//
//        return $fileContents;
//    }

//    /**
//     * @param $dyingSessionID
//     * @param $newSessionID
//     * @param $zombieTimeMilliseconds
//     */
//    function setupZombieID($dyingSessionID, $zombieTimeMilliseconds) {
//        // TODO - this needs to be wrapped in a lock.
//        list($newSessionID, $newFileHandle) = $this->createNewSessionFile();
//
//        fseek($this->fileHandle, 0);
//        stream_copy_to_stream($this->fileHandle, $newFileHandle);
//
//        $zombieFilename = $this->generateFilename($dyingSessionID, self::ZOMBIE_FILE);
//        file_put_contents($zombieFilename, "".$newSessionID."");
//
//        //TODO - rename profile
//
//
//        // Store as temp variable so that $this->fileHandle is always a file
//        // handle to a valid file.
//        $oldFileHandle = $this->fileHandle;
//        $this->fileHandle = $newFileHandle;
//        fclose($oldFileHandle);
//
//        return $newSessionID;
//    }
//
//
//
//    /**
//     * @return mixed
//     */
//    function destroyExpiredSessions() {
//        // TODO: Implement destroyExpiredSessions() method.
//    }

    /**
     * Delete a single session that matches the $sessionID
     * @param $sessionID
     */
    public function deleteSessionByID($sessionID)
    {
        $filename = $this->generateFilenameForDataFile($sessionID);
        unlink($filename);
    }

    /**
     * Acquire a lock for the session
     * @param $fileHandle
     * @param $filename
     * @param $lockTimeMS
     * @param $acquireTimeoutMS
     * @return bool
     * @throws FailedToAcquireLockException
     */
    public function acquireLock($sessionId, $lockTimeMS, $acquireTimeoutMS)
    {
        // Get the time in MS
        $currentTime = microtime(true);
        $giveUpTime = $currentTime + ($acquireTimeoutMS * 0.001);

        $lockFilename = $this->generateFilenameForLockFile($sessionId);

        do {
            //Re-open the lock file every loop, to prevent issues where another
            //process deletes it.
            $fileHandle = fopen($lockFilename, 'c+');
            //'c+' means "Open the file for writing only. If the file does not exist,
            // it is created. If it exists, it is neither truncated (as opposed to 'w'),
            // nor the call to this function fails (as is the case with 'x').
            $locked = flock($fileHandle, LOCK_EX|LOCK_NB);
            if ($locked) {
                //$touchTime = time() + intval(ceil($lockTimeMS / 1000));
                $expireTime = microtime(true) + ($lockTimeMS * 0.0001);
                file_put_contents(
                    $lockFilename,
                    sprintf("%f", $expireTime)
                );
                //touch($lockFilename, $touchTime);
                return $fileHandle;
            }

            //We did not acquire a lock - check to see if the lock has expired
            $contents = file_get_contents($lockFilename);
            $existingExpireTime = floatval($contents);
            // TODO - we could do a basic sanity test on the lock data
            // however, what we be the correct action to take?
//            if ($existingExpireTime < 1447040641 ||
//                $existingExpireTime > 2551578313) {
//                //lock contents are rubbish
//                //TODO - decide what to do.
//            }

            if (microtime(true) > $existingExpireTime) {
                unlink($lockFilename);
            }
            else {
                // sleep 1ms to avoid churning CPU
                usleep(1000);
            }
        } while($giveUpTime > microtime(true));

        throw new FailedToAcquireLockException(
            "FileDriver failed to acquire lock."
        );
    }

    /**
     * @param $sessionId
     * @param $milliseconds
     * @return mixed
     */
    public function renewLock($sessionId, $milliseconds, FileInfo $fileInfo) {

        //Write the new expire time to the existing lock handle

        if (!$this->validateLock($sessionId, $fileInfo)) {
            throw new LostLockException("Cannot renew lock, it has already been released.");
        }

        //$this->acquireLock($sessionId, $lockTimeMS, $acquireTimeoutMS)

        // TODO - there is a race condition here between
        $filename = $this->generateFilenameForDataFile($sessionId);
        $time = time() + intval((ceil($milliseconds / 1000)));
        touch($filename,  $time);
    }

    /**
     * @param FileInfo $fileInfo
     * @return mixed
     */
    public function releaseLock(FileInfo $fileInfo)
    {
        $lockFilehandle = $fileInfo->lockFileHandle;
        $fileInfo->lockFileHandle = null;
        if ($lockFilehandle != null) {
            fclose($lockFilehandle);
        }
    }

    /**
     * @param FileInfo $fileInfo
     */
    public function close(FileInfo $fileInfo)
    {
        @fclose($fileInfo->lockFileHandle);
        $fileInfo->lockFileHandle = null;
    }
}


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

use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RequestStack;
use Tardigrades\SectionField\Form\FormInterface;
use Tardigrades\SectionField\Service\CreateSectionInterface;
use Tardigrades\SectionField\Service\SectionManagerInterface;
use Tardigrades\SectionField\ValueObject\SectionFormOptions;
use Twig_Extension;
use Twig_Function;

class SectionFormTwigExtension extends Twig_Extension
{
    /** @var SectionManagerInterface */
    private $sectionManager;

    /** @var FormInterface */
    private $form;

    /** @var CreateSectionInterface */
    private $createSection;

    /** @var RequestStack */
    private $requestStack;

    public function __construct(
        SectionManagerInterface $sectionManager,
        CreateSectionInterface $createSection,
        FormInterface $form,
        RequestStack $requestStack
    ) {
        $this->sectionManager = $sectionManager;
        $this->createSection = $createSection;
        $this->form = $form;
        $this->requestStack = $requestStack;
    }

    public function getFunctions(): array
    {
        return array(
            new Twig_Function(
                'sectionForm',
                array($this, 'sectionForm')
            )
        );
    }

    /**
     * This method returns a form to be rendered with Twig.
     * It will return a view, validate and save the form data.
     *
     * @param string $forHandle
     * @param array $sectionFormOptions
     * @return FormView
     */
    public function sectionForm(
        string $forHandle,
        array $sectionFormOptions = []
    ): FormView {

        $sectionFormOptions = SectionFormOptions::fromArray($sectionFormOptions);

        $form = $this->form->buildFormForSection(
            $forHandle,
            $this->requestStack,
            $sectionFormOptions
        );
        $form->handleRequest();

        if ($form->isSubmitted() &&
            $form->isValid()
        ) {
            $data = $form->getData();
            $this->createSection->save($data);

            try {
                $redirect = $sectionFormOptions->getRedirect();
            } catch (\Exception $exception) {
                $redirect = '/';
            }
            header('Location: ' . $redirect);
            exit;
        }

        return $form->createView();
    }
}


<?php

/*
 * This file is part of the FSi Component package.
 *
 * (c) Lukasz Cybula <lukasz@fsi.pl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FSi\Component\Reflection;

class ReflectionProperty extends \ReflectionProperty
{
    protected static $properties = array();

    /**
     * Constructs a new ReflectionProperty object.
     *
     * @param string|object $class
     * @param string $name
     * @throws ReflectionException
     * @return ReflectionProperty
     */
    final public function __construct($class, $name)
    {
        $bt = debug_backtrace();
        if (!isset($bt[1]['class']) || ($bt[1]['class'] !== __CLASS__))
            throw new ReflectionException('ReflectionClass\' constructor cannot be called from outside the class');
        parent::__construct($class, $name);
    }

    /**
     * Constructs a new ReflectionProperty object from property and class name.
     * If object already exists in cache it will taken from there instead of creating
     * new object
     *
     * @param string|object $class
     * @param string $property
     * @return ReflectionProperty
     */
    public static function factory($class, $property = null)
    {
        if (is_object($class))
            $class = get_class($class);
        $class = (string)$class;
        if (!isset(self::$properties[$class])) {
            $classReflection = new \ReflectionClass($class);
            $properties = $classReflection->getProperties();
            self::$properties[$class] = array();
            foreach ($properties as $propertyReflection) {
                if ($propertyReflection->class != $class) {
                    self::$properties[$class][$propertyReflection->name] = self::factory($propertyReflection->class, $propertyReflection->name);
                } else {
                    self::$properties[$class][$propertyReflection->name] = new self($propertyReflection->class, $propertyReflection->name);
                    self::$properties[$class][$propertyReflection->name]->setAccessible(true);
                }
            }
        }
        if (isset($property)) {
            if (!isset(self::$properties[$class][$property])) {
                self::$properties[$class][$property] = new self($class, $property);
                self::$properties[$class][$property]->setAccessible(true);
            }
            return self::$properties[$class][$property];
        } else
            return array_values(self::$properties[$class]);
    }

    /**
     * Get class ReflectionObject using ReflectionClass::factory method.
     *
     * @return ReflectionClass
     */
    public function getDeclaringClass()
    {
        return ReflectionClass::factory($this->class);
    }
}


<?php

namespace keltanas\Bundle\YandexMetrikaBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        // Description metrika params
        // @link http://help.yandex.ru/metrika/objects/creating-object.xml

        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('keltanas_yandex_metrika');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.
        $rootNode
            ->children()
                ->scalarNode('number')->isRequired()->end()
                ->booleanNode('debug')->defaultValue(false)->end()
                ->arrayNode('params')
                    ->prototype('scalar')
                    ->end()
                ->end()
                ->scalarNode('accurateTrackBounce')->defaultValue(false)->end()
                ->booleanNode('clickmap')->defaultFalse()->end()
                ->booleanNode('defer')->defaultFalse()->end()
                ->booleanNode('enableAll')->defaultFalse()->end()
                ->booleanNode('onlyHttps')->defaultFalse()->end()
                ->booleanNode('trackHash')->defaultFalse()->end()
                ->booleanNode('trackLinks')->defaultFalse()->end()
                ->integerNode('type')->defaultValue(0)->end()
                ->scalarNode('ut')->defaultValue(null)->end()
                ->booleanNode('webvisor')->defaultFalse()->end()
            ->end()
        ->end();

        return $treeBuilder;
    }
}


<?php
/**
 * Inventory
 *
 * PHP Version 5.3 -> 5.4
 * SugarCRM Versions 6.5 - 7.6
 *
 * @author Rémi Sauvat
 * @copyright 2005-2015 iNet Process
 *
 * @package inetprocess/inventory
 *
 * @license GNU General Public License v2.0
 *
 * @link http://www.inetprocess.com
 */

namespace Inet\Inventory\Facter;

use Symfony\Component\Process\Process;

class CommandProvider implements FacterInterface
{
    protected $cmd;
    protected $as_json;

    public function __construct($command, $as_json = false)
    {
        $this->cmd = $command;
        $this->as_json = $as_json;
    }

    /**
     * Return the facts generated from the command.
     * If as_json is true, the command must produce valid json.
     */
    public function getFacts()
    {
        try {
            $output = $this->runCommand($this->cmd);
            if ($this->as_json) {
                $json = json_decode($output, true);
                if (is_null($json)) {
                    return array();
                }

                return $json;
            } else {
                return $this->parseFacts($output);
            }
        } catch (\Exception $e) {
            return array();
        }
    }

    /**
     * Run the command.
     *
     * @param $cmd Command line to run
     *
     * @return oupout of command
     */
    protected function runCommand($cmd)
    {
        $process = new Process($cmd);
        $process->mustRun();

        return $process->getOutput();
    }

    /**
     * Parse flat results in the form
     * fact1=value1
     * fact2=value2
     */
    protected function parseFacts($facts_string)
    {
        $facts = array();
        foreach (explode(PHP_EOL, $facts_string) as $line) {
            if (empty($line)) {
                continue;
            }
            list($key, $value) = explode('=', $line, 2);
            $facts[$key] = $value;
        }

        return $facts;
    }
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\DependencyInjection\Compiler;

use Imatic\Bundle\ViewBundle\Templating\Helper\Condition\ExpressionLanguage;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Registers the expression language providers.
 */
class AddExpressionLanguageProvidersPass implements CompilerPassInterface
{
    public const EXPRESSION_LANGUAGE_PROVIDER_TAG = 'imatic_view.expression_language_provider';

    /**
     * @param ContainerBuilder $container
     *
     * @SuppressWarnings(PHPMD.UnusedLocalVariables)
     */
    public function process(ContainerBuilder $container)
    {
        $definition = $container->findDefinition(ExpressionLanguage::class);

        foreach ($container->findTaggedServiceIds(self::EXPRESSION_LANGUAGE_PROVIDER_TAG) as $id => $attributes) {
            $definition->addMethodCall('registerProvider', [new Reference($id)]);
        }
    }
}


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

namespace FDevs\Photatoes;

class Meta implements \Serializable
{
    /**
     * @var int
     */
    private $width = 0;

    /**
     * @var int
     */
    private $height = 0;

    /**
     * @var string
     */
    private $href = '';

    /**
     * @var string
     */
    private $size = '';

    /**
     * init
     *
     * @param string $href
     * @param int    $height
     * @param int    $width
     */
    public function __construct($href, $width = 0, $height = 0)
    {
        $this->height = $height;
        $this->href = $href;
        $this->width = $width;
        $this->setSize(ImageSize::getSize($width, $height));
    }

    /**
     * to String
     *
     * @return string
     */
    public function __toString()
    {
        return $this->href;
    }

    /**
     * {@inheritDoc}
     */
    public function serialize()
    {
        $data = array(
            $this->href,
            $this->width,
            $this->height,
            $this->size
        );

        return serialize($data);
    }

    /**
     * {@inheritDoc}
     */
    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        list(
            $this->href,
            $this->width,
            $this->height,
            $this->size
            ) = $data;
    }

    /**
     * set Size
     *
     * @param string $size
     *
     * @return $this
     */
    public function setSize($size)
    {
        if ($size = ImageSize::get($size)) {
            $this->size = $size;
        }

        return $this;
    }

    /**
     * get Size
     *
     * @return string
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * @param int $height
     *
     * @return $this
     */
    public function setHeight($height)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * @return int
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * @param string $href
     *
     * @return $this
     */
    public function setHref($href)
    {
        $this->href = $href;

        return $this;
    }

    /**
     * set Href
     *
     * @return string
     */
    public function getHref()
    {
        return $this->href;
    }

    /**
     * set Width
     *
     * @param int $width
     *
     * @return $this
     */
    public function setWidth($width)
    {
        $this->width = $width;

        return $this;
    }

    /**
     * get Width
     *
     * @return int
     */
    public function getWidth()
    {
        return $this->width;
    }
}


<?php

namespace Anax\DatabaseActiveRecord;

use Anax\DatabaseActiveRecord\Exception\ActiveRecordException;
use Anax\DatabaseQueryBuilder\DatabaseQueryBuilder;

/**
 * An implementation of the Active Record pattern to be used as
 * base class for database driven models.
 */
class ActiveRecordModel
{
    /**
     * @var DatabaseQueryBuilder $db the object for persistent
     *                               storage.
     */
    protected $db = null;

    /**
     * @var string $tableName name of the database table.
     */
    protected $tableName = null;

    /**
     * @var string $tableIdColumn name of the id column in the database table.
     */
    protected $tableIdColumn = "id";

    /**
     * Set the database object to use for accessing storage.
     *
     * @param DatabaseQueryBuilder $db as database access object.
     *
     * @return void
     */
    public function setDb(DatabaseQueryBuilder $db)
    {
        $this->db = $db;
    }

    /**
     * Check if database is injected or throw an exception.
     *
     * @throws ActiveRecordException when database is not set.
     *
     * @return void
     */
    protected function checkDb()
    {
        if (!$this->db) {
            throw new ActiveRecordException("Missing \$db, did you forget to inject/set is?");
        }
    }

    /**
     * Get essential object properties.
     *
     * @return array with object properties.
     */
    protected function getProperties()
    {
        $properties = get_object_vars($this);
        unset(
            $properties['tableName'],
            $properties['db'],
            $properties['di'],
            $properties['tableIdColumn']
        );
        return $properties;
    }

    /**
     * Find and return first object found by search criteria and use
     * its data to populate this instance.
     *
     * @param string $column to use in where statement.
     * @param mixed  $value  to use in where statement.
     *
     * @return this
     */
    public function find($column, $value)
    {
        return $this->findWhere("$column = ?", $value);
    }

    /**
     * Find and return first object by its tableIdColumn and use
     * its data to populate this instance.
     *
     * @param integer $id to find or use $this->{$this->tableIdColumn}
     *                    as default.
     *
     * @return this
     */
    public function findById($id = null)
    {
        $id = $id ?: $this->{$this->tableIdColumn};
        return $this->findWhere("{$this->tableIdColumn} = ?", $id);
    }

    /**
     * Find and return first object found by search criteria and use
     * its data to populate this instance.
     *
     * The search criteria `$where` of can be set up like this:
     *  `id = ?`
     *  `id1 = ? and id2 = ?`
     *
     * The `$value` can be a single value or an array of values.
     *
     * @param string $where to use in where statement.
     * @param mixed  $value to use in where statement.
     *
     * @return this
     */
    public function findWhere($where, $value)
    {
        $this->checkDb();
        $params = is_array($value) ? $value : [$value];
        $this->db->connect()
                 ->select()
                 ->from($this ->tableName)
                 ->where($where)
                 ->execute($params)
                 ->fetchInto($this);
    }

    /**
     * Find and return all.
     *
     * @return array of object of this class
     */
    public function findAll()
    {
        $this->checkDb();
        return $this->db->connect()
                        ->select()
                        ->from($this->tableName)
                        ->execute()
                        ->fetchAllClass(get_class($this));
    }

    /**
     * Find and return all matching the search criteria.
     *
     * The search criteria `$where` of can be set up like this:
     *  `id = ?`
     *  `id IN [?, ?]`
     *
     * The `$value` can be a single value or an array of values.
     *
     * @param string $where to use in where statement.
     * @param mixed  $value to use in where statement.
     *
     * @return array of object of this class
     */
    public function findAllWhere($where, $value)
    {
        $this->checkDb();
        $params = is_array($value) ? $value : [$value];
        return $this->db->connect()
                        ->select()
                        ->from($this->tableName)
                        ->where($where)
                        ->execute($params)
                        ->fetchAllClass(get_class($this));
    }

    /**
     * Save current object/row, insert if id is missing and do an
     * update if the id exists.
     *
     * @return void
     */
    public function save()
    {
        if (isset($this->{$this->tableIdColumn})) {
            return $this->update();
        }

        return $this->create();
    }

    /**
     * Save/update current object/row using a custom where-statement.
     *
     * The criteria `$where` of can be set up like this:
     *  `id = ?`
     *  `id1 = ? AND id2 = ?`
     *
     * The `$value` can be a single value or an array of values.
     *
     * @param string $where to use in where statement.
     * @param mixed  $value to use in where statement.
     *
     * @return void
     */
    public function saveWhere($where, $value)
    {
        return $this->updateWhere($where, $value);
    }

    /**
     * Create new row.
     *
     * @return void
     */
    protected function create()
    {
        $this->checkDb();
        $properties = $this->getProperties();
        unset($properties[$this->tableIdColumn]);
        $columns = array_keys($properties);
        $values  = array_values($properties);

        $this->db->connect()
                 ->insert($this->tableName, $columns)
                 ->execute($values);

        $this->{$this->tableIdColumn} = $this->db->lastInsertId();
    }

    /**
     * Update row using $tableIdColumn as where.
     *
     * @return void
     */
    protected function update()
    {
        $this->checkDb();
        $properties = $this->getProperties();
        unset($properties[$this->tableIdColumn]);
        $columns = array_keys($properties);
        $values  = array_values($properties);
        $values[] = $this->{$this->tableIdColumn};

        $this->db->connect()
                 ->update($this->tableName, $columns)
                 ->where("{$this->tableIdColumn} = ?")
                 ->execute($values);
    }

    /**
     * Update row using a custom where-statement.
     *
     * The criteria `$where` of can be set up like this:
     *  `id = ?`
     *  `id1 = ? AND id2 = ?`
     *  `id IN (?, ?)`
     *
     * The `$value` can be a single value or an array of values.
     *
     * @param string $where to use in where statement.
     * @param mixed  $value to use in where statement.
     *
     * @return void
     */
    protected function updateWhere($where, $value)
    {
        $this->checkDb();
        $properties = $this->getProperties();
        $columns = array_keys($properties);
        $values  = array_values($properties);
        $values1 = is_array($value)
            ? $value
            : [$value];
        $values = array_merge($values, $values1);

        $this->db->connect()
                 ->update($this->tableName, $columns)
                 ->where($where)
                 ->execute($values);
    }

    /**
     * Update row using $tableIdColumn as where and clear value of
     * `$tableIdColumn`.
     *
     * @param integer $id to delete or use $this->{$this->tableIdColumn}
     *                    as default.
     *
     * @return void
     */
    public function delete($id = null)
    {
        $this->checkDb();
        $id = $id ?: $this->{$this->tableIdColumn};

        $this->db->connect()
                 ->deleteFrom($this->tableName)
                 ->where("{$this->tableIdColumn} = ?")
                 ->execute([$id]);

        $this->{$this->tableIdColumn} = null;
    }

    /**
     * Delete row using a custom where-statement and leave value of
     * `$tableIdColumn` as it is.
     *
     * The criteria `$where` of can be set up like this:
     *  `id = ?`
     *  `id1 = ? AND id2 = ?`
     *  `id IN (?, ?)`
     *
     * The `$value` can be a single value or an array of values.
     *
     * @param string $where to use in where statement.
     * @param mixed  $value to use in where statement.
     *
     * @return void
     */
    public function deleteWhere($where, $value)
    {
        $this->checkDb();
        $values = is_array($value) ? $value : [$value];

        $this->db->connect()
                 ->deleteFrom($this->tableName)
                 ->where($where)
                 ->execute($values);
    }
}


<?php

namespace Fracture\Routing;

class Pattern
{

    // default pattern fragment for matching URL query segment
    const STRVAL = '[^/\\\\.,;?\n]+';

    // pattern of the route notation element
    const REGKEY = '/(\:([a-zA-Z]+))/';

    // pattern fragment to match Pattern::STRVAL in a string
    const REGVAL = '[^/\\\\\\\\.,;?\n]+';

    protected $notation;

    protected $conditions;

    protected $expression;

    public function __construct($notation, array $conditions = [])
    {
        $this->notation = $notation;
        $this->conditions = $conditions;
    }

    public function prepare()
    {
        $notation = $this->cleanNotation($this->notation);
        $expression = $this->parseNotation($notation);

        if (count($this->conditions)) {
            $expression = $this->applyConditions($expression, $this->conditions);
        }

        $this->expression = "#^$expression$#";
    }

    protected function cleanNotation($notation)
    {
        if (strlen($notation) === 0) {
            return $notation;
        }

        return $this->addSlash($notation);
    }

    /**
     * Method ensures that all non-empty route notations expect '/' as first symbol
     */
    protected function addSlash($notation)
    {
        $notation = trim($notation, '/');
        $offset = strspn($notation, '[');

        if ($offset === 0) {
            return '/' . $notation;
        }

        if (substr($notation, $offset, 1) !== '/') {
            $notation = substr($notation, 0, $offset) . '/' . substr($notation, $offset);
        }

        return $notation;
    }

    /**
     * Turns route notation in a regular expression
     */
    protected function parseNotation($notation)
    {
        $out = str_replace(['[', ']'], ['(?:', ')?'], $notation);

        $enhancement = '(?P<\2>' . self::REGVAL . ')';
        $out = preg_replace(self::REGKEY, $enhancement, $out);

        return $out;
    }

    /**
     * Inserts custom patterns in the existing regular expression
     */
    protected function applyConditions($expression, $conditions)
    {
        $search = $replace = [];

        foreach ($conditions as $key => $value) {
            $search[]  = "<$key>" . self::STRVAL;
            $replace[] = "<$key>$value";
        }

        return str_replace($search, $replace, $expression);
    }

    public function getExpression()
    {
        return $this->expression;
    }
}


<?php

namespace Zeeml\Algorithms\Formulas;

use Zeeml\Algorithms\Exceptions\WrongUsageException;
use Zeeml\DataSet\DataSet;

class Mean extends Formulas
{
    /**
     * calculate the mean of the dataSet
     * @return FormulasInterface
     * @throws WrongUsageException
     */
    public function calculate(): FormulasInterface
    {
        if (! $this->dataSet instanceof DataSet) {
            throw new WrongUsageException('DataSet was not provided for mean calculus');
        }

        $dataSetSize = $this->dataSet->getSize();
        $this->result = [];

        foreach ($this->dataSet as $instance) {
            foreach ($instance->getDimensions() as $index => $dimension) {
                $this->result[0][$index] = $this->result[0][$index] ?? 0;
                $this->result[0][$index] += $dimension / $dataSetSize;
            }
            foreach ($instance->getOutputs() as $index => $output) {
                $this->result[1][$index] = $this->result[1][$index] ?? 0;
                $this->result[1][$index] += $output / $dataSetSize;
            }
        }

        return $this;
    }
}


<?php
/**
 * PX Commands "autoindex"
 */
namespace picklesFramework2\processors\autoindex;

/**
 * PX Commands "autoindex"
 */
class autoindex{

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

	/**
	 * 機能別に値を記憶する領域
	 */
	private $func_data_memos = '\\<\\!\\-\\-\\s*autoindex\\s*\\-\\-\\>';

	/**
	 * extensions function
	 * @param object $px Picklesオブジェクト
	 */
	public static function exec( $px ){
		$autoindex = new self( $px );

		//  autoindex
		if( strlen( $autoindex->func_data_memos ) ){
			$px->bowl()->each( array($autoindex, 'apply_autoindex') );
		}

		return true;
	}

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 */
	public function __construct( $px ){
		$this->px = $px;
	}

	/**
	 * ページ内の目次をソースに反映する。
	 *
	 * マーク文字列 `<!-- autoindex -->` を、自動生成した目次に置き換えます。
	 * 目次は、`<hx>` タグを検出し、自動的に生成されます。
	 *
	 * マーク文字列が検出されない場合は、何も行わず処理をスキップします。
	 *
	 * @param string $content 予告状態の コンテンツ HTMLソース
	 *
	 * @return string 目次が反映されたHTMLソース
	 */
	public function apply_autoindex( $content ){
		if( !preg_match( '/'.$this->func_data_memos.'/s', $content ) ){
			// アンカーリンクが使われてなかったら、処理しない。
			return $content;
		}

		$tmp_cont = $content;
		$content = '';
		$index = array();
		$indexCounter = array();
		$i = 0;
		while( 1 ){
			set_time_limit(60*30);
			if( !preg_match( '/^(.*?)(<\!\-\-(?:.*?)\-\->|


<?php
/**
 * Project seo.
 * Created by PhpStorm.
 * User: 713uk13m <dev@nguyenanhung.com>
 * Date: 11/6/18
 * Time: 16:03
 */

namespace nguyenanhung\SEO\Social;

use nguyenanhung\SEO\ProjectInterface;
use nguyenanhung\SEO\Version;

/**
 * Class GooglePlus
 *
 * @package   nguyenanhung\SEO\Social
 * @author    713uk13m <dev@nguyenanhung.com>
 * @copyright 713uk13m <dev@nguyenanhung.com>
 */
class GooglePlus implements ProjectInterface, GooglePlusInterface
{
    use Version, SocialTrait;
    const SHARE_URI = 'https://plus.google.com/share';
    /** @var string Link dùng để nhúng share trên Google+ */
    private $link;

    /**
     * ShareLink constructor.
     */
    public function __construct()
    {
    }

    /**
     * Function createShareLink
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 16:12
     *
     * @param string $url
     *
     * @return $this
     */
    public function createShareLink($url = '')
    {
        $params     = array(
            'url' => $url . '?utm_source=google%2B&utm_medium=link_share&utm_campaign=google_plus_share',
        );
        $this->link = self::SHARE_URI . '?' . http_build_query($params);

        return $this;
    }
}


<?php

declare(strict_types=1);

namespace ManoManoTech\CorrelationIdHTTPlug;

use Http\Client\Common\Plugin;
use Http\Client\Common\PluginClient;
use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use ManoManoTech\CorrelationId\CorrelationEntryNameInterface;
use ManoManoTech\CorrelationId\CorrelationIdContainerInterface;

final class HttpClientFactory
{
    /** @var Plugin[] */
    private $plugins = [];

    public function __construct(
        CorrelationIdContainerInterface $requestIdentifier,
        CorrelationEntryNameInterface $correlationEntryName = null
    ) {
        $this->addPlugin(new CorrelationIdHTTPlug($requestIdentifier, $correlationEntryName));
    }

    public function addPlugin(Plugin $plugin): void
    {
        $this->plugins[] = $plugin;
    }

    /** Build the HTTP client to talk to the API. */
    public function create(HttpClient $client = null): PluginClient
    {
        return new PluginClient($client ?? HttpClientDiscovery::find(), $this->plugins);
    }
}


<?php

namespace Addons\Core\Http\Response;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\BinaryFileResponse as BaseBinaryFileResponse;

class BinaryFileResponse extends BaseBinaryFileResponse {

	/**
	 * Automatically sets the ETag header according to the checksum of the file.
	 */
	public function setAutoEtag()
	{
		$this->setEtag(md5(serialize(fileinfo($this->file->getPathname()))));
		return $this;
	}

	/**
	 * Sets the file to stream.
	 *
	 * @param \SplFileInfo|string $file               The file to stream
	 * @param string              $contentDisposition
	 * @param bool                $autoEtag
	 * @param bool                $autoLastModified
	 *
	 * @return BinaryFileResponse
	 *
	 * @throws FileException
	 */
	public function setFile($file, $contentDisposition = null, $etag = false, $lastModified = true)
	{
		if (!$file instanceof File) {
			if ($file instanceof \SplFileInfo) {
				$file = new File($file->getPathname());
			} else {
				$file = new File((string) $file);
			}
		}

		if (!$file->isReadable()) {
			throw new FileException('File must be readable.');
		}

		$this->file = $file;

		if ($etag === true)
			$this->setAutoEtag();
		elseif (!empty($etag))
			$this->setEtag($etag);

		if ($lastModified === true)
			$this->setAutoLastModified();
		elseif (!empty($lastModified))
		{
			is_numeric($lastModified) && $lastModified = '@'.$lastModified;
			$this->setLastModified(new \DateTime($lastModified));
		}

		if ($contentDisposition)
			$this->setContentDisposition($contentDisposition);

		return $this;
	}

	/**
	 * {@inheritdoc}
	 */
	public function prepare(Request $request)
	{

		parent::prepare($request);
		$lastModified = $this->getLastModified();

		if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $this->getEtag())
		{
			$this->setStatusCode(304);
			//此时必须退出，不然因为etag等头会触发chorme pending的BUG
			abort(304, '', ['Last-Modified' => $lastModified instanceof \DateTime ? $lastModified->format('D, d M Y H:i:s').' GMT' : $lastModified]);
			$this->maxlen = 0;
		}
		else if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
		{
			if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= ($lastModified instanceof \DateTime ? $lastModified->getTimeStamp() : $lastModified))
			{
				$this->setStatusCode(304);
				abort(304, '' , ['Last-Modified' => $lastModified instanceof \DateTime ? $lastModified->format('D, d M Y H:i:s').' GMT' : $lastModified]);
				$this->maxlen = 0;
			}
		}
		else
		{
			switch (substr($_SERVER['SERVER_SOFTWARE'], 0, (int)strpos($_SERVER['SERVER_SOFTWARE'],'/'))) {
				case 'nginx':
					$path = str_replace(['/./', '//'], ['/', '/'], rtrim(config('session.path'), '\\/').'/'.relative_path($this->file->getPathname(), base_path()));
					$this->headers->set('X-Accel-Redirect', $path);
					$this->headers->set('X-Accel-Buffering', 'no');
					//$this->headers->set('X-Accel-Limit-Rate', '102400'); //速度限制 Byte/s
					//$this->headers('Accept-Ranges', 'none');//单线程 限制多线程
					$this->maxlen = 0;
					break;
				case 'Apache':
					if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules()))
					{
						$this->headers->set('X-Sendfile', $this->file->getPathname());
						$this->maxlen = 0;
					}
					break;
				case 'squid':
					$this->headers->set('X-Accelerator-Vary', $this->file->getPathname());
					$this->maxlen = 0;
					break;
				case 'lighttpd':
					$this->headers->set('X-LIGHTTPD-send-file', $this->file->getPathname());
					$this->maxlen = 0;
					break;
			}

		}
		return $this;
	}
}


<?php
/**
 * Project seo.
 * Created by PhpStorm.
 * User: 713uk13m <dev@nguyenanhung.com>
 * Date: 11/6/18
 * Time: 14:38
 */

namespace nguyenanhung\SEO\Social;

use nguyenanhung\SEO\ProjectInterface;
use nguyenanhung\SEO\Utils;
use nguyenanhung\SEO\Version;

/**
 * Class Facebook
 *
 * @package   nguyenanhung\SEO\Social
 * @author    713uk13m <dev@nguyenanhung.com>
 * @copyright 713uk13m <dev@nguyenanhung.com>
 */
class Facebook implements ProjectInterface, FacebookInterface
{
    use Version, SocialTrait;
    const SHARE_URI = 'https://www.facebook.com/dialog/share';
    const GRAPH_URI = 'https://graph.facebook.com/';
    /** @var string Facebook App ID */
    private $appId;
    /** @var string List Admin ID, mỗi ID cách nhau 1 dấu , */
    private $adminId;
    /** @var string Link chuyển hướng sau khi share link */
    private $redirectUrl;
    /** @var string Link dùng để nhúng share trên facebook */
    private $link;
    /** @var null|object Object chứa thông tin graph content */
    private $graphShare;

    /**
     * Facebook constructor.
     */
    public function __construct()
    {
    }

    /**
     * Function setAppId
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:43
     *
     * @param string $appId
     *
     * @return $this
     */
    public function setAppId($appId = '')
    {
        $this->appId = $appId;

        return $this;
    }

    /**
     * Function getAppId
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:44
     *
     * @return string
     */
    public function getAppId()
    {
        return $this->appId;
    }

    /**
     * Function setAdminId
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:46
     *
     * @param string $adminId
     *
     * @return $this
     */
    public function setAdminId($adminId = '')
    {
        $this->adminId = $adminId;

        return $this;
    }

    /**
     * Function getAdminId
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:46
     *
     * @return string
     */
    public function getAdminId()
    {
        return $this->adminId;
    }

    /**
     * Function setRedirectUrl
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:53
     *
     * @param string $redirectUrl
     *
     * @return $this
     */
    public function setRedirectUrl($redirectUrl = '')
    {
        $this->redirectUrl = $redirectUrl;

        return $this;
    }

    /**
     * Function getRedirectUrl
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:54
     *
     * @return string
     */
    public function getRedirectUrl()
    {
        return $this->redirectUrl;
    }

    /**
     * Function createShareLink
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 14:58
     *
     * @param string $url
     * @param string $caption
     *
     * @return $this
     */
    public function createShareLink($url = '', $caption = '')
    {
        if (empty($caption) && !empty($this->redirectUrl)) {
            $parseUrl = parse_url($this->redirectUrl);
            $caption  = $parseUrl['host'];
        }
        $params     = array(
            'app_id'       => $this->appId,
            'caption'      => $caption,
            'href'         => $url . '?utm_source=facebook&utm_medium=link_share&utm_campaign=facebook_share',
            'redirect_uri' => $this->redirectUrl . '?utm_source=facebook&utm_medium=link_call_back&utm_campaign=facebook_share'
        );
        $this->link = self::SHARE_URI . '?' . http_build_query($params);

        return $this;
    }

    /**
     * Function graphShare
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 15:23
     *
     * @param string $url
     *
     * @return $this
     */
    public function graphShare($url = '')
    {
        $params  = array('id' => $url);
        $request = Utils::sendRequest(self::GRAPH_URI, $params);
        if (!empty($request)) {
            $this->graphShare = json_decode(trim($request));
        } else {
            $this->graphShare = NULL;
        }

        return $this;
    }

    /**
     * Function commentCount
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 15:27
     *
     * @return int
     */
    public function commentCount()
    {
        if (is_object($this->graphShare) && isset($this->graphShare->share->comment_count)) {
            $result = $this->graphShare->share->comment_count;
        } else {
            $result = 0;
        }

        return $result;
    }

    /**
     * Function shareCount
     *
     * @author: 713uk13m <dev@nguyenanhung.com>
     * @time  : 11/6/18 15:28
     *
     * @return int
     */
    public function shareCount()
    {
        if (is_object($this->graphShare) && isset($this->graphShare->share->share_count)) {
            $result = $this->graphShare->share->share_count;
        } else {
            $result = 0;
        }

        return $result;
    }
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Twig\Loader;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig_Error_Loader;
use Twig_LoaderInterface;

/**
 * Remote loader.
 */
class RemoteLoader implements Twig_LoaderInterface
{
    /** @var ContainerInterface */
    private $container;
    /** @var array map of remote templates */
    private $templates;

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

    /**
     * Add a remote template.
     *
     * @param string $name
     * @param string $url
     * @param int    $ttl
     * @param array  $blocks
     * @param array  $metadata
     */
    public function addTemplate($name, $url, $ttl, array $blocks, array $metadata)
    {
        $this->templates[$name] = [
            'url' => $url,
            'ttl' => $ttl,
            'blocks' => $blocks,
            'metadata' => $metadata,
            'checked_ttl' => false,
            'checking_ttl' => false,
        ];
    }

    public function exists($name)
    {
        return isset($this->templates[$name]);
    }

    public function getSource($name)
    {
        $this->ensureExists($name);

        // fetch source
        $e = null;
        try {
            $source = \file_get_contents($this->templates[$name]['url']);
        } catch (\Exception $e) {
        }
        if ($e || false === $source) {
            throw new Twig_Error_Loader(
                \sprintf(
                    'Could not load remote template "%s" from URL "%s"',
                    $name,
                    $this->templates[$name]['url']
                ),
                -1,
                null,
                $e
            );
        }

        // convert placeholders to blocks
        $source = $this->placeholdersToBlocks($this->templates[$name]['blocks'], $source);

        // add metadata variable
        $metadata = $this->getMetadata($name);
        $source = \sprintf('{%% set _remote = %s %%}', \json_encode($metadata)) . $source;

        return $source;
    }

    public function getCacheKey($name)
    {
        $this->ensureExists($name);

        if (
            !$this->container->get('twig')->isAutoReload()
            && !$this->templates[$name]['checked_ttl']
            && !$this->templates[$name]['checking_ttl']
        ) {
            $this->templates[$name]['checking_ttl'] = true;
            $this->checkCacheFileTtl($name);
            $this->templates[$name]['checking_ttl'] = false;
            $this->templates[$name]['checked_ttl'] = true;
        }

        return $name;
    }

    public function isFresh($name, $time)
    {
        // this method is called only if env->isAutoReload() == TRUE
        $this->ensureExists($name);

        return \time() - $time < $this->templates[$name]['ttl'];
    }

    /**
     * Check cache file TTL.
     *
     * @param string $name
     */
    private function checkCacheFileTtl($name)
    {
        // this method is called only if env->isAutoReload() == FALSE
        if (
            false !== ($cacheFile = $this->container->get('twig')->getCacheFilename($name))
            && \is_file($cacheFile)
            && \time() - \filemtime($cacheFile) >= $this->templates[$name]['ttl']
        ) {
            // remove expired cache file
            \unlink($cacheFile);
        }
    }

    /**
     * Make sure the given template is a known remote template.
     *
     * @param string $name
     *
     * @throws Twig_Error_loader
     */
    private function ensureExists($name)
    {
        if (!isset($this->templates[$name])) {
            throw new Twig_Error_Loader(\sprintf('Template "%s" is not a known remote template', $name));
        }
    }

    /**
     * Convert placeholders to blocks in the source.
     *
     * @param array  $blocks
     * @param string $source
     *
     * @return string
     */
    private function placeholdersToBlocks(array $blocks, $source)
    {
        $usedBlockMap = [];
        $placeholderToBlockMap = [];

        $pattern = '';
        $first = true;
        foreach ($blocks as $blockName => $block) {
            $first ? $first = false : $pattern .= '|';
            $pattern .= \preg_quote($block['placeholder'], '/');

            $placeholderToBlockMap[$block['placeholder']] = $blockName;
        }

        return \preg_replace_callback(
            \sprintf('/(%s)/', $pattern),
            function (array $match) use ($placeholderToBlockMap, &$usedBlockMap) {
                $blockName = $placeholderToBlockMap[$match[0]];

                if (isset($usedBlockMap[$blockName])) {
                    return $this->createRepeatedPlaceholderBlockSyntax($blockName);
                }
                $usedBlockMap[$blockName] = true;

                return $this->createPlaceholderBlockSyntax($blockName);
            },
            $source
        );
    }

    /**
     * Create placeholder block syntax.
     *
     * @param string $blockName
     *
     * @return string
     */
    private function createPlaceholderBlockSyntax($blockName)
    {
        return \sprintf('{%% block %s %%}{%% endblock %%}', $blockName);
    }

    /**
     * Create repeated placeholder block syntax.
     *
     * @param string $blockName
     *
     * @return string
     */
    private function createRepeatedPlaceholderBlockSyntax($blockName)
    {
        return \sprintf('{{ block("%s") }}', $blockName);
    }

    /**
     * Get template metadata array.
     *
     * @param string $name template name
     *
     * @return string
     */
    private function getMetadata($name)
    {
        $this->ensureExists($name);

        return
            ['url' => $this->templates[$name]['url']]
            + $this->templates[$name]['metadata'];
    }

    public function getSourceContext($name)
    {
        return new \Twig_Source($this->getSource($name), $name);
    }
}


<?php

namespace TheCodingMachine\Definition;

use Assembly\ArrayDefinitionProvider;
use Interop\Container\Definition\DefinitionProviderInterface;
use Interop\Container\Definition\Factory\DefinitionProviderFactoryInterface;
use Puli\Discovery\Api\Discovery;
use Puli\Repository\Resource\FileResource;

/**
 * A class in charge of creating the YamlDefinitionLoader.
 */
class YamlDefinitionLoaderFactory implements DefinitionProviderFactoryInterface
{

    /**
     * Creates a definition provider.
     *
     * @param Discovery $discovery
     *
     * @return DefinitionProviderInterface
     */
    public static function buildDefinitionProvider(Discovery $discovery)
    {
        $bindings = $discovery->findBindings('definition-interop/yaml-definition-files');

        $definitionProviders = [];

        foreach ($bindings as $binding) {
            foreach ($binding->getResources() as $resource) {
                /* @var $resource FileResource */
                $definitionProviders[] = new YamlDefinitionLoader($resource->getFilesystemPath());
            }
        }

        return self::mergeDefinitionProviders($definitionProviders);
    }

    /**
     * @param DefinitionProviderInterface[] $definitionProviders
     */
    private static function mergeDefinitionProviders(array $definitionProviders) {
        $definitions = [];
        foreach ($definitionProviders as $definitionProvider) {
            $definitions += $definitionProvider->getDefinitions();
        }
        return new ArrayDefinitionProvider($definitions);
    }
}


<?php

namespace Addons\Core\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

use Addons\Core\Models\WechatMessageMedia;
use Addons\Core\Tools\Wechat\API;
use Addons\Core\Tools\Wechat\Attachment;
class DelayUnlink implements SelfHandling, ShouldQueue
{
	use Queueable;
	use InteractsWithQueue, SerializesModels;

	public $path, $hash;
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($path, $hash)
	{
		$this->path = $path;
		$this->hash = $hash;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{return ;
		if (is_link($this->path))
			unlink($this->path);
		else if (is_dir($this->path))
			rmdir_recursive($this->path);
		else
		{
			if ($this->hash == md5_file($this->path))
				unlink($this->path);
		}
	}
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Templating\Helper\Condition;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Define some ExpressionLanguage functions.
 */
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    /**
     * @var Security
     */
    private $security;

    /**
     * @param Security $security
     */
    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    /**
     * @return array|ExpressionFunction[]
     *
     * @SuppressWarnings(PHPMD.UnusedLocalVariables)
     */
    public function getFunctions()
    {
        return [
            new ExpressionFunction(
                'isGranted',
                function ($str) {
                    throw new \Exception($str . ' function is not implemented');
                },
                function (array $values, $attributes, $object = null) {
                    return $this->security->isGranted($attributes, $object);
                }
            ),
        ];
    }
}


<?php

namespace Zeeml\Algorithms\Formulas;

use Zeeml\Algorithms\Exceptions\CalculusResultNotFound;

class FormulasResults
{
    protected $results = [];
    protected $stack;

    /**
     * return all the results stored in
     * @return mixed
     */
    public function getAll()
    {
        return $this->results;
    }

    /**
     * Gets the last result stored
     * @return mixed
     */
    public function last()
    {
        return end($this->results);
    }

    /**
     * Returns a specific result by key
     * @param string $formulaName
     * @return mixed
     * @throws CalculusResultNotFound
     */
    public function of(string $formulaName)
    {
        if (! isset($this->results[$formulaName])) {
            throw new CalculusResultNotFound('No result found for the given formula : ' . $formulaName );
        }

        return $this->results[$formulaName];
    }

    /**
     * Save the results of a given formula to keep in the history
     * @param FormulasInterface $formula
     * @return FormulasResults
     */
    public function save(FormulasInterface $formula): FormulasResults
    {
        if ($this->isValid($formula)) {
            $this->results[get_class($formula)] = $formula->getResult();
        }

        //the stack contains all the formulas called (a callstack)
        $this->stack[] = $formula;

        return $this;
    }

    /**
     * Validates the formula by validating the result
     * A formula is not valid if the result is : null, an empty array or not a float
     * @param FormulasInterface $formula
     * @return bool
     */
    public function isValid(FormulasInterface $formula): bool
    {
        $result = $formula->getResult();

        if ((is_array($result) && count($result) > 0) || is_numeric($result)) {
            return true;
        }

        return false;
    }

    /**
     * Resets the results to empty the history
     * @return FormulasResults
     */
    public function reset(): FormulasResults
    {
        $this->results = [];

        return $this;
    }
}


<?php

namespace Greg\Support\Validation;

use Greg\Support\Arr;
use Greg\Support\Obj;

class Validation
{
    protected $prefixes = [
        'Greg\\Support\\Validation\\',
    ];

    protected $suffixes = [
        'Validator',
    ];

    /**
     * @var ValidatorStrategy[][]
     */
    protected $validators = [];

    public function __construct(array $validators = [], $prefix = null, $suffix = null)
    {
        if ($num = func_num_args()) {
            $this->addValidators((array) $validators);
        }

        if ($num > 1) {
            $this->addPrefix((array) $prefix);
        }

        if ($num > 2) {
            $this->addSuffix((array) $suffix);
        }

        return $this;
    }

    public function addValidators(array $validators)
    {
        $this->validators = array_merge($this->validators, $validators);

        return $this;
    }

    public function addPrefix($prefix)
    {
        $this->prefixes = array_merge($this->prefixes, (array) $prefix);

        return $this;
    }

    public function addSuffix($suffix)
    {
        $this->suffixes = array_merge($this->suffixes, (array) $suffix);

        return $this;
    }

    public function validate(array $params = [])
    {
        $errors = [];

        foreach ($this->validators as $key => $keyValidators) {
            if (is_scalar($keyValidators)) {
                $keyValidators = explode('|', $keyValidators);
            }

            if (is_object($keyValidators)) {
                $keyValidators = [$keyValidators];
            }

            foreach ($keyValidators as $keyValidator) {
                $validator = $this->fetchValidator($keyValidator);

                if ($validatorErrors = $validator->validate(Arr::get($params, $key), $params)) {
                    $errors[$key] = isset($errors[$key]) ? array_merge($errors[$key], $validatorErrors) : $validatorErrors;
                }
            }
        }

        return $errors;
    }

    protected function getClassByName($name)
    {
        if ($className = Obj::exists(ucfirst($name), $this->prefixes, $this->suffixes)) {
            return $className;
        }

        throw new ValidationException('Validator `' . $name . '` not found.');
    }

    /**
     * @param $validator
     *
     * @throws ValidationException
     *
     * @return ValidatorStrategy
     */
    protected function fetchValidator($validator)
    {
        if (!is_object($validator)) {
            if (is_array($validator)) {
                $name = array_shift($validator);

                $args = $validator;
            } else {
                $parts = explode(':', $validator, 2);

                $name = array_shift($parts);

                $args = $parts ? explode(',', array_shift($parts)) : [];
            }

            $className = $this->getClassByName($name);

            $validator = new $className(...$args);
        }

        if (!($validator instanceof ValidatorStrategy)) {
            throw new ValidationException('Validator `' . get_class($validator) . '` should be an instance of `' . ValidatorStrategy::class . '`.');
        }

        return $validator;
    }
}


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

/**
 * PX Commands "config"
 *
 *

 *
PX=config

 *
Pickles Framework 2 の設定情報を表示します。

 *

 */
class config{

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

	/**
	 * 設定オブジェクト
	 */
	private $conf;

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

	/**
	 * constructor
	 * @param object $px Picklesオブジェクト
	 */
	public function __construct( $px ){
		$this->px = $px;
	}

	/**
	 * kick
	 */
	private function kick(){
		$this->conf = clone $this->px->conf();

		if( $this->px->req()->is_cmd() ){
			header('Content-type: text/plain;');
			print $this->px->pxcmd()->get_cli_header();
			var_dump( $this->conf );
			print $this->px->pxcmd()->get_cli_footer();
		}else{
			$html = '';
			ob_start(); ?>

basic

<colgroup><col width="30%" /><col width="30%" /><col width="40%" /></colgroup>
<?php
print $this->mk_config_unit('name', 'プロジェクト名', 'string');
print $this->mk_config_unit('copyright', 'コピーライト', 'string');
print $this->mk_config_unit('domain', 'ドメイン名', 'string', true);
print $this->mk_config_unit('path_controot', 'コンテンツルートのパス', 'string', true);
print $this->mk_config_unit('path_top', 'トップページのパス', 'string');
print $this->mk_config_unit('path_publish_dir', 'パブリッシュ先ディレクトリのパス', 'string');
print $this->mk_config_unit('public_cache_dir', '公開キャッシュディレクトリのパス', 'string');
print $this->mk_config_unit('path_files', 'リソースディレクトリのパス', 'string');
print $this->mk_config_unit('contents_manifesto', 'コンテンツマニフェストのパス', 'string');
print $this->mk_config_unit('directory_index', 'ディレクトリインデックス', 'array');
print $this->mk_config_unit('commands', 'コマンド', 'hash');
print $this->mk_config_unit('path_phpini', 'php.ini のパス', 'string');
print $this->mk_config_unit('allow_pxcommands', 'PXコマンドを許可', 'bool');
print $this->mk_config_unit('default_timezone', 'タイムゾーン設定', 'string');
?>

filesystem

<colgroup><col width="30%" /><col width="30%" /><col width="40%" /></colgroup>
<?php
print $this->mk_config_unit('file_default_permission', 'デフォルトのファイルパーミッション', 'string', true);
print $this->mk_config_unit('dir_default_permission', 'デフォルトのディレクトリパーミッション', 'string', true);
print $this->mk_config_unit('filesystem_encoding', 'ファイルシステムの文字セット', 'string');
print $this->mk_config_unit('output_encoding', '出力時の文字セット', 'string');
print $this->mk_config_unit('output_eol_coding', '出力時の改行コード', 'string');
?>

session

<colgroup><col width="30%" /><col width="30%" /><col width="40%" /></colgroup>
<?php
print $this->mk_config_unit('session_name', 'セッション名', 'string');
print $this->mk_config_unit('session_expire', 'セッション有効期限', 'int');
?>

processor

paths_enable_sitemap (サイトマップのロードを有効にするパス)

<?php
	$conf_value = @$this->conf->{'paths_enable_sitemap'};
	unset( $this->conf->{'paths_enable_sitemap'} );
?>

<colgroup><col width="100%" /></colgroup>

path

path

<?php
foreach( $conf_value as $key=>$val ){
	print '
';
	print ''.htmlspecialchars($val).'	';
	print '
';
}
?>

paths_proc_type (プロセスタイプ)

<?php
	$conf_value = @$this->conf->{'paths_proc_type'};
	unset( $this->conf->{'paths_proc_type'} );
?>

<colgroup><col width="70%" /><col width="30%" /></colgroup>

path
proc

path
proc

<?php
foreach( $conf_value as $key=>$val ){
	print '
';
	print ''.htmlspecialchars($key).'	';
	print ''.htmlspecialchars($val).'	';
	print '
';
}
?>

funcs (プロセス機能)

<colgroup><col width="10%" /><col width="15%" /><col width="75%" /></colgroup>
<?php
print $this->mk_config_unit('funcs', 'プロセス機能', 'hash');
?>

<?php if( count( get_object_vars($this->conf) ) ){ ?>

other

<?php var_dump( $this->conf ); ?>

<?php } ?>

<?php
			$html .= ob_get_clean();
			print $this->px->pxcmd()->wrap_gui_frame($html);
		}

		exit;
	}

	/**
	 * コンフィグ項目1件を出力する。
	 *
	 * @param string $key コンフィグのキー
	 * @param string $label コンフィグラベル
	 * @param string $type 値に期待される型
	 * @param bool $required 必須項目の場合 `true`、それ以外は `false`
	 * @return string コンフィグ1件分のHTMLソース(trタグ)
	 */
	private function mk_config_unit( $key, $label, $type='string', $required = false ){
		$conf_value = @$this->conf->{$key};
		unset( $this->conf->{$key} );
		$rowspan = 1;
		if( $type == 'array' && is_array($conf_value) && count($conf_value) >= 1 ){
			$rowspan = count($conf_value);
		}

		$src = '';
		$src .= '
'."\n";
		$src .= '		'.htmlspecialchars( $key ).'	'."\n";
		if( strlen($label) ){
			$src .= '		';
			$src .= htmlspecialchars( $label );
			$src .= '	'."\n";
		}
		if( $type == 'array' && @is_array($conf_value) ){
			if( !count($conf_value) ){
				$src .= '		'.'---'.'	'."\n";
			}else{
				$i = 0;
				foreach( $conf_value as $conf_value_row ){
					if( $i > 0 ){
						$src .= '
'."\n";
						$src .= '
'."\n";
					}
					$src .= '		'.htmlspecialchars($conf_value_row).'	'."\n";
					$i ++;
				}
			}
		}elseif( $type == 'hash' && (@is_array($conf_value) || @is_object($conf_value)) ){
			$src .= '		';
			$conf_value_test = $conf_value;
			if( is_object($conf_value) ){
				$conf_value_test = get_object_vars($conf_value);
			}
			$conf_value_test = $conf_value;
			if( !count($conf_value_test) ){
				$src .= '---';
			}else{
				$src .= '
';
				foreach( $conf_value as $ary_key=>$ary_val ){
					$src .= '
'.htmlspecialchars($ary_key).'
';
					$src .= '
';
					if( is_string($ary_val) || is_int($ary_val) || is_float($ary_val) ){
						$src .= htmlspecialchars($ary_val);
					}else{
						ob_start();
						var_dump($ary_val);
						$src .= '
'.htmlspecialchars( ob_get_clean() ).'
';
					}
					$src .= '
';
				}
				$src .= '
';
			}
			$src .= '	'."\n";
		}elseif(@is_null($conf_value)){
			$src .= '		';
			$src .= 'null';
			if( $required ){
				$src .= 'required!!';
			}
			$src .= '	'."\n";
		}elseif(@is_array($conf_value) || @is_object($conf_value)){
			$src .= '		';
			$src .= '
';
			ob_start();
			var_dump($conf_value);
			$src .= ob_get_clean();
			$src .= '
';
			if( $required ){
				$src .= 'required!!';
			}
			$src .= '	'."\n";
		}else{
			$src .= '		';
			switch(strtolower($type)){
				case 'bool':
					$src .= ($conf_value?'true':'false');
					break;
				case 'realpath':
					$src .= $this->h( realpath( $conf_value ) ).'
(<q>'.$this->h( $conf_value ).'</q>)';
					break;
				case 'string':
				default:
					if( preg_match( '/^colors\./', $key ) ){
						// 色設定の場合に限り、カラーチップを手前に置く。
						$src .= '■'.$this->h( $conf_value );
					}else{
						$src .= $this->h( $conf_value );
					}
					break;
			}
			$src .= '	'."\n";
		}
		$src .= '
'."\n";
		return $src;
	}

	/**
	 * HTML特殊文字をエスケープする。
	 *
	 * このメソッドは改行コードを改行タグ `<br />` に変換します。
	 *
	 * @param string $txt 文字列
	 * @return string HTML特殊文字がエスケープされた文字列
	 */
	private function h($txt){
		$txt = htmlspecialchars($txt);
		$txt = preg_replace('/\r\n|\r|\n/','
',$txt);
		return $txt;
	}

}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Menu;

use Imatic\Bundle\ViewBundle\Templating\Utils\StringUtil;
use Knp\Menu\ItemInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Translation\TranslatorInterface;

class Helper
{
    /**
     * @var TranslatorInterface
     */
    protected $translator;
    /**
     * @var Security
     */
    private $security;

    public function __construct(TranslatorInterface $translator, Security $security)
    {
        $this->translator = $translator;
        $this->security = $security;
    }

    /**
     * Adds a vertical/horizontal divider.
     *
     * @param ItemInterface $item
     * @param bool          $vertical
     *
     * @return ItemInterface
     */
    public function addDivider(ItemInterface $item, $vertical = false)
    {
        $class = $vertical ? 'divider-vertical' : 'divider';

        return $item->addChild('divider_' . \rand())
            ->setLabel('')
            ->setAttribute('class', $class);
    }

    /**
     * Adds a menu header.
     *
     * @param ItemInterface $item
     * @param $text
     *
     * @return ItemInterface
     */
    public function addHeader(ItemInterface $item, $text)
    {
        return $item->addChild('header_' . \rand())
            ->setLabel($text)
            ->setAttribute('class', 'nav-header');
    }

    /**
     * Creates a drop down menu item from item.
     *
     * @param ItemInterface $dropDownItem
     */
    public function setDropdown(ItemInterface $dropDownItem)
    {
        $dropDownItem
            ->setUri('#')
            ->setLinkattribute('class', 'dropdown-toggle')
            ->setLinkattribute('data-toggle', 'dropdown')
            ->setAttribute('class', 'dropdown')
            ->setChildrenAttribute('class', 'dropdown-menu');

        $dropDownItem->setLabel($dropDownItem->getLabel() . '');
        $dropDownItem->setExtra('safe_label', true);
    }

    /**
     * Creates a sub menu item from item.
     *
     * @param ItemInterface $item
     */
    public function setSubmenu(ItemInterface $item)
    {
        $item->setChildrenAttribute('class', 'nav nav-list');
    }

    public function setBadge(ItemInterface $item, $content, $type = null, $right = null)
    {
        $badge = \sprintf(' %s', $type, $right ? ' pull-right' : '', $content);
        $item
            ->setExtra('safe_label', true)
            ->setLabel(StringUtil::escape($item->getLabel()) . $badge);
    }

    public function setIcon(ItemInterface $item, $icon, $right = null)
    {
        $icon = \sprintf('', $icon, $right ? 'right' : 'left');
        $item
            ->setExtra('safe_label', true)
            ->setLabel($icon . StringUtil::escape($item->getLabel()));
    }

    /**
     * Translates the given choice message by choosing a translation according to a number.
     *
     * @param string $id         The message id
     * @param int    $number     The number to use to find the indice of the message
     * @param array  $parameters An array of parameters for the message
     * @param string $domain     The domain for the message
     * @param string $locale     The locale
     *
     * @return string The translated string
     */
    public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null): string
    {
        return $this->translator->transChoice($id, $number, $parameters, $domain, $locale);
    }

    /**
     * Translates the given message.
     *
     * @param string $id         The message id
     * @param array  $parameters An array of parameters for the message
     * @param string $domain     The domain for the message
     * @param string $locale     The locale
     *
     * @return string The translated string
     */
    public function trans($id, array $parameters = [], $domain = null, $locale = null): string
    {
        return $this->translator->trans($id, $parameters, $domain, $locale);
    }

    /**
     * Returns the current locale.
     *
     * @return string The locale
     */
    public function getLocale(): string
    {
        return $this->translator->getLocale();
    }

    /**
     * Returns true if current user is logged.
     *
     * @return bool
     */
    public function isUserLogged(): bool
    {
        return $this->security->isGranted('IS_AUTHENTICATED_REMEMBERED');
    }

    /**
     * @return null|UserInterface
     */
    public function getUser(): ?UserInterface
    {
        return $this->security->getUser();
    }

    /**
     * Checks if the attributes are granted against the current authentication token and optionally supplied object.
     *
     * @param mixed $attributes
     * @param mixed $subject
     *
     * @return bool
     */
    public function isUserGranted($attributes, $subject = null): bool
    {
        return $this->security->isGranted($attributes, $subject);
    }
}


<?php
namespace Addons\Core\Http;

use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Addons\Core\Http\Response\BinaryFileResponse;
use Illuminate\Routing\ResponseFactory as FactoryContract;

class ResponseFactory extends FactoryContract {

	/**
	 * Return a new response from the application.
	 *
	 * @param  string  $content
	 * @param  int  $status
	 * @param  array  $headers
	 * @return \Illuminate\Http\Response
	 */
	public function make($content = '', $status = 200, array $headers = [])
	{
		return new Response($content, $status, $headers);
	}

	/**
	 * Create a new file download response.
	 *
	 * @param  \SplFileInfo|string  $file
	 * @param  string  $name
	 * @param  array  $headers
	 * @param  string|null  $disposition
	 * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
	 */
	public function download($file, $name = null, array $headers = [], $options = [], $disposition = 'attachment')
	{
		!empty($options['cached']) && $headers = array_merge($headers, ['Cache-Control' => 'private, max-age=3600, must-revalidate', 'Pragma' => 'cache']);
		!empty($options['mime_type']) && $headers = array_merge($headers, ['Content-Type' => $options['mime_type']]);

		$response = new BinaryFileResponse($file, 200, $headers, true, $disposition);

		if (isset($options['last_modified']))
			$response->setLastModified($options['last_modified']);

		if (isset($options['etag']))
			$response->setEtag($options['etag']);

		if (!is_null($name))
			$response->setContentDisposition($disposition, $name, str_replace('%', '', Str::ascii($name)));

		return $response;
	}

	public function preview($file, $headers = [], $options = [])
	{
		return $this->download($file, null, $headers, $options, null);
	}
}


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

namespace FDevs\Photatoes\Adapter;

use FDevs\Photatoes\Gallery;
use FDevs\Photatoes\Image;
use FDevs\Photatoes\Manager;
use FDevs\Photatoes\Meta;
use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Symfony\Component\Serializer\Encoder\JsonDecode;

class YandexAdapter implements AdapterInterface
{
    /**
     * @var Client
     */
    private $client;

    /**
     * init
     *
     * @param string          $user
     * @param ClientInterface $client
     */
    public function __construct($user, ClientInterface $client = null)
    {
        if ($client) {
            $this->client = $client;
        } else {
            $this->client = new Client();
        }
        $this->client->setConfig(array('users' => $user));
        $this->client->setDefaultOption('headers', array('Accept' => 'application/json'));
        $this->client->setBaseUrl($this->getBaseUrl());
    }

    /**
     * {@inheritDoc}
     */
    public function getImage(Image $image)
    {
        $photo = $this->getDataByType($image->getId());

        return $this->mappingImage($image, $photo);
    }

    /**
     * {@inheritDoc}
     */
    public function getGallery(Gallery $album)
    {
        $data = $this->getDataByType($album->getId(), 'album');
        $this->setGallery($data, $album);

        return $album;
    }

    /**
     * {@inheritDoc}
     */
    public function getCover(Gallery $album)
    {
        $data = $this->getDataByType($album->getId(), 'album');
        if (isset($data['links']['cover'])) {
            $idImage = array_slice(explode('/', $data['links']['cover']), -2, 1);
            $data = $this->getDataByType($idImage[0]);
            $this->setListCover($data['img'], $album);
        }

        return $album;
    }

    /**
     * {@inheritDoc}
     */
    public function getImagesGallery(Gallery $album)
    {
        $data = $this->getDataByType($album->getId(), 'albumPhotos');
        if (isset($data['entries'])) {
            foreach ($data['entries'] as $dataImage) {
                $image = new Image(substr(strrchr($dataImage['id'], ':'), 1));
                $this->mappingImage($image, $dataImage);
                $album->addImage($image);
            }
        }

        return $album;
    }

    /**
     * {@inheritDoc}
     */
    public function getListGallery(Manager $manager)
    {
        $albums = array();
        $data = $this->getDataByType('', 'albums');
        if (isset($data['entries'])) {
            foreach ($data['entries'] as $entry) {
                $albums[] = $this->setGallery($entry, new Gallery($this->getId($entry['id']), $manager));
            }
        }

        return $albums;
    }

    /**
     * {@inheritDoc}
     */
    public function saveImage(Image $image)
    {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function saveGallery(Gallery $gallery)
    {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function getTagList()
    {
        $tags = array();
        $data = $this->getDataByType('', 'tags');
        if (isset($data['entries'])) {
            foreach ($data['entries'] as $tag) {
                $tags[] = $tag['title'];
            }
        }

        return $tags;
    }

    /**
     * {@inheritDoc}
     */
    public function getImagesByTag($tag, Manager $manager = null)
    {
        $data = $this->getDataByType(rawurlencode($tag), 'tag');
        $images = array();
        if (isset($data['entries'])) {
            foreach ($data['entries'] as $img) {
                $image = new Image($this->getId($img['id']), $manager);
                $images[] = $this->mappingImage($image, $img);
            }
        }

        return $images;
    }

    /**
     * mapping Image
     *
     * @param Image $image
     * @param array $data
     *
     * @return Image
     */
    private function mappingImage(Image $image, array $data)
    {
        if (isset($data['summary'])) {
            $image->setDescription($data['summary']);
        }
        if (isset($data['title'])) {
            $image->setTitle($data['title'])
                ->setPublishAt(new \DateTime($data['published']))
                ->setUpdateAt(new \DateTime($data['updated']))
                ->setTags(array_keys($data['tags']));
            foreach ($data['img'] as $value) {
                $image->addMeta(new Meta($value['href'], $value['width'], $value['height']));
            }
        }

        return $image;
    }

    /**
     * get Id
     *
     * @param string $id
     *
     * @return string
     */
    private function getId($id)
    {
        $return = array_slice(explode(':', $id), -1, 1);

        return count($return) ? $return[0] : '';
    }

    /**
     * get Base Url
     *
     * @return string
     */
    private function getBaseUrl()
    {
        return 'http://api-fotki.yandex.ru/api/users/{users}';
    }

    /**
     * set Gallery
     *
     * @param  array   $data album
     * @param  Gallery $album
     *
     * @return Gallery
     */
    private function setGallery(array $data, Gallery $album)
    {
        if (isset($data['title'])) {
            $album->setName($data['title'])
                ->setCount(0)
                ->setUpdatedAt(new \DateTime($data['updated']));
            if (isset($data['imageCount'])) {
                $album->setCount($data['imageCount']);
            }
            if (isset($data['img'])) {
                $this->setListCover($data['img'], $album);
            }
        }

        return $album;
    }

    /**
     * get Api Url
     *
     * @param  string $type album|photo|albumPhotos|albums or base path
     * @param  string $key
     *
     * @return string
     */
    private function getUrl($type, $key)
    {
        switch ($type) {
            case 'album':
                $url = 'album/%s/';
                break;
            case 'photo':
                $url = 'photo/%s/';
                break;
            case 'albumPhotos':
                $url = 'album/%s/photos/';
                break;
            case 'albums':
                $url = 'albums/';
                break;
            case 'tags':
                $url = 'tags/';
                break;
            case 'tag':
                $url = 'tag/%s/photos/';
                break;
            default:
                $url = '/';
        }

        return sprintf($url, $key);
    }

    /**
     * set Cover List
     *
     * @param array   $listCover
     * @param Gallery $album
     */
    private function setListCover(array $listCover, Gallery $album)
    {
        foreach ($listCover as $image) {
            $album->addCover(new Meta($image['href'], $image['width'], $image['height']));
        }
    }

    /**
     * get Data By Type
     *
     * @param  string $key
     * @param  string $type
     *
     * @return array
     */
    private function getDataByType($key, $type = 'photo')
    {
        $url = $this->getUrl($type, $key);

        return $this->getData($url);
    }

    /**
     * get Data By Url
     *
     * @param string $url
     *
     * @return array
     */
    private function getData($url)
    {
        try {
            $request = $this->client->get($url);
            $response = $request->send();
            $decoder = new JsonDecode(true);
            $data = $decoder->decode($response->getBody(true), 'json');
            if (isset($data['links']['next'])) {
                $next = $this->getData($data['links']['next']);
                $data['entries'] = array_merge($data['entries'], $next['entries']);
            }
        } catch (\Exception $e) {
            $data = array();
        }

        return $data;
    }
}


<?php namespace Foothing\RepositoryController\Controllers;

class RouteInstaller {

    /**
     * Install route patterns.
     *
     * @param null $baseUri
     */
    public static function install($baseUri = null) {
		$baseUri = $baseUri ? "$baseUri/" : "";
        \Route::post($baseUri . "resources/bulk/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@postBulk");
        \Route::put($baseUri . "resources/bulk/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@putBulk");
        \Route::put($baseUri . "resources/{resource}/{id}/link/{relation}/{related}/{relatedId}", "Foothing\RepositoryController\Controllers\ResourceController@putLink");
        \Route::delete($baseUri . "resources/{resource}/{id}/link/{relation}/{related}/{relatedId}", "Foothing\RepositoryController\Controllers\ResourceController@deleteLink");
        \Route::get($baseUri . "resources/{resource}/{id?}/{args?}", "Foothing\RepositoryController\Controllers\ResourceController@getIndex")->where('args', '[a-zA-Z0-9/_]*');
		\Route::put($baseUri . "resources/{resource}/{id}", "Foothing\RepositoryController\Controllers\ResourceController@putIndex");
		\Route::delete($baseUri . "resources/{resource}/{id}", "Foothing\RepositoryController\Controllers\ResourceController@deleteIndex");
		\Route::post($baseUri . "resources/{resource}", "Foothing\RepositoryController\Controllers\ResourceController@postIndex");
	}
}


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

namespace Dominia;

use \Smalot\PdfParser\Parser;

class DocParser
{
    /**
     * Reads the specified PDF file (complete path & filename), decode and parse it
     * and returns an array containing as many elements as domains inside the PDF file.
     * Each array element is an associative array of type ('domain' => domain.com, 'registerDate'=>yyyy-mm-dd)
     *
     * @param $pdfFile
     * @return array
     * @throws \Exception
     */
    public function pdfToArray($pdfFile){
        $domains = array();
        $lines = array();
        $parser = new \Smalot\PdfParser\Parser();
        $pdf = $parser->parseFile($pdfFile);
        $text = $pdf->getText();
        $rawLines = explode("\n", $text);
        $line = "";
        foreach($rawLines as $l){

            $l = trim($l);
            $line .= $l;
            if($this->isValidDate(substr($line, -10))){
                $lines[] = $line;
                $line = "";
            }
        }

        foreach($lines as $l) {
            $l = trim($l);
            preg_match_all('#[0-3][0-9]\/[0-1][0-9]\/[2][0][0-9][0-9]#', $l, $found);
            foreach($found[0] as $fDate){
                $i = strpos($l, $fDate);
                $dateOrig = substr($l, $i, 10);
                $domainEntry = trim(substr($l, 0, $i));
                if($this->isValidDate($dateOrig) && $this->isValidDomain($domainEntry)) {
                    $date = substr($dateOrig, 6, 4)."-".substr($dateOrig, 3, 2)."-".substr($dateOrig, 0, 2);
                    $domains[] = array('domain' => $domainEntry, 'registerDate' => $date);
                }
                $l = substr($l, $i + 10);
            }
        }
        return $domains;
    }

    /**
     * Checks if a date string is valid
     * @param $date
     * @return bool
     */
    private function isValidDate($date){
        return preg_match('#[0-3][0-9]\/[0-1][0-9]\/[2][0][0-9][0-9]#', $date)
               &&
               checkdate((int)substr($date, 3, 2),
                         (int)substr($date, 0, 2),
                         (int)substr($date, 6, 4));
    }

    /**
     * Checks if a string is a valid domain name
     * @param $domain
     * @return mixed
     */
    private function isValidDomain($domain){
        return filter_var("http://".$domain, FILTER_VALIDATE_URL);
    }
}