<?php

/**
 * マイグレーションを表します。
 *
 * @author Seiji Nitta
 */
abstract class Zeclib_Migration
{
    /**
     * マイグレーションバージョン
     *
     * 各マイグレーションを適用する順序を解決するために使用されます。
     * 詳細は Zeclib_Migrator::sort() を参照して下さい。
     *
     * @var string
     * @see Zeclib_Migrator::sort()
     */
    public $version;

    /**
     * @var bool
     */
    public $applied = false;

    /**
     * @var SC_Query_Ex
     */
    public $query;

    /**
     * @var Zeclib_MigrationLogger
     */
    public $logger;

    /**
     * @param string $version マイグレーションバージョン
     * @param SC_Query_Ex $query
     */
    public function __construct($version, SC_Query_Ex $query)
    {
        $this->version = $version;
        $this->query = $query;
    }

    /**
     * マイグレーションを適用します。
     * 適用を中断する場合は例外を発生させて下さい。
     */
    abstract public function up();

    /**
     * マイグレーションを取り消します。
     * 取り消しを中断する場合は例外を発生させて下さい。
     */
    abstract function down();

    /**
     * ログを記録します。
     * マイグレーション中に残したいメッセージを指定して下さい。
     *
     * @param string $message
     * @param int $type
     */
    public function log($message, $type = Zeclib_MigrationLogger::TYPE_INFO)
    {
        $this->logger->log($message, $type);
    }
}


<?php

/*
 * This file is part of the Meta Reader package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MetaReader;

use Temp\MetaReader\Value\ValueBag;

/**
 * Chain reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ChainReader implements ReaderInterface
{
    /**
     * @var ReaderInterface[]
     */
    private $readers;

    /**
     * @param ReaderInterface[] $readers
     */
    public function __construct(array $readers = [])
    {
        foreach ($readers as $reader) {
            $this->addReader($reader);
        }
    }

    /**
     * @param ReaderInterface $reader
     */
    public function addReader(ReaderInterface $reader)
    {
        $this->readers[] = $reader;
    }

    /**
     * @return bool
     */
    public function available()
    {
        foreach ($this->readers as $reader) {
            if ($reader->available()) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        foreach ($this->readers as $reader) {
            if ($reader->available() && $reader->supports($filename)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function read($filename)
    {
        $meta = new ValueBag();

        foreach ($this->readers as $reader) {
            if ($reader->available() && $reader->supports($filename)) {
                $meta->merge($reader->read($filename));
            }
        }

        return $meta;
    }
}


<?php
namespace Lab123\Odin\Command;

use Illuminate\Console\Command;

class AppStart extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start Laravel App';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->validate();

        try {
            $this->info('Starting App...');

            $this->composer_install();
            $this->vendor_publish();
            $this->migrate();
            $this->seed();
        } catch (\Exception $ex) {
            // $this->migrate_reset();
            $this->error($ex);
        }
    }

    private function validate()
    {
        if (! env('DB_HOST')) {
            $this->error('Verify .env to connect database');
            exit();
        }
    }

    private function composer_install()
    {
        $this->line('> composer install');
        exec('composer install');
    }

    private function vendor_publish()
    {
        $this->line('> php artisan vendor:publish');
        exec('php artisan vendor:publish');
    }

    private function migrate()
    {
        $this->line('> php artisan migrate');
        exec('php artisan migrate');
    }

    private function migrate_reset()
    {
        $this->line('> php artisan migrate:refresh --seed');
        exec('php artisan migrate:refresh --seed');
    }

    private function seed()
    {
        $this->line('> php artisan db:seed');
        exec('php artisan db:seed');
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Authentication\Adapter;

use Zend\Authentication\Result,
    Zend\Crypt\Password\Bcrypt,
    Zend\Session\Container,
    CmsCommon\Persistence\MapperProviderInterface,
    CmsCommon\Persistence\MapperProviderTrait,
    CmsCommon\Mapping\Common\PasswordableInterface,
    CmsCommon\Mapping\Common\StateableInterface,
    CmsCommon\Mapping\Dateable\ExpirableInterface,
    CmsAuthentication\Adapter\AbstractAdapter,
    CmsAuthentication\Adapter\AdapterChainEvent,
    CmsUser\Mapping\LoginTrackableInterface,
    CmsUser\Options\AuthenticationOptionsInterface,
    CmsUser\Persistence\UserMapperInterface;

class DefaultAdapter extends AbstractAdapter implements MapperProviderInterface
{
    use MapperProviderTrait;

    /**
     * @var AuthenticationOptionsInterface
     */
    protected $options;

    /**
     * @var callable
     */
    protected $credentialPreprocessor;

    /**
     * __construct
     *
     * @param UserMapperInterface $mapper
     * @param AuthenticationOptionsInterface $options
     */
    public function __construct(UserMapperInterface $mapper, AuthenticationOptionsInterface $options)
    {
        $this->setMapper($mapper);
        $this->options = $options;
    }

    /**
     * {@inheritDoc}
     *
     * @throws Exception\BadMethodCallException
     */
    public function authenticate(AdapterChainEvent $e)
    {
        if ($this->isSatisfied()) {
            $storage = $this->getStorage()->read();
            $e->setIdentity($storage['identity'])
              ->setCode(Result::SUCCESS)
              ->setMessages(['Authentication successful']);

            return;
        }

        $post = $e->getRequest()->getPost();

        $identity = $post->get($e->getIdentityKey());
        $identityObject = $this->getMapper()->findByIdentity($identity);
        if (!$identityObject) {
            $e->setCode(Result::FAILURE_IDENTITY_NOT_FOUND)
              ->setMessages(['A record with the supplied identity could not be found']);
            $this->setSatisfied(false);

            return false;
        }

        if ($identityObject instanceof PasswordableInterface) {
            $credential = $post->get($e->getCredentialKey());
            $credential = $this->preprocessCredential($credential);
            $password   = $identityObject->getPassword();

            if (!$this->getMapper()->getPasswordService()->verify($credential, $password)) {
                // Password does not match
                $e->setCode(Result::FAILURE_CREDENTIAL_INVALID)
                  ->setMessages(['Supplied credential is invalid']);
                $this->setSatisfied(false);

                return false;
            }

            // Update user's password hash if the cost parameter has changed
            $this->updateCredentialHash($identityObject, $credential);
        }

        if ($identityObject instanceof StateableInterface) {
            $allowedStates = $this->options->getAllowedAuthenticationStates();

            // Don't allow user to login if state is not in allowed list
            if ($allowedStates && !in_array($identityObject->getState(), $allowedStates, true)) {
                $e->setCode(Result::FAILURE_UNCATEGORIZED)
                  ->setMessages(['A record with the supplied identity is disabled']);
                $this->setSatisfied(false);

                return false;
            }
        }

        if ($identityObject instanceof ExpirableInterface
            && null !== ($expireAt = $identityObject->getExpireAt())
            && $expireAt < new \DateTime('now')
        ) {
            $e->setCode(Result::FAILURE_UNCATEGORIZED)
              ->setMessages(['Record has expired']);
            $this->setSatisfied(false);

            return false;
        }

        // Regenerate the id
        $session = new Container($this->getStorage()->getNameSpace());
        $session->getManager()->regenerateId();

        // Success!
        $e->setIdentity($identityObject->getId());

        // Remember user if needed
        if ($post->get('rememberme') && ($ttl = $e->getRememberMeTimeout()) > 0) {
            $session->getManager()->rememberMe($ttl);
        }

        if ($identityObject instanceof LoginTrackableInterface) {
            $identityObject->setLoginAt(new \DateTime('now'));
        }

        $this->getMapper()->update($identityObject)->save();

        $this->setSatisfied(true);

        $storage = $this->getStorage()->read();
        $storage['identity'] = $e->getIdentity();
        $this->getStorage()->write($storage);

        $e->setCode(Result::SUCCESS)
          ->setMessages(['Authentication successful']);
    }

    /**
     * Called when user id logged out
     *
     * @param  AdapterChainEvent $e Event passed
     * @return void
     */
    public function logout(AdapterChainEvent $e)
    {
        $session = new Container($this->getStorage()->getNameSpace());
        $session->getManager()->forgetMe();
        $session->getManager()->destroy();
    }

    /**
     * Update identity object password hash if cost has been changed
     *
     * @param PasswordableInterface $identityObject
     * @param string $password
     * @return self
     */
    protected function updateCredentialHash(PasswordableInterface $identityObject, $password)
    {
        $cryptoService = $this->getMapper()->getPasswordService();
        if (!$cryptoService instanceof Bcrypt) {
            return $this;
        }

        $hash = explode('$', $identityObject->getPassword());
        if ($hash[2] === $cryptoService->getCost()) {
            return $this;
        }

        $identityObject->setPassword($cryptoService->create($password));

        return $this;
    }

    /**
     * Preprocess credential
     *
     * @param string $credential
     * @return string
     */
    public function preprocessCredential($credential)
    {
        $processor = $this->getCredentialPreprocessor();
        if (is_callable($processor)) {
            return $processor($credential);
        }

        return $credential;
    }

    /**
     * Get credential preprocessor
     *
     * @return callable
     */
    public function getCredentialPreprocessor()
    {
        return $this->credentialPreprocessor;
    }

    /**
     * Set credential preprocessor
     *
     * @param callable $credentialPreprocessor the value to be set
     * @return self
     */
    public function setCredentialPreprocessor(callable $credentialPreprocessor)
    {
        $this->credentialPreprocessor = $credentialPreprocessor;
        return $this;
    }
}


<?php
namespace HtSettingsModule\Options;

use Zend\Stdlib\AbstractOptions;
use HtSettingsModule\Exception;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Zend\Stdlib\Hydrator;
use ArrayObject;

class NamespaceOptions extends AbstractOptions implements NamespaceOptionsInterface
{
    /**
     * @var string
     */
    protected $name;

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

    /**
     * @var object
     */
    protected $entityPrototype;

    /**
     * @var string|HydratorInterface      Hydrator of namespace entity for converting array to namespace entity
     */
    protected $hydrator;

    /**
     * Sets name of namespace
     *
     * @param  string $name
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this->name;
    }

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

    /**
     * Sets entity class of namespace entity
     *
     * @param  string $entityClass
     * @return self
     */
    public function setEntityClass($entityClass)
    {
        $this->entityClass = $entityClass;

        return $this;
    }

    /**
     * Sets entity prototype of namespace entity
     *
     * @param  object $entityPrototype
     * @return self
     */
    public function setEntityPrototype($entityPrototype)
    {
        if (!is_object($entityPrototype)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be an object, %s provided instead',
                    __METHOD__,
                    is_object($entityPrototype) ? get_class($entityPrototype) : gettype($entityPrototype)
                )
            );
        }
        $this->entityPrototype = $entityPrototype;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getEntityPrototype()
    {
        if (!$this->entityPrototype) {
            if ($this->getEntityClass()) {
                $entityClass = $this->getEntityClass();
                $this->entityPrototype = new $entityClass;
            } else {
                $this->entityPrototype = new ArrayObject;
            }
        }

        return $this->entityPrototype;
    }

    /**
     * Gets entity class of namespace
     *
     * @return string
     */
    public function getEntityClass()
    {
        return $this->entityClass;
    }

    /**
     * Sets hydrator of namespace entity for converting array to namespace entity
     *
     * @param  HydratorInterface|string $hydrator
     * @return self
     */
    public function setHydrator($hydrator)
    {
        if (!is_string($hydrator) && !$hydrator instanceof HydratorInterface) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be an object of instance Zend\Stdlib\Hydrator\HydratorInterface or string, %s provided instead',
                    __METHOD__,
                    is_object($hydrator) ? get_class($hydrator) : gettype($hydrator)
                )
            );
        }
        $this->hydrator = $hydrator;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getHydrator()
    {
        if ($this->hydrator === null) {
            if ($this->getEntityPrototype() instanceof ArrayObject) {
                $hydrator = new Hydrator\ArraySerializable;
            } else {
                $hydrator = new Hydrator\ClassMethods;
            }
            $this->hydrator = $hydrator;
        }

        return $this->hydrator;
    }
}


<?php

namespace Nether;
use \Nether;
use \Exception;

///////////////////////////////////////////////////////////////////////////////
// library options ////////////////////////////////////////////////////////////

Option::Define([

	'surface-auto-capture' => true,
	/*//
	@option surface-auto-capture boolean
	if true, surface will start recording STDOUT into its overbuffer the
	moment the object is created. if false, you will need to manually call
	the Start method to begin recording.
	//*/

	'surface-auto-stash' => 'surface',
	/*//
	@option surface-auto-stash string
	if a string and Nether\Stash exists, this is the key name Surface will
	automatically tuck itself into. set to false to disable this behaviour.
	//*/

	'surface-auto-render' => true,
	/*//
	@option surface-auto-render boolean
	if true, surface will automatically render the final product when the
	object instance is destroyed.
	//*/

	'surface-theme' => 'default',
	/*//
	@option surface-theme string
	the default value to use as the main page theme. this is the theme we will
	pull the design.phtml for when all is ready to go.
	//*/

	'surface-theme-stack' => [ 'common' ],
	/*//
	@option surface-theme-stack array[string, ...]
	a list of themes to fall back on if a file was requested from the
	configured theme could not be found.
	//*/

	'surface-theme-style' => 'default',
	/*//
	@option surface-theme-style string
	the default value to use as the "Style" of the theme. the style is not
	used by anything in Surface, but exists here to provide a mechanism for
	allowing something like a user selected subtheme, or whatever.
	//*/

	'surface-title-brand' => true,
	/*//
	@option surface-title-brand boolean
	if true it will attempt to brand your page-title value with data from
	app name. if no page-title had ever been set by the app then it will
	attempt ot use both app-name and app-short-desc.
	//*/

	'surface-theme-root' => sprintf('%s/themes',rtrim(Option::Get('nether-web-root'),'/')),
	/*//
	@option surface-theme-root string
	defines the full filepath to the themes directory as the server needs to
	know it.
	//*/

	'surface-theme-path' => sprintf('%s/themes',rtrim(Option::Get('nether-web-path'),'/'))
	/*//
	@option surface-theme-path string
	defines the relative uri to the themes directory as the browser needs to
	know it.
	//*/

]);

///////////////////////////////////////////////////////////////////////////////
// library ki event handlers //////////////////////////////////////////////////

Ki::Queue('avenue-redirect',function(){
	// if a redirect was requested shut down the automatic surface instance and
	// throw away whatever it already collected.

	if(!class_exists('Nether\Stash')) return;

	$surface = Stash::Get(Option::Get('surface-auto-stash'));

	if($surface && $surface instanceof Surface)
	$surface->SetAutoRender(false)->Stop(false);

	return;
},true);

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

class Surface {
/*//
this is the engine engine designed to make it easy to application output into
page templates with ease. there is no template language, the templates are
plain html with embedded php calls to the various surface methods. just in case
you have forgotten, php *is* a templating language.

to work as intended surface needs to know two things, which you should configure
as early as possible in the application real booting process via Nether\Option.

* nether-web-root - the filepath to the root of the public web directory.
* nether-web-path - the web url base directory from the base domain. e.g. "/"

armed with those values, surface will extrapolate where the themes are stored
by way of the suggested Nether application structure. if you wish to be specific
instead of allowing it to guess, you may specify the root and path for the
theme directory via surface-theme-root (filesystem path) and
surface-theme-path (web url path).
//*/

	protected $Started = false;
	/*//
	@type boolean
	a sentinel marking if this object has begun capturing a level of stdout
	or not.
	//*/

	protected $Rendered = false;
	/*//
	@type boolean
	marks if this object has rendered before. this is mainly to prevent the
	destruct from trying again if we had manually called Render prior.
	//*/

	protected $Storage = [];
	/*//
	@type array
	where this surface instance stores the data to be used for rendering.
	//*/

	////////////////////////
	////////////////////////

	protected $AutoRender = false;
	/*//
	@type bool
	if this object should automatically render when it is destroyed. this value
	is populated by the option surface-auto-render on creation.
	//*/

	public function
	GetAutoRender() { return $this->AutoRender; }

	public function
	SetAutoRender($b) { $this->AutoRender = (bool)$b; return $this; }

	////////
	////////

	protected $Style;
	/*//
	@type string
	the name of the subtheme for the theme to use if it wants. the library
	itself does not actually use this, but it is there to make subthemes easier
	to make.
	//*/

	public function
	GetStyle() { return $this->Style; }

	public function
	SetStyle($style) { $this->Style = $style; return $this; }

	////////
	////////

	protected $Theme;
	/*//
	@type string
	the name of the theme to render in.
	//*/

	public function
	GetTheme() { return $this->Theme; }

	public function
	SetTheme($theme) { $this->Theme = $theme; return $this; }

	////////
	////////

	protected $ThemeRoot;
	/*//
	@type string
	the directory all the themes are installed.
	//*/

	public function
	GetThemeRoot() { return $this->ThemeRoot; }

	public function
	SetThemeRoot($path) { $this->ThemeRoot = $path; return $this; }

	///////////////////////////////////////////////////////////////////////////
	// magic object behaviour methods /////////////////////////////////////////

	public function
	__Construct($opt=null) {
	/*//
	handle object construction.
	//*/

		$opt = new Nether\Object\Mapped($opt,[
			'Theme'       => Option::Get('surface-theme'),
			'ThemeRoot'   => Option::Get('surface-theme-root'),
			'Style'       => Option::Get('surface-theme-style'),
			'AutoCapture' => Option::Get('surface-auto-capture'),
			'AutoStash'   => Option::Get('surface-auto-stash'),
			'AutoRender'  => Option::Get('surface-auto-render')
		]);

		$this->Storage['stdout'] = '';

		// pull in default settings.
		$this->AutoRender = ((php_sapi_name()==='cli')?(false):($opt->AutoRender));
		$this->Theme = $opt->Theme;
		$this->ThemeRoot = $opt->ThemeRoot;
		$this->Style = $opt->Style;

		// if auto stashing is enabled.
		if(is_string($opt->AutoStash) && class_exists('Nether\Stash')) {
			if(!Stash::Has($opt->AutoStash))
			Stash::Set($opt->AutoStash,$this);
		}

		// begin capture if autocapture is enabled and this is not the
		// command line interface.
		if($opt->AutoCapture && php_sapi_name() !== 'cli')
		$this->Start();

		return;
	}

	public function
	__Destruct() {
	/*//
	handle object destruction.
	//*/

		if($this->AutoRender && !$this->Rendered)
		$this->Render();

		return;
	}

	public function
	__Invoke() {
	/*//
	@argv string Key
	provide a shortcut for getting and setting data. if one argument
	is provided then it will get the value. if two, it will set it.
	//*/

		$argv = func_get_args();
		switch(count($argv)) {
			case 1: {
				return $this->Get($argv[0]);
			}
			case 2: {
				$this->Set($argv[0],$argv[1]);
				return $this;
			}
		}

		return $this;
	}

	///////////////////////////////////////////////////////////////////////////
	// rendering control api //////////////////////////////////////////////////

	/*// these methods will manage the overbuffer recording and deal with
	compiling the resulting page from the configured template. //*/

	public function
	Start() {
	/*//
	@return boolean
	begin capturing stdout if this object has not already done so. returns if
	the capture was a success or not... not that i have ever seen ob_start fail.
	//*/

		// don't allow obception.
		if(!$this->Started)
		$this->Started = ob_start();

		return $this->Started;
	}

	public function
	Stop($keep=true) {
	/*//
	@return mixed
	@argv boolean KeepBuffer default true
	stop capturing stdout. if the append argument is true it will throw the
	caught data into the storage array, else it will return and discard it.
	//*/

		// nothing if we haven't started.
		if(!$this->Started) return false;

		// else fetch the buffer.
		$this->Started = false;
		$stdout = ob_get_clean();

		// allow things to filter this content.
		Ki::Flow('surface-stdout',[&$stdout]);

		// append it if we elected to keep it.
		if($keep) {
			$this->Storage['stdout'] .= $stdout;
			return true;
		}

		// else return it and forget it.
		return $stdout;
	}

	public function
	Render($return=false) {
	/*//
	@return boolean
	begin the rendering operation using the full page template.
	//*/

		// flag this as called.
		$this->Rendered = true;

		// fetch whatever is still hanging on in the buffer.
		$this->Stop(true);

		// check if we had decided on a theme yet.
		if(!$this->Theme)
		$this->Theme = Nether\Option::Get('surface-theme');

		// determine the template file to use.
		if(!($template = $this->GetThemeFile('design.phtml')))
		throw new Exception("error opening {$template} for {$this->Theme}");

		// notification of beginning a render process.
		Nether\Ki::Flow('surface-render-init',[$this],FALSE);

		// run through the framework settings to generate some common meta data
		// like page title if the data hasn't already been defined.
		$this->PrepareTitle();
		$this->PrepareKeywords();
		$this->PrepareDescription();

		////////
		////////

		ob_start();
		call_user_func(function($__filename,$__scope){
			extract($__scope); unset($__scope);
			require($__filename);
		},$template,$this->GetRenderScope());

		if(!$return) {
			// print it out if we didn't want it back.
			echo ob_get_clean();
			return;
		} else {
			// hand it back if we wanted it.
			return ob_get_clean();
		}
	}

	///////////////////////////////////////////////////////////////////////////
	// metadata methods ///////////////////////////////////////////////////////

	/*// these methods will use the application configuration to generate some
	common meta data that is useful for webpages. //*/

	protected function
	PrepareTitle() {
	/*//
	generate or modify a page-title value.
	//*/

		if($this->Get('page-title'))
		$this->PrepareTitle_FromExisting();

		else
		$this->PrepareTitle_FromNothing();

		return;
	}

	protected function
	PrepareTitle_FromNothing() {
	/*//
	and from the ashes will arise a new page title. if our view or app has
	not yet described a page title then attempt to generate one if we have
	other data like app name and description set.
	//*/

		// no name, no branding.
		if(!Option::Get('surface-title-brand') || !Option::Get('app-name'))
		return $this;

		// if we have a description lets use it too.
		if(Option::Get('app-short-desc'))
		$this->Set('page-title',sprintf(
			'%s - %s',
			Option::Get('app-name'),
			Option::Get('app-short-desc')
		));

		// else just use the app name.
		else
		$this->Set('page-title',Option::Get('app-name'));

		return $this;
	}

	protected function
	PrepareTitle_FromExisting() {
	/*//
	append the site name if enabled and defined to the page title that
	was generated at some point by the app.
	//*/

		if(!Option::Get('surface-title-brand') || !Option::Get('app-name'))
		return $this;

		$this->Set('page-title',sprintf(
			'%s - %s',
			$this->Get('page-title'),
			Option::Get('app-name')
		));

		return $this;
	}

	protected function
	PrepareKeywords() {
	/*//
	generate a page-keywords if one has not yet been defined.
	//*/

		// if the app has already defined keywords then do not overwite them.
		if($this->Get('page-keywords'))
		return $this;

		// use the app keywords if defined.
		if(Option::Get('app-keywords'))
		$this->Set('page-keywords',Option::Get('app-keywords'));

		return $this;
	}

	protected function
	PrepareDescription() {
	/*//
	generate a page-desc if one has not yet been defined.
	//*/

		// if no description is set, attempt to get one from the application
		// configuration.
		if(!$this->Get('page-desc') && Option::Get('app-long-desc'))
		$this->Set('page-desc',Option::Get('app-long-desc'));

		return;
	}

	////////////////////////////////////////////////////////////////////////////
	// new area api ////////////////////////////////////////////////////////////

	public function
	GetArea($which) {
	/*//
	@argv string AreaFileRequest
	@return string
	attempt to fetch the result of the specified area file. it takes a string
	to the requested area relative to the current theme. it can also be
	prefixed with a theme stack with colons to customise which theme this
	request comes from.

	* index/home
	* alt:index/home
	* alt1:alt2:index/home

	with a technically infinite number of stacks. throws an exception if no
	files were found to handle the surface area.
	//*/

		$stack = explode(':',$which);
		$area = array_pop($stack);

		$filename = $this->GetThemeFile(
			"area/{$area}.phtml",
			$stack
		);

		if(!$filename)
		throw new Exception("no surface area matching {$which} could be located.");

		// notification of beginning a render process.
		Nether\Ki::Flow('surface-render-init',[$this],FALSE);

		////////
		////////

		ob_start();
		call_user_func(function($__filename,$__scope){
			extract($__scope); unset($__scope);
			require($__filename);
		},$filename,$this->GetRenderScope());
		return ob_get_clean();
	}

	public function
	ShowArea($which) {
	/*//
	@argv string AreaFileRequest
	@return self
	wraps the GetArea method for instant printign.
	//*/

		echo $this->GetArea($which);
		return $this;
	}

	////////////////////////////////////////////////////////////////////////////
	// data storage api ////////////////////////////////////////////////////////

	public function
	Define($Key,$Val) {
	/*//
	@date 2017-12-20
	add data in storage only if it does not yet exist.
	//*/

		if(!array_key_exists($Key,$this->Storage))
		$this->Storage[$Key] = $Val;

		return $this;
	}

	public function
	Get($what) {
	/*//
	@argv string Key
	@argv array(string Key, ...)
	@return mixed
	return the value stored in this surface object. if given a string the value
	associated with it is returned. if given an array of keys, an array of
	values associated with them will be returned instead.
	//*/

		if(is_string($what))
		return $this->Get_ByString($what);

		if(is_array($what))
		return $this->Get_ByArray($what);

		return NULL;
	}

	protected function
	Get_ByString($key) {
	/*//
	@argv string Key
	@return mixed
	return the data stored in the specified key.
	//*/

		if(array_key_exists($key,$this->Storage))
		return $this->Storage[$key];

		return NULL;
	}

	protected function
	Get_ByArray($list) {
	/*//
	@argv array KeyList
	@return array
	given an array of keys to lookup, return an array of data
	indexed by those same keys.
	//*/

		$return = [];

		foreach($list as $key)
		$return[$key] = $this->Get_ByString($key);

		return $return;
	}

	public function
	Set($what,$value=null) {
	/*//
	@argv string Key, Mixed Value
	@argv array(string Key => mixed Value, ...)
	@return self
	sets values in the surface storage. can take a string key and value, or an
	associative array of multiple keys and values to set.
	//*/

		if(is_string($what))
		return $this->Set_ByString($what,$value);

		if(is_array($what))
		return $this->Set_ByArray($what);

		return $this;
	}

	protected function
	Set_ByString($key,$val) {
	/*//
	@argv string Key, mixed Val
	@return self
	//*/

		$this->Storage[$key] = $val;
		return $this;
	}

	protected function
	Set_ByArray($data) {
	/*//
	@argv array Dataset
	@return self
	//*/

		foreach($data as $key => $val)
		$this->Set_ByString($key,$val);

		return $this;
	}

	public function
	Show($key,$safety=true) {
	/*//
	@argv string Key
	@return self
	echo the data under the selected key.
	//*/

		if(array_key_exists($key,$this->Storage)) {
			if($safety) echo htmlentities($this->Storage[$key]);
			else echo $this->Storage[$key];
		}

		return $this;
	}

	////////////////
	////////////////

	public function
	GetRenderScope() {
	/*//
	@return array
	allow other libraries to attach data to the render system to create a
	variable to be accessable within theme templates. the scope is an
	associative array passed around by reference. in the theme file it will
	extract the array into variables.
	//*/

		$scope = ['surface'=>$this];
		Ki::Flow(
			'surface-render-scope',
			[&$scope]
		);

		return $scope;
	}

	////////////////
	////////////////

	public function
	GetThemeFile($name,$stack=null) {
	/*//
	@argv string Filename
	@argv string Filename, string StackDefine
	@argv string Filename, array StackList
	@return string or false.
	run through the theme stack and attempt to locate a file that matches the
	request. if found it returns the full filepath to that file - if not then
	it returns boolean false.
	//*/

		// if we passed a stacked request handle it. else assume the stack
		// was passed explictly in the stack argument already.
		if(strpos($name,':') !== false) {
			$stack = explode(':',$name);
			$name = array_pop($stack);
		}

		foreach($this->GetThemeStack($stack) as $theme) {
			$filename = sprintf(
				'%s/%s/%s',
				$this->ThemeRoot,
				$theme,
				$name
			);

			// if this theme file was not found pray continue.
			if(!file_exists($filename) || !is_readable($filename))
			continue;

			// else it seems valid enough so use it.
			return $filename;
		}

		return false;
	}

	public function
	GetThemeStack($input=null) {
	/*//
	@argv string ThemeStackSpecification
	@argv array ThemeStackList
	@return array
	if given a string it will split the string on colons to generate the
	input list of the theme stack. this is how stacks will be custom
	selected by the area method. if given an array then that is just it.
	it returns a list of all the themes to check for requested files.
	//*/

		if(is_string($input)) {
			// accept a string:like:this for custom stacking.
			$stack = explode(':',$input);
		}
		elseif(is_array($input)) {
			// accept a straight array.
			$stack = $input;
		}
		else {
			// else start with an empty slate.
			$stack = [];
		}

		// append the configured theme.
		$stack[] = $this->Theme;

		// append the default theme stack.
		if(is_array(Option::Get('surface-theme-stack'))) {
			$stack = array_merge(
				$stack,
				Option::Get('surface-theme-stack')
			);
		}
		elseif(is_string(Option::Get('surface-theme-stack'))) {
			$stack[] = Option::Get('surface-theme');
		}

		// and return the stack.
		return $stack;
	}

	public function
	GetThemeURI($input) {
	/*//
	@argv string Input
	@return string
	prints or returns the string at the end of the surface uri. useful for
	linking to theme resources. accepts theme stacking to the point where
	you can overload the theme, but we will not test that the file exists
	in this case, so it will just be from the top of the stack.
	//*/

		$stack = explode(':',$input);
		$file = array_pop($stack);

		$stack = $this->GetThemeStack($stack);

		return sprintf(
			'/%s/%s/%s',
			trim(Option::Get('surface-theme-path'),'/'),
			$stack[0],
			$file
		);
	}

	///////////////////////////////////////////////////////////////////////////
	// deprecated / backwards compat crap /////////////////////////////////////

	public function
	Area($input,$return=false) {
	/*//
	@argv string Area, bool ShouldReturn default false
	@return string or null
	@deprecated
	this function exists for backwards compat and is basically a binary alias
	to the GetArea and ShowArea methods.
	//*/

		if(!$return) return $this->ShowArea($input);
		else return $this->GetArea($input);
	}

}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\browser;

use Yii;

/**
 * HandlerObjects [[@doctodo class_description:cascade\components\web\browser\HandlerObjects]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class HandlerObjects extends \canis\web\browser\Handler
{
    /**
     * @var [[@doctodo var_type:bundleClass]] [[@doctodo var_description:bundleClass]]
     */
    public $bundleClass = 'cascade\components\web\browser\Bundle';
    /**
     * @var [[@doctodo var_type:_dataSource]] [[@doctodo var_description:_dataSource]]
     */
    protected $_dataSource;

    /**
     * Get data source.
     *
     * @return [[@doctodo return_type:getDataSource]] [[@doctodo return_description:getDataSource]]
     */
    public function getDataSource()
    {
        if (is_null($this->_dataSource)) {
            $typeItem = Yii::$app->collectors['types']->getOne($this->instructions['type']);
            if (!$typeItem || !($type = $typeItem->object)) {
                return $this->_dataSource = false;
            }
            $primaryModel = $type->primaryModel;
            if (isset($this->instructions['parent'])) {
                $registryClass = Yii::$app->classes['Registry'];
                $object = $registryClass::getObject($this->instructions['parent']);
                if (!$object) {
                    return $this->_dataSource = false;
                }
                $this->_dataSource = $object->queryChildObjects($primaryModel, [], []);
            } else {
                $this->_dataSource = $primaryModel::find();
            }
            $dummyModel = new $primaryModel();
            $sortOptions = array_values($dummyModel->sortOptions);
            if ($this->filterQuery) {
                $primaryModel::simpleSearchTermQuery($this->_dataSource, $this->filterQuery);
            } elseif (isset($sortOptions[0])) {
                $this->_dataSource->orderBy($sortOptions[0]);
            }
        }

        return $this->_dataSource;
    }

    /**
     * @inheritdoc
     */
    public function getTotal()
    {
        if (!$this->dataSource) {
            return false;
        }

        return $this->dataSource->count();
    }

    /**
     * @inheritdoc
     */
    public function getItems()
    {
        $instructions = $this->instructions;
        if (!$this->dataSource) {
            return false;
        }
        $dataSource = clone $this->dataSource;
        $dataSourceClass = $dataSource->modelClass;
        $dataSource->attachBehaviors($dataSourceClass::queryBehaviors());
        if (!$this->filterQuery) {
            $dataSource->limit($this->bundle->limit);
            $dataSource->offset($this->bundle->offset);
        }
        $items = [];
        foreach ($dataSource->all() as $object) {
            $items[] = [
                'type' => 'object',
                'objectType' => $object->objectType->systemId,
                'id' => $object->primaryKey,
                'descriptor' => $object->descriptor,
                'subdescriptor' => $object->primarySubdescriptor,
                'hasChildren' => !empty($object->objectTypeItem->children),
                'isSelectable' => $instructions['modules'] === false || in_array($object->objectType->systemId, $instructions['modules']),
            ];
        }

        return $items;
    }
}


<?php

namespace ArtaxServiceBuilder\Service;

use Amp\Artax\Response;
use ArtaxServiceBuilder\Service\Link;

/**
 * Class GithubPaginator
 *
 * Utility class for extracting links from RFC 5988 headers. This class may be usable
 * as a generic RFC 5988 parser, but it has a specific name for now until I can check
 * other APIs that use RFC 5988.
 *
 * @package ArtaxServiceBuilder\Service
 */
class GithubPaginator {

    public $earliestPage = null;
    public $furthestPage = null;
    public $nextPage = null;

    public $urlStub = null;

    public $firstLink = null;
    public $previousLink = null;
    public $nextLink = null;
    public $lastLink = null;

    const FIRST     = 'first';  //first	Shows the URL of the first page of results.
    const PREVIOUS  = 'prev';   //prev	Shows the URL of the immediate previous page of results.
    const NEXT      = 'next';   //next	Shows the URL of the immediate next page of results.
    const LAST      = 'last';   //last	Shows the URL of the last page of results.

    /** @var \ArtaxServiceBuilder\Service\Link[] */
    public $links = [];

    private static $linkTypes = [
        self::FIRST,
        self::PREVIOUS,
        self::NEXT,
        self::LAST
    ];

    /**
     * We may need to re-order or sanity check the results of paging,
     * so list the order things should be in. Obviously the first link can be
     * equal to the previous link
     * @var array
     */
    public static $typeOrder = [
        self::FIRST => 0,
        self::PREVIOUS => 1,
        self::NEXT => 3,
        self::LAST => 4
    ];

    /**
     * @param array $linkHeaders
     */
    public function __construct(array $linkHeaders) {
        $this->parseLinksHeaders($linkHeaders);

        if (isset($this->links[self::FIRST])) {
            $this->firstLink = $this->links[self::FIRST];
        }
        if (isset($this->links[self::PREVIOUS])) {
            $this->previousLink = $this->links[self::PREVIOUS];
        }
        if (isset($this->links[self::NEXT])) {
            $this->nextLink = $this->links[self::NEXT];
        }
        if (isset($this->links[self::LAST])) {
            $this->lastLink = $this->links[self::LAST];
        }

        $this->makeDramaticAssumptionsAboutLinks($this->links);
    }

    /**
     * @return Link[]
     */
    public function getLinks() {
        return $this->links;
    }

    /**
     * @param $page
     * @return string
     */
    public function getURLForPage($page) {
        $page = intval($page);
        return $this->urlStub.$page;
    }

    /**
     * @return array
     */
    public function getPageRange() {
        if ($this->earliestPage && $this->furthestPage) {
            return [$this->earliestPage, $this->furthestPage];
        }

        return [];
    }

    /**
     * Returns an iterator of the remaining pages if both
     * $nextPage and $furthestPage are set, otherwise returns false
     */
    function getRemainingPages() {
        if ($this->nextPage !== null &&
            $this->furthestPage !== null) {
            return $this->getPages($this->nextPage, $this->furthestPage, $this->urlStub);
        }

        return false;
    }

    /**
     *
     *
     *
     * @return array|bool An array of URI strings on success or false on failure.
     */
    function getAllKnownPages() {
        if ($this->earliestPage !== null &&
            $this->furthestPage !== null) {
            return $this->getPages($this->earliestPage, $this->furthestPage, $this->urlStub);
        }

        return false;
    }

    /**
     * Generates an array of the URIs for a set of pages.
     * @param $startPage
     * @param $endPage
     * @param $urlStub
     * @return array
     */
    public function getPages($startPage, $endPage, $urlStub) {
        $pages = [];
        //TODO yield this array - after upgrading to php 5.5
        for($x=$startPage ; $x<=$endPage ; $x++) {
            $pages[] = $urlStub.$x;
        }

        return $pages;
    }

    /**
     * @param Response $response
     * @return GithubPaginator|null
     */
    public static function constructFromResponse(Response $response) {
        //TODO - make this not nullable
        if ($response->hasHeader('Link') == false) {
            return null;
        }

        $linkHeaders = $response->getHeader('Link');
        $instance = new self($linkHeaders);

        return $instance;
    }

    /**
     * Extract the link header(s) as parse the RFC 5988 style links from them.
     * fyi RFC 5988 is a terrible idea. It means to cache a response, you now need to
     * cache both the body data return as well as the headers.
     * @return \ArtaxServiceBuilder\Service\Link[]
     */
    public function parseLinksHeaders(array $linkHeaders) {

        $links = array();

        foreach ($linkHeaders as $linkHeader) {
            $linkInfoArray = \HTTP2\HTTP2::parseLinks($linkHeader);

            foreach ($linkInfoArray as $linkInfo) {
                $url = null;
                $description = null;

                if (isset($linkInfo['_uri']) == true) {
                    $url = $linkInfo['_uri'];
                }

                if (isset($linkInfo['rel']) == true) {
                    $relInfo = $linkInfo['rel'];
                    if (is_array($relInfo)) {
                        foreach ($relInfo as $linkType) {
                            $description = $linkType;
                        }
                    }
                }

                if ($url != null && $description != null) {
                    //Check that it's not a new type that we don't understand
                    if (in_array($description, self::$linkTypes)) {
                        $links[$description] = new Link($url, $description);
                    }
                }
            }
        }

        $this->links = $links;
    }

    /**
     * This is a stupid function and I feel bad writing it, but it's not my fault.
     * Github return information about what links are available in text in the rel
     * links.....which means we need to manually extract the information about
     * what pages are available by hand. Which sucks, as it just completely fragile
     * and makes dramatic assumptions about the URI that github has return to us
     * @param \ArtaxServiceBuilder\Service\Link[] $links
     */
    function makeDramaticAssumptionsAboutLinks(array $links) {

        $earliestKnownLink = null;
        $earliestType = null;

        $furthestKnownLink = null;
        $furthestType = null;

        $nextLink = null;

        if (isset($links[self::FIRST]) == true) {
            $earliestKnownLink = $links[self::FIRST];
            $earliestType = self::FIRST;
        }
        else if (isset($links[self::PREVIOUS]) == true) {
            $earliestKnownLink = $links[self::PREVIOUS];
            $earliestType = self::PREVIOUS;
        }
        else if (isset($links[self::NEXT]) == true) {
            $earliestKnownLink = $links[self::NEXT];
            $earliestType = self::NEXT;
        }

        if (isset($links[self::LAST]) == true) {
            $furthestKnownLink = $links[self::LAST];
            $furthestType = self::LAST;
        }
        else if (isset($links[self::NEXT]) == true) {
            $furthestKnownLink = $links[self::NEXT];
            $furthestType = self::NEXT;
            $nextLink = $links[self::NEXT];
        }
        else if (isset($links[self::PREVIOUS]) == true) {
            $furthestKnownLink = $links[self::PREVIOUS];
            $furthestType = self::PREVIOUS;
        }

        if (isset(self::$typeOrder[$furthestType]) &&
            isset(self::$typeOrder[$earliestType])) {
            if (self::$typeOrder[$furthestType] <
                self::$typeOrder[$earliestType]
            ) {
                //TODO - links are borked.
            }
        }

        $urlStub1 = null;
        $urlStub2 = null;

        if  ($earliestKnownLink) {
            if (preg_match('/(.*page=)(\d+)$/', $earliestKnownLink->url, $matches)) {
                $urlStub1 = $matches[1];
                $this->earliestPage = intval($matches[2]);
            }
        }

        if  ($furthestKnownLink) {
            if (preg_match('/(.*page=)(\d+)$/', $furthestKnownLink->url, $matches)) {
                $urlStub2 = $matches[1];
                $this->furthestPage = intval($matches[2]);
            }
        }

        if  ($nextLink) {
            if (preg_match('/(.*page=)(\d+)$/', $nextLink->url, $matches)) {
                $urlStub2 = $matches[1];
                $this->nextPage = intval($matches[2]);
            }
        }

        if ($urlStub1 && $urlStub2) {
            //TODO - what do we do when they don't match?
        }

        if ($urlStub1) {
            $this->urlStub = $urlStub1;
        }
        else if ($urlStub2) {
            $this->urlStub = $urlStub2;
        }
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\EventSystem\Listener\PageCollection;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\EventSystem\Event\PageCollection\SiteSavedEvent;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Class SiteSavedListener listens to SiteSavedEvent to update the whole assets from backend to production
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\EventSystem\Listener\Page
 */
class SiteSavedListener
{
    /**
     * @type \RedKiteCms\Configuration\ConfigurationHandler
     */
    private $configurationHandler;

    /**
     * Constructor
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public function __construct(ConfigurationHandler $configurationHandler)
    {
        $this->configurationHandler = $configurationHandler;
    }

    /**
     * Synchronizes the backend folder with the production one
     * @param \RedKiteCms\EventSystem\Event\PageCollection\SiteSavedEvent $event
     */
    public function onSiteSaved(SiteSavedEvent $event)
    {
        $fs = new Filesystem();
        $fs->mirror(
            $this->configurationHandler->uploadAssetsDir(),
            $this->configurationHandler->uploadAssetsDirProduction()
        );
    }
}


<?php
namespace cascade\components\helpers;

use canis\caching\Cacher;

/**
 * Gravatar [[@doctodo class_description:cascade\components\helpers\Gravatar]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Gravatar extends \emberlabs\gravatarlib\Gravatar
{
    /**
     * [[@doctodo method_description:test]].
     *
     * @param [[@doctodo param_type:email]] $email      [[@doctodo param_description:email]]
     * @param boolean                       $hash_email [[@doctodo param_description:hash_email]] [optional]
     *
     * @return [[@doctodo return_type:test]] [[@doctodo return_description:test]]
     */
    public function test($email, $hash_email = true)
    {
        $original = $this->getDefaultImage();
        $this->setDefaultImage(404);
        $url = htmlspecialchars_decode($this->get($email, $hash_email));
        $this->setDefaultImage($original);
        $cacheKey = ['testGravatar', $url];
        $cache = Cacher::get($cacheKey);
        if ($cache) {
            return $cache;
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        $data = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if (!$data || $httpCode !== 200) {
            $result = false;
        } else {
            $result = true;
        }
        Cacher::set($cacheKey, $result, 3600);

        return $result;
    }

    /**
     * [[@doctodo method_description:fetch]].
     *
     * @param [[@doctodo param_type:email]] $email      [[@doctodo param_description:email]]
     * @param boolean                       $hash_email [[@doctodo param_description:hash_email]] [optional]
     *
     * @return [[@doctodo return_type:fetch]] [[@doctodo return_description:fetch]]
     */
    public function fetch($email, $hash_email = true)
    {
        $url = $this->get($email, $hash_email);
        $cacheKey = md5('gravatar-' . $url);
        $cache = Yii::$app->fileCache->get($cacheKey);
        if ($cache) {
            return unserialize($cache);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        $data = curl_exec($curl);
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if (!$data || $httpCode !== 200) {
            $data = false;
        }
        Yii::$app->fileCache->set($cacheKey, serialize($data), 3600);

        return $data;
    }
}


<?php

namespace ArtaxServiceBuilder\Service;

use Amp\Artax\Request;

class FlickrOauth1 extends \ArtaxServiceBuilder\Service\Oauth1 {
    /**
     * Decide whether the post fields should be added to the Oauth BaseString.
     * Flickr incorrectly add the post fields when the content type is 'multipart/form-data'. They should only be added when the content type is 'application/x-www-form-urlencoded'
     *
     * @param $request
     * @return bool Whether the post fields should be signed or not
     */

    public function shouldPostFieldsBeSigned(Request $request) {
        $returnValue = false;

        if ($request->hasHeader('Content-Type')) {
            $contentType = $request->getHeader('Content-Type');
            //TODO - not safe
            if ($contentType === 'application/x-www-form-urlencoded' ||
                $contentType === 'multipart/form-data') {
                $returnValue = true;
            }
        }

        // Don't sign POST fields if the request uses POST fields and no files
        $body = $request->getBody();

        if ($body instanceof \Amp\Artax\FormBody) {
            if ($body == 0) {
                $returnValue = false;
            }
        }

        return $returnValue;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Validator\Constraints;

use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelInterface\Repository\NodeRepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class CheckRoutePatternValidator
 */
class CheckRoutePatternValidator extends ConstraintValidator
{
    protected $nodeRepository;

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

    /**
     * Checks if the passed value is valid.
     *
     * @param NodeInterface $value The value that should be validated
     * @param Constraint    $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {
        $nodesSameRoute = $this->nodeRepository->findByParentAndRoutePattern(
            $value->getParentId(),
            $value->getRoutePattern(),
            $value->getNodeId(),
            $value->getSiteId()
        );
        if (0 < count($nodesSameRoute)) {
            $nodesSameRoute = current($nodesSameRoute);
            $message = $constraint->message;
            if (true === $nodesSameRoute->isDeleted()) {
                $message = $constraint->messageWitNodeDeleted;
            }
            $this->context->buildViolation($message, array("%nodeName%" => $nodesSameRoute->getName()))
                ->atPath('routePattern')
                ->addViolation();
        }
    }
}


<?php
namespace DasRed\Translation\Command\Executor\Log;

class ToExcel extends ToCsv
{

	/**
	 *
	 * @var int
	 */
	protected $currentLine = 1;

	/**
	 * @var \PHPExcel
	 */
	protected $excel;

	/**
	 * @var \PHPExcel_Writer_IWriter
	 */
	protected $writer;

	/**
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\Executor\Log\ToCsv::execute()
	 */
	public function execute()
	{
		parent::execute();

		$sheet = $this->getExcel()->getActiveSheet();

		$sheet->getStyle('A1')->getFont()->setBold(true);
		$sheet->getStyle('B1')->getFont()->setBold(true);
		$sheet->getStyle('C1')->getFont()->setBold(true);
		$sheet->getStyle('D1')->getFont()->setBold(true);
		$sheet->getStyle('E1')->getFont()->setBold(true);

		// auto size
		for ($column = 'A'; $column != 'F'; $column++)
		{
			$sheet->getColumnDimension($column)->setAutoSize(true);
		}

		$this->getWriter()->save($this->getArguments()[1]);

		return true;
	}

	/**
	 * @return int
	 */
	protected function getCurrentLine()
	{
		return $this->currentLine;
	}

	/**
	 * @return \PHPExcel
	 */
	protected function getExcel()
	{
		if ($this->excel === null)
		{
			$this->excel = new \PHPExcel();
			$this->excel->getProperties()->setCreator('dasred/translation');
			$this->excel->setActiveSheetIndex(0);

			$sheet = $this->excel->getActiveSheet()->setTitle(basename($this->getArguments()[0]));
		}

		return $this->excel;
	}

	/**
	 * @return PHPExcel_Writer_IWriter
	 */
	protected function getWriter()
	{
		if ($this->writer === null)
		{
			$this->writer = \PHPExcel_IOFactory::createWriter($this->getExcel(), 'Excel5');
		}

		return $this->writer;
	}

	/**
	 * @param int $currentLine
	 * @return self
	 */
	protected function setCurrentLine($currentLine)
	{
		$this->currentLine = $currentLine;

		return $this;
	}

	/**
	 *
	 * @param string $file
	 * @param int $lineNumber
	 * @param string $key
	 * @param string $locale
	 * @param int $count
	 * @return self
	 */
	protected function write($file, $lineNumber, $key, $locale, $count)
	{
		$sheet = $this->getExcel()->getActiveSheet();

		// labels
		$sheet->setCellValue('A' . $this->getCurrentLine(), $file)
			->setCellValue('B' . $this->getCurrentLine(), $lineNumber)
			->setCellValue('C' . $this->getCurrentLine(), $key)
			->setCellValue('D' . $this->getCurrentLine(), $locale)
			->setCellValue('E' . $this->getCurrentLine(), $count);

		$sheet->getStyle('B' . $this->getCurrentLine())->getNumberFormat()->setFormatCode('#,###,###,###');
		$sheet->getStyle('E' . $this->getCurrentLine())->getNumberFormat()->setFormatCode('#,###,###,###');

		return $this->setCurrentLine($this->getCurrentLine() + 1);
	}
}


<?php

namespace Scalify\PuppetMaster\Client;

use DateTime;

class Job
{
    const STATUS_CREATED = "created";
    const STATUS_QUEUED = "queued";
    const STATUS_DONE = "done";

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

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

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

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

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

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

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

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

    /** @var int */
    protected $duration;

    /** @var DateTime */
    protected $createdAt;

    /** @var DateTime */
    protected $startedAt;

    /** @var DateTime */
    protected $finishedAt;

    /**
     * Job constructor.
     *
     * @param array $data
     */
    public function __construct(array $data = [])
    {
        $this->fill($data);
    }

    /**
     * Fills the given data into the respective properties.
     *
     * @param array $data
     */
    protected function fill(array $data)
    {
        $this->uuid = $data["uuid"] ?: "";
        $this->status = $data["status"] ?: "";
        $this->code = $data["code"] ?: "";
        $this->modules = $data["modules"] ?: [];
        $this->vars = $data["vars"] ?: [];
        $this->error = $data["error"] ?: "";
        $this->logs = $data["logs"] ?: [];
        $this->results = $data["results"] ?: [];
        $this->duration = $data["duration"] ?: 0;
        $this->createdAt = $this->parseDate($data["created_at"]);
        $this->startedAt = $this->parseDate($data["started_at"]);
        $this->finishedAt = $this->parseDate($data["finished_at"]);
    }

    /**
     * @param string|null $dateTime
     *
     * @return DateTime|null
     */
    private function parseDate($dateTime)
    {
        if (empty($dateTime)) {
            return null;
        }

        return DateTime::createFromFormat(DateTime::RFC3339, $dateTime);
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            "uuid" => $this->uuid,
            "status" => $this->status,
            "code" => $this->code,
            "modules" => $this->modules,
            "vars" => $this->vars,
            "error" => $this->error,
            "logs" => $this->logs,
            "results" => $this->results,
            "duration" => $this->duration,
            "created_at" => $this->formatDate($this->createdAt),
            "started_at" => $this->formatDate($this->startedAt),
            "finished_at" => $this->formatDate($this->finishedAt),
        ];
    }

    private function formatDate(DateTime $dateTime): string
    {
        if ($dateTime === null) {
            return null;
        }

        return $dateTime->format(DateTime::RFC3339);
    }

    /**
     * @return string
     */
    public function getUUID(): string
    {
        return $this->uuid;
    }

    /**
     * @return string
     */
    public function getStatus(): string
    {
        return $this->status;
    }

    /**
     * @return string
     */
    public function getCode(): string
    {
        return $this->code;
    }

    /**
     * @return array
     */
    public function getModules(): array
    {
        return $this->modules;
    }

    /**
     * @return array
     */
    public function getVars(): array
    {
        return $this->vars;
    }

    /**
     * @return string
     */
    public function getError(): string
    {
        return $this->error;
    }

    /**
     * @return array
     */
    public function getLogs(): array
    {
        return $this->logs;
    }

    /**
     * @return array
     */
    public function getResults(): array
    {
        return $this->results;
    }

    /**
     * @return int
     */
    public function getDuration(): int
    {
        return $this->duration;
    }

    /**
     * @return DateTime
     */
    public function getCreatedAt(): DateTime
    {
        return $this->createdAt;
    }

    /**
     * @return DateTime
     */
    public function getStartedAt()
    {
        return $this->startedAt;
    }

    /**
     * @return DateTime
     */
    public function getFinishedAt()
    {
        return $this->finishedAt;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Client;

use Doctrine\Common\Collections\ArrayCollection;
use Dothiv\Bundle\ContentfulBundle\Exception\RuntimeException;
use PhpOption\Option;

class HttpClient implements HttpClientInterface
{
    /**
     * @var ArrayCollection
     */
    private $headers;

    /**
     * @var string|null
     */
    private $etag;

    /**
     * @var string
     */
    private $accessToken;

    /**
     * @var string
     */
    private $contentType;

    public function __construct($accessToken, $contentType = null)
    {
        $this->headers     = new ArrayCollection();
        $this->accessToken = $accessToken;
        $this->contentType = Option::fromValue($contentType)->getOrElse('application/vnd.contentful.delivery.v1+json');
    }

    /**
     * {@inheritdoc}
     */
    public function get($uri)
    {
        $opts = $this->buildOpts('GET');
        if ($this->etag != null) {
            $opts['http']['header'] .= "\n" . sprintf('If-None-Match: "%s"', $this->etag);
        }
        return $this->execute($uri, $opts);
    }

    /**
     * @param string $uri
     * @param array  $data
     *
     * @return string
     */
    function post($uri, array $data = null)
    {
        $opts = $this->buildOpts('POST');
        if ($data !== null) {
            $opts['http']['content'] = json_encode($data);
        }
        return $this->execute($uri, $opts);
    }

    /**
     * @param string $uri
     * @param array  $data
     *
     * @return string
     */
    function put($uri, array $data = null)
    {
        $opts = $this->buildOpts('PUT');
        if ($data !== null) {
            $opts['http']['content'] = json_encode($data);
        }
        return $this->execute($uri, $opts);
    }

    /**
     * @param string $uri
     *
     * @return string
     */
    function delete($uri)
    {
        $opts = $this->buildOpts('DELETE');
        return $this->execute($uri, $opts);
    }

    protected function execute($uri, $opts)
    {
        $context = stream_context_create($opts);
        $body    = file_get_contents($uri, false, $context);
        $status  = $http_response_header[0];
        list(, $statusCode,) = explode(' ', $status, 3);
        if (intval($statusCode) < 200 || intval($statusCode) > 299) {
            throw new RuntimeException(
                sprintf(
                    'Failed to fetch "%s": %s!',
                    $uri,
                    $status
                )
            );
        }
        $this->parseResponseHeader($http_response_header);
        return $body;
    }

    protected function parseResponseHeader(array $header)
    {
        foreach ($header as $hdr) {
            if (strpos($hdr, ':') === false) continue;
            list($k, $v) = explode(':', $hdr);
            $this->headers->set(strtolower(trim($k)), trim($v));
        }
    }

    /**
     * @param string $name
     *
     * @return string
     */
    function header($name)
    {
        return $this->headers->get($name);
    }

    /**
     * @param string $etag
     */
    function setEtag($etag)
    {
        $this->etag = $etag;
    }

    /**
     * @return ArrayCollection
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param string $method
     *
     * @return array
     */
    protected function buildOpts($method)
    {
        $opts = array(
            'http' =>
                array(
                    'method'        => $method,
                    'header'        => sprintf("Content-type: %s\n", $this->contentType) .
                        'Authorization: Bearer ' . $this->accessToken,
                    'ignore_errors' => true,
                )
        );
        return $opts;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: las
 * Date: 28/06/2016
 * Time: 22:22
 */
namespace Venus\lib\Request;

class Server implements RequestInterface
{
    /**
     * get parameter
     * @param string $name
     * @param string $default
     * @return string
     */
    public function get(string $name, string $default = null)
    {
        if (isset($_SERVER[$name]) && $_SERVER[$name] != '') {
            return $_SERVER[$name];
        } else if ($default !== null) {
            return $default;
        }
    }
}


<?php
namespace Clusterpoint\Query;

use Closure;
use Clusterpoint\Instance\Service;
use Clusterpoint\Contracts\ConnectionInterface;

/**
 *
 * Provides query builder functionality.
 *
 * @category   Clusterpoint 4.0 PHP Client API
 * @package    clusterpoint/php-client-api-v4
 * @copyright  Copyright (c) 2016 Clusterpoint (http://www.clusterpoint.com)
 * @author     Marks Gerasimovs <marks.gerasimovs@clusterpoint.com>
 * @license    http://opensource.org/licenses/MIT    MIT
 */
abstract class Builder
{
    /**
     * The stdClass with scope for query parametrs.
     *
     * @var \stdClass
     */
    protected $scope;

    /**
     * The stdClass with scope of connection access points.
     *
     * @var \stdClass
     */
    protected $connection;

    /**
     * Set connection access points.
     *
     * @param  \stdClass  $connection
     * @return void
     */
    abstract public function __construct(ConnectionInterface $connection);

	public function listWords($word, $field = null)
	{
		$this->where('word','==',$word);

		if (!is_null($field)){
			$this->scope->listWordsField = $field;
		}
		else {
			$this->scope->listWordsField = '';
		}

		return $this;
	}

	public function alternatives($word, $field = null)
	{
		$this->where('word','==',$word);

		if (!is_null($field)){
			$this->scope->alternativesField = $field;
		}
		else {
			$this->scope->alternativesField = '';
		}

		return $this;
	}

	public function getStatus()
	{
		return Parser::getStatus($this->connection);
	}

    /**
     * Add a basic where clause to the query.
     *
     * @param  string  $field
     * @param  string  $operator
     * @param  mixed   $value
     * @param  string  $logical
     * @return $this
     */
    public function where($field, $operator = null, $value = null, $logical = '&&')
    {
        if ($field instanceof Closure) {
            $this->scope->where .= $this->scope->where=='' ? ' (' : $logical.' (';
            call_user_func($field, $this);
            $this->scope->where .= ') ';
        } else {
            $logical = (strlen($this->scope->where) <=1 || substr($this->scope->where, -1)=='(') ? '' : $logical;
            $this->scope->where .= Parser::where($field, $operator, $value, $logical);
        }
        return $this;
    }

    /**
     * Add an "or where" clause to the query.
     *
     * @param  string  $field
     * @param  string  $operator
     * @param  mixed   $value
     * @return $this
     */
    public function orWhere($field, $operator = null, $value = null)
    {
        return $this->where($field, $operator, $value, '||');
    }

    /**
     * Set Select parametr to the query.
     *
     * @param  mixed  $select
     * @return $this
     */
    public function select($select = null)
    {
        $this->scope->select = Parser::select($select);
        return $this;
    }

    /**
     * Set Limit parametr to the query.
     *
     * @param  mixed  $limit
     * @return $this
     */
    public function limit($limit)
    {
        $this->scope->limit = Parser::limit($limit);
        return $this;
    }

    /**
     * Set Offset parametr to the query.
     *
     * @param  mixed  $offset
     * @return $this
     */
    public function offset($offset)
    {
        $this->scope->offset = Parser::offset($offset);
        return $this;
    }

    /**
     * Add "Order by" clause to the query.
     *
     * @param  string  $field
     * @param  string  $order
     * @return $this
     */
    public function orderBy($field, $order = null)
    {
        $this->scope->orderBy[] = Parser::orderBy($field, $order);
        return $this;
    }

    /**
     * Add "Group by" clause to the query.
     *
     * @param  string  $field
     * @return $this
     */
    public function groupBy($field)
    {
        $this->scope->groupBy[] = Parser::groupBy($field);
        return $this;
    }

	public function join($type)
	{
		$this->scope->join = $type;
		return $this;
	}

    /**
     * Set prepending text to the query.
     *
     * @param  string  $prepend
     * @return $this
     */
    public function prepend($prepend)
    {
        $this->scope->prepend .= $prepend.' ';
        return $this;
    }

    /**
     * Retrieve document by it's "_id" field.
     *
     * @param  string  $id
     * @return \Clusterpoint\Response\Single
     */
    public function find($id)
    {
        return Parser::find($id, $this->connection);
    }

    /**
     * Retrieve first document from the list executing the builded query.
     *
     * @return \Clusterpoint\Response\Single
     */
    public function first()
    {
        $this->scope->limit = 1;
        $this->scope->offset = 0;
        return $this->get(null);
    }

    /**
     * Retrieve batch of the documents executing the builded query.
     *
     * @param  boolean  $multiple
     * @return \Clusterpoint\Response\Batch
     */
    public function get($multiple = true)
    {
        $scope = $this->scope;
        return Parser::get($scope, $this->connection, $multiple);
    }

    /**
     * Get batch of documents executing the string passed as parametr.
     *
     * @param  string  $raw
     * @return \Clusterpoint\Response\Batch
     */
    public function raw($raw)
    {
        return Parser::raw($raw, $this->connection);
    }

    /**
     * Delete document by it's "_id" field.
     *
     * @param  string  $id
     * @return \Clusterpoint\Response\Single
     */
    public function delete($id = null)
    {
        return Parser::delete($id, $this->connection);
    }

    /**
     * Delete documents by "_id" fields.
     *
     * @param  $ids array
     * @return \Clusterpoint\Response\Single
     */
    public function deleteMany(array $ids = array())
    {
        return Parser::deleteMany($ids, $this->connection);
    }

    /**
     * Insert one document.
     *
     * @param  mixed  $document
     * @return \Clusterpoint\Response\Single
     */
    public function insertOne($document)
    {
        return Parser::insertOne($document, $this->connection);
    }

    /**
     * Insert batch of documents.
     *
     * @param  mixed  $document
     * @return \Clusterpoint\Response\Single
     */
    public function insertMany($document)
    {
        return Parser::insertMany($document, $this->connection);
    }

    /**
     * Update document by it's "_id".
     *
     * @param  string  $id
     * @param  mixed  $document
     * @return \Clusterpoint\Response\Single
     */
    public function update($id, $document  = null)
    {
        return Parser::update($id, $document, $this->connection);
    }

    /**
     * Replace document by it's "_id".
     *
     * @param  string  $id
     * @param  mixed  $document
     * @return \Clusterpoint\Response\Single
     */
    public function replace($id, $document = null)
    {
        return Parser::replace($id, $document, $this->connection);
    }

    /**
     * Start transaction.
     *
     * @return \Clusterpoint\Instance\Service
     */
    public function transaction()
    {
        $transaction_id = Parser::beginTransaction($this->connection);
        $connection = clone $this->connection;
        $connection->transactionId = $transaction_id;
        return new Service($connection);
    }

    /**
     * Rollback transaction.
     *
     * @return \Clusterpoint\Response\Single
     */
    public function rollback()
    {
        return Parser::rollbackTransaction($this->connection);
    }

    /**
     * Commit transaction.
     *
     * @return \Clusterpoint\Response\Single
     */
    public function commit()
    {
        return Parser::commitTransaction($this->connection);
    }

    /**
     * Reset query scope values to defaults.
     *
     * @return $this
     */
    public function resetQuery()
    {
        $this->scope->resetSelf();
        return $this;
    }

    /**
     * Get scope value by clause
     *
     * @return $scope
     */
    public function getQuery()
    {
        return Parser::get($this->scope, $this->connection, true, true);
    }
    /**
     * Get all available Methods
     *
     * @return $scope
     */
    public function availableMethods(){
        return get_class_methods($this);
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * ServerServiceProvider.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015
 *
 * @see      https://github.com/overtrue/wechat
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\Encryption\Encryptor;
use EasyWeChat\Server\Guard;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class ServerServiceProvider.
 */
class ServerServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['encryptor'] = function ($pimple) {
            return new Encryptor(
                $pimple['config']['app_id'],
                $pimple['config']['token'],
                $pimple['config']['aes_key']
            );
        };

        $pimple['server'] = function ($pimple) {
            $server = new Guard($pimple['config']['token']);

            $server->debug($pimple['config']['debug']);

            $server->setEncryptor($pimple['encryptor']);

            return $server;
        };
    }
}


<?php
namespace eMacros\Runtime\Argument;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;

class ArgumentGet implements Applicable {
	/**
	 * Argument index to obtain
	 * @var int
	 */
	public $index;

	public function __construct($index = null) {
		$this->index = $index;
	}

	/**
	 * Obtains argument at given index
	 * Usage: (%0) (% _num)
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (is_null($this->index)) {
			if (count($arguments) == 0) throw new \BadFunctionCallException("ArgumentGet: No index specified.");
			$index = intval($arguments[0]->evaluate($scope));
		}
		else $index = $this->index;

		if (!array_key_exists($index, $scope->arguments))
			throw new \UnexpectedValueException(sprintf("ArgumentGet: No parameter found at index %d.", $index));
		return $scope->arguments[$index];
	}
}
?>


<?php

namespace Chill\PersonBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use Chill\PersonBundle\Entity\Person;

class PersonToIdTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    private $om;

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

    /**
     * Transforms an object (issue) to a string (id).
     *
     * @param  Issue|null $issue
     * @return string
     */
    public function transform($issue)
    {
        if (null === $issue) {
            return "";
        }

        return $issue->getId();
    }

    /**
     * Transforms a string (id) to an object (issue).
     *
     * @param  string $id
     *
     * @return Issue|null
     *
     * @throws TransformationFailedException if object (issue) is not found.
     */
    public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }

        $issue = $this->om
            ->getRepository('ChillPersonBundle:Person')
            ->findOneBy(array('id' => $id))
        ;

        if (null === $issue) {
            throw new TransformationFailedException(sprintf(
                'An issue with id "%s" does not exist!',
                $id
            ));
        }

        return $issue;
    }
}
?>


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace Controller\Page;

use RedKiteCms\Rendering\Controller\Page\ApprovePageController as BaseApprovePageController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to approve a page contribution
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Seo
 */
class ApprovePageController extends BaseApprovePageController
{
    /**
     * Approve page contribution action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function approveAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "page_manager" => $app["red_kite_cms.page_manager"],
            "username" => $this->fetchUsername($app["security"], $app["red_kite_cms.configuration_handler"]),
        );

        return parent::approve($options);
    }
}


<?php namespace ForeverPHP\Cache;

use ForeverPHP\Cache\CacheInterface;

/**
 * Realiza cache con archivos en disco, es la forma basica del cache.
 *
 * @author  Daniel Nuñez S. <dnunez@emarva.com>
 * @since   Version 0.4.0
 */
class FileCache implements CacheInterface {
    /**
     * Ruta del directorio a usar para el cache.
     *
     * @var string
     */
    private $location;

    public function __construct($location) {
        $this->location = $location;

        // Verifica si existe el directorio del cache, si no se crea
        if (!file_exists($this->location)) {
            mkdir($this->location, 0777);
        }
    }

    /**
     * Valida si existe el archivo en el directorio cache.
     *
     * @param  string $key
     * @return boolean
     */
    public function exists($key) {
        $filenameCache = $this->location . DS . $key;

        if (file_exists($filenameCache)) {
            return true;
        }

        return false;
    }

    /**
     * Almacena un nuevo archivo en cache.
     *
     * @param string $key
     * @param string $value
     */
    public function set($key, $value) {
        try {
            $filenameCache = $this->location . DS . $key;

            // Escribe el archivo en cache
            file_put_contents($filenameCache, $value);
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    public function get($key) {

    }

    public function remove($key) {

    }
}


<?php

abstract class SDIS62_Model_Mapper_WebService_Abstract implements SDIS62_Model_Mapper_Interface
{
    /**
     * @var SDIS62_Service_Generic
     */
    protected $webservice;

    /**
     * Définition du webservice
     *
     * @param SDIS62_Service_Generic $service
     * @return SDIS62_Model_Mapper_WebService_Abstract Interface fluide
     * @throws Zend_Exception Si l'objet n'est pas une instance de SDIS62_Service_Generic
     */
    public function setWebService($service)
    {
        if (!$service instanceof SDIS62_Service_Generic)
        {
            throw new Zend_Exception("L'objet n'est pas une instance de type SDIS62_Service_Generic");
        }

        $this->service = $service;

        return $this;
    }

    /**
     * Récupération du webservice
     * Si le webservice devant être retourné n'est pas du type SDIS62_Service_Generic, on le transforme automatiquement
     *
     * @return Zend_Db_Table_Abstract|null
     */
    public function getWebService()
    {
        if (is_string($this->webservice))
        {
            $this->setWebService($this->webservice);
        }

        return $this->webservice;
    }

    /**
     * Récupération, construction, et envoi d'une entité correspondant à l'id donnée
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param int $id
     * @return SDIS62_Model_Proxy_Abstract|null
     */
    abstract public function fetchById($id);

    /**
     * Récupération, construction, et envoi d'une entité correspondant aux critères spécifiés
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param string|array $where Optionnel
     * @param string|array $order Optionnel
     * @param int $offset Optionnel
     * @return SDIS62_Model_Proxy_Abstract
     */
    abstract public function fetchRow($where = null, $order = null, $offset = null);

    /**
     * Récupération, construction, et envoi d'une liste d'entités correspondants aux critères spécifiés
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param string|array $where Optionnel
     * @param string|array $order Optionnel
     * @param int $count Optionnel
     * @param int $offset Optionnel
     * @return array
     */
    abstract public function fetchAll($where = null, $order = null, $count = null, $offset = null);

    /**
     * On persiste les données de l'entité (sauvegarde)
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param SDIS62_Model_Proxy_Abstract $entity Paramètre passé en référence
     */
    abstract public function save(SDIS62_Model_Proxy_Abstract &$entity);

    /**
     * Suppression des données d'une entité identifiée
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param int $id
     * @return boolean
     */
    abstract public function delete($id);

    /**
     * Construction et/ou hydratation de l'entité liée au mapper
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param array $data
     * @return SDIS62_Model_Proxy_Abstract
     */
    abstract protected function createEntity(array $data);
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\widgets;

use canis\base\collector\CollectedObjectTrait;
use Yii;

/**
 * Item [[@doctodo class_description:cascade\components\web\widgets\Item]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Item extends \canis\base\collector\Item implements \canis\base\collector\CollectedObjectInterface
{
    use CollectedObjectTrait;

    /**
     * @var [[@doctodo var_type:name]] [[@doctodo var_description:name]]
     */
    public $name;
    /**
     * @var [[@doctodo var_type:widget]] [[@doctodo var_description:widget]]
     */
    public $widget;
    /**
     * @var [[@doctodo var_type:tab]] [[@doctodo var_description:tab]]
     */
    public $tab;
    /**
     * @var [[@doctodo var_type:_priority]] [[@doctodo var_description:_priority]]
     */
    public $_priority = 0;
    /**
     * @var [[@doctodo var_type:locations]] [[@doctodo var_description:locations]]
     */
    public $locations = [];
    /**
     * @var [[@doctodo var_type:_section]] [[@doctodo var_description:_section]]
     */
    protected $_section;
    /**
     * @var [[@doctodo var_type:settings]] [[@doctodo var_description:settings]]
     */
    public $settings = [];

    /**
     * @inheritdoc
     */
    public function getObject()
    {
        if (is_null($this->widget)) {
            return;
        }
        $object = Yii::createObject($this->widget);
        $object->settings = $this->settings;
        $object->collectorItem = $this;

        return $object;
    }

    /**
     * Get section.
     *
     * @param [[@doctodo param_type:parent]] $parent   [[@doctodo param_description:parent]] [optional]
     * @param array                          $settings [[@doctodo param_description:settings]] [optional]
     *
     * @return [[@doctodo return_type:getSection]] [[@doctodo return_description:getSection]]
     */
    public function getSection($parent = null, $settings = [])
    {
        $settings = array_merge($this->settings, $settings);
        if (is_null($this->_section)) {
            $this->_section = $this->owner->getSection($parent, $settings);
        }
        if (is_callable($this->_section) || (is_array($this->_section) && !empty($this->_section[0]) && is_object($this->_section[0]))) {
            return $this->evaluateExpression($this->_section, ['parent' => $parent, 'settings' => $settings]);
        }

        return $this->_section;
    }

    /**
     * Set section.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setSection($value)
    {
        $this->_section = $value;
    }

    /**
     * Set priority.
     *
     * @param [[@doctodo param_type:priority]] $priority [[@doctodo param_description:priority]]
     */
    public function setPriority($priority)
    {
        $this->_priority = $priority;
    }

    /**
     * Get priority.
     *
     * @return [[@doctodo return_type:getPriority]] [[@doctodo return_description:getPriority]]
     */
    public function getPriority()
    {
        return $this->_priority;
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\HWIOAuth;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\AbstractUserResponse;
use RunetId\Client\Result\User\UserResult;

final class UserResponse extends AbstractUserResponse
{
    private $userResult;

    public function __construct(ResourceOwnerInterface $resourceOwner, UserResult $userResult)
    {
        $this->resourceOwner = $resourceOwner;
        $this->userResult = $userResult;
    }

    public function getUserResult(): UserResult
    {
        return $this->userResult;
    }

    public function getRunetId(): int
    {
        return $this->userResult->RunetId;
    }

    /**
     * {@inheritdoc}
     */
    public function getUsername()
    {
        return (string) $this->userResult->RunetId;
    }

    /**
     * {@inheritdoc}
     */
    public function getNickname()
    {
        return (string) $this->userResult->RunetId;
    }

    /**
     * {@inheritdoc}
     */
    public function getEmail()
    {
        return $this->userResult->Email;
    }

    /**
     * {@inheritdoc}
     */
    public function getFirstName()
    {
        return $this->userResult->FirstName;
    }

    /**
     * {@inheritdoc}
     */
    public function getLastName()
    {
        return $this->userResult->LastName;
    }

    /**
     * {@inheritdoc}
     */
    public function getRealName()
    {
        return $this->userResult->FirstName.' '.$this->userResult->LastName;
    }

    /**
     * {@inheritdoc}
     */
    public function getProfilePicture()
    {
        return null === $this->userResult->Photo ? null : $this->userResult->Photo->Original;
    }
}


<?php

namespace NodePub\Common\Yaml;

use Symfony\Component\Yaml\Yaml;
use NodePub\Common\Config\ConfigurationProviderInterface;

/**
 * Loads and saves settings to a yaml file
 */
class YamlConfigurationProvider implements ConfigurationProviderInterface
{
    protected $filePath,
              $config,
              $defaultConfig;

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

    public function get($key, $default = null)
    {
        if (is_null($this->config)) {
            $this->load();
        }

        return isset($this->config[$key]) ? $this->config[$key] : $default;
    }

    public function getAll()
    {
        if (is_null($this->config)) {
            $this->load();
        }

        return $this->config;
    }

    public function update($key, $value)
    {
        $this->config[$key] = $value;

        try {
            $this->save();
            return true;
        } catch (\Exception $e) {
            # TODO: log the error
            return false;
        }
    }

    /**
     * Loads the yaml config file
     */
    protected function load()
    {
        $this->config = array();

        if (file_exists($this->filePath)) {
            $this->config = Yaml::parse($this->filePath);
        }
    }

    /**
     * Saves the current configuration array to the configuration yaml file
     */
    protected function save()
    {
        $yaml = Yaml::dump($this->config, 2);
        file_put_contents($this->filePath, $yaml);
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Group.php.
 *
 * @author    allen05ren <allen05ren@outlook.com>
 * @copyright 2016 overtrue <i@overtrue.me>
 *
 * @see       https://github.com/overtrue
 * @see       http://overtrue.me
 */

namespace EasyWeChat\ShakeAround;

use EasyWeChat\Core\AbstractAPI;

/**
 * Class Group.
 */
class Group extends AbstractAPI
{
    const API_ADD = 'https://api.weixin.qq.com/shakearound/device/group/add';
    const API_UPDATE = 'https://api.weixin.qq.com/shakearound/device/group/update';
    const API_DELETE = 'https://api.weixin.qq.com/shakearound/device/group/delete';
    const API_GET_LIST = 'https://api.weixin.qq.com/shakearound/device/group/getlist';
    const API_GET_DETAIL = 'https://api.weixin.qq.com/shakearound/device/group/getdetail';
    const API_ADD_DEVICE = 'https://api.weixin.qq.com/shakearound/device/group/adddevice';
    const API_DELETE_DEVICE = 'https://api.weixin.qq.com/shakearound/device/group/deletedevice';

    /**
     * Add device group.
     *
     * @param string $name
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function add($name)
    {
        $params = [
            'group_name' => $name,
        ];

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

    /**
     * Update a device group name.
     *
     * @param int    $groupId
     * @param string $name
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function update($groupId, $name)
    {
        $params = [
            'group_id' => intval($groupId),
            'group_name' => $name,
        ];

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

    /**
     * Delete device group.
     *
     * @param int $groupId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function delete($groupId)
    {
        $params = [
            'group_id' => intval($groupId),
        ];

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

    /**
     * List all device groups.
     *
     * @param int $begin
     * @param int $count
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function lists($begin, $count)
    {
        $params = [
            'begin' => intval($begin),
            'count' => intval($count),
        ];

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

    /**
     * Get details of a device group.
     *
     * @param int $groupId
     * @param int $begin
     * @param int $count
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getDetails($groupId, $begin, $count)
    {
        $params = [
            'group_id' => intval($groupId),
            'begin' => intval($begin),
            'count' => intval($count),
        ];

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

    /**
     * Add  one or more devices to a device group.
     *
     * @param int   $groupId
     * @param array $deviceIdentifiers
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function addDevice($groupId, array $deviceIdentifiers)
    {
        $params = [
            'group_id' => intval($groupId),
            'device_identifiers' => $deviceIdentifiers,
        ];

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

    /**
     * Remove one or more devices from a device group.
     *
     * @param int   $groupId
     * @param array $deviceIdentifiers
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function removeDevice($groupId, array $deviceIdentifiers)
    {
        $params = [
            'group_id' => intval($groupId),
            'device_identifiers' => $deviceIdentifiers,
        ];

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


<?php
/**
 * Wing Commander is a Mustache wrapper for Flight
 *
 * @author Chris Worfolk <chris@worfolk.co.uk>
 *
 * For full copyright and licence information, please view the LICENCE
 * file that was distributed with this source code.
 */

class WingCommander extends Mustache_Engine
{
    /**
     * Path to template files
     */
    private $templatePath = './templates';

    /**
     * Template extension
     */
    private $templateExtension = 'html';

    /**
     * Variables to parse in
     */
    private $vars = array();

    /**
     * Initialise the template engine
     *
     * @param array $options Mustache options
     */
    public static function init ($options = array())
    {
        Flight::map("render", function($template, $data, $toVar = false){
            Flight::view()->render($template, $data, $toVar);
        });

        Flight::register('view', get_called_class(), $options);
    }

    /**
     * Render a page
     *
     * @param string      $filename Filename
     * @param array       $vars     Variables
     * @param string|null $toVar    If specified, it will save as a variable rather than output
     *
     * @return void
     */
    public function render ($filename, $vars = array(), $toVar = null)
    {
        $templatePath = $this->templatePath . '/' . $filename . '.' . $this->templateExtension;

        if (file_exists($templatePath)) {

            $template = file_get_contents($templatePath);
            $output = parent::render($template, array_merge($this->vars, $vars));

            if ($toVar) {
                $this->set($toVar, $output);
            } else {
                echo $output;
            }

        } else {

            throw new Exception ("Template '$filename' could not be found.");

        }
    }

    /**
     * Set a variable
     *
     * @param string $name  Variable name
     * @maram mixed  $value Value
     *
     * @return boolean Success
     */
    public function set ($name, $value)
    {
        $this->vars[$name] = $value;
        return true;
    }

    /**
     * Set the template path
     *
     * @param string $path Path, no trailing slash
     *
     * @return boolean Success
     */
    public function setTemplatePath ($path)
    {
        $this->templatePath = $path;
        return true;
    }

    /**
     * Set the template extension
     *
     * @param string $extension Extension (i.e. mustache, html)
     *
     * @return boolean Success
     */
    public function setTemplateExtension ($extension)
    {
        $this->templateExtension = $extension;
        return true;
    }
}