<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Routing;

use Closure;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use FastRoute\RouteCollector;
use FastRoute\RouteParser;
use FastRoute\Dispatcher\GroupCountBased as Dispatcher;
use FastRoute\DataGenerator\GroupCountBased as DataGenerator;

use Autarky\Files\LockingFilesystem;

/**
 * FastRoute implementation of the router.
 */
class Router implements RouterInterface
{
	/**
	 * @var \Autarky\Routing\InvokerInterface
	 */
	protected $invoker;

	/**
	 * @var EventDispatcherInterface
	 */
	protected $eventDispatcher;

	/**
	 * @var \FastRoute\RouteCollector
	 */
	protected $routeCollector;

	/**
	 * @var \FastRoute\RouteParser
	 */
	protected $routeParser;

	/**
	 * @var mixed
	 */
	protected $dispatchData;

	/**
	 * @var string|null
	 */
	protected $cachePath;

	/**
	 * @var \Autarky\Routing\Route
	 */
	protected $currentRoute;

	/**
	 * The hooks that are currently applied to every route being added.
	 *
	 * @var array
	 */
	protected $currentHooks = [];

	/**
	 * The URL prefix that is currently applied to every route being added.
	 *
	 * @var string
	 */
	protected $currentPrefix = '';

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

	/**
	 * @var \SplObjectStorage
	 */
	protected $routes;

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

	/**
	 * @param RouteParser $routeParser
	 * @param InvokerInterface $invoker
	 * @param EventDispatcherInterface|null $eventDispatcher
	 * @param string|null $cachePath
	 */
	public function __construct(
		RouteParser $routeParser,
		InvokerInterface $invoker,
		EventDispatcherInterface $eventDispatcher = null,
		$cachePath = null
	) {
		$this->routes = new \SplObjectStorage;
		$this->invoker = $invoker;
		$this->eventDispatcher = $eventDispatcher;

		if ($cachePath) {
			$this->cachePath = $cachePath;
			if (file_exists($cachePath)) {
				Route::setRouter($this);
				$this->dispatchData = require $cachePath;
				return;
			}
		}

		$this->routeCollector = new RouteCollector(
			$routeParser, new DataGenerator
		);
	}

	/**
	 * @return bool
	 */
	public function isCaching()
	{
		return $this->dispatchData !== null;
	}

	/**
	 * @return \SplObjectStorage
	 */
	public function getRoutes()
	{
		return $this->routes;
	}

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

	/**
	 * Add a "before" event listener.
	 *
	 * @param  string   $name
	 * @param  callable $handler
	 * @param  integer  $priority
	 *
	 * @return void
	 */
	public function addBeforeHook($name, $handler, $priority = 0)
	{
		$this->addEventListener($name, $handler, 'before', $priority);
	}

	/**
	 * Add an "after" event listener.
	 *
	 * @param  string   $name
	 * @param  callable $handler
	 * @param  integer  $priority
	 *
	 * @return void
	 */
	public function addAfterHook($name, $handler, $priority = 0)
	{
		$this->addEventListener($name, $handler, 'after', $priority);
	}

	/**
	 * Add a global "before" event listener.
	 *
	 * @param  callable $handler
	 * @param  integer  $priority
	 *
	 * @return void
	 */
	public function addGlobalBeforeHook($handler, $priority = 0)
	{
		$this->addEventListener(null, $handler, 'before', $priority);
	}

	/**
	 * Add a global "after" event listener.
	 *
	 * @param  callable $handler
	 * @param  integer  $priority
	 *
	 * @return void
	 */
	public function addGlobalAfterHook($handler, $priority = 0)
	{
		$this->addEventListener(null, $handler, 'after', $priority);
	}

	protected function addEventListener($name, $handler, $when, $priority)
	{
		if ($this->eventDispatcher === null) {
			return;
		}

		if ($name) {
			if (isset($this->hooks[$name])) {
				throw new \LogicException("Hook with name $name already defined");
			}

			$this->hooks[$name] = $name;
		}

		$name = $name ? "route.$when.$name" : "route.$when";
		$this->eventDispatcher->addListener($name, $handler, $priority);
	}

	/**
	 * {@inheritdoc}
	 */
	public function mount(array $routes, $path = '/')
	{
		if ($this->isCaching()) {
			return;
		}

		(new Configuration($this, $routes))
			->mount($path);
	}

	/**
	 * {@inheritdoc}
	 */
	public function group(array $flags, Closure $callback)
	{
		if ($this->isCaching()) {
			return;
		}

		$oldPrefix = $this->currentPrefix;
		$oldHooks = $this->currentHooks;

		foreach (['before', 'after'] as $when) {
			if (isset($flags[$when])) {
				foreach ((array) $flags[$when] as $hook) {
					$this->currentHooks[] = [$when, $this->getHook($hook)];
				}
			}
		}

		if (isset($flags['prefix'])) {
			$this->currentPrefix .= '/' . trim($flags['prefix'], '/');
		}

		$callback($this);

		$this->currentPrefix = $oldPrefix;
		$this->currentHooks = $oldHooks;
	}

	protected function getHook($name)
	{
		if (!isset($this->hooks[$name])) {
			throw new \InvalidArgumentException("Hook with name $name is not defined");
		}

		return $this->hooks[$name];
	}

	/**
	 * {@inheritdoc}
	 */
	public function addRoute($methods, $path, $controller, $name = null, array $options = [])
	{
		if ($this->isCaching()) {
			return null;
		}

		$methods = (array) $methods;
		$path = $this->makePath($path);

		$route = $this->createRoute($methods, $path, $controller, $name, $options);
		$this->routes->attach($route);

		if ($name) {
			$this->addNamedRoute($name, $route);
		}

		$this->routeCollector->addRoute($route->getMethods(), $path, $route);

		return $route;
	}

	/**
	 * Add a cached route.
	 *
	 * @param Route $route
	 *
	 * @internal
	 */
	public function addCachedRoute(Route $route)
	{
		$this->routes->attach($route);
		if ($name = $route->getName()) {
			$this->addNamedRoute($name, $route);
		}
	}

	protected function makePath($path)
	{
		if ($this->currentPrefix !== null) {
			$path = rtrim($this->currentPrefix, '/') .'/'. ltrim($path, '/');
		}

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

		if ($path == '/') {
			return $path;
		}

		return rtrim($path, '/');
	}

	protected function addNamedRoute($name, Route $route)
	{
		if (isset($this->namedRoutes[$name])) {
			throw new \InvalidArgumentException("Route with name $name already exists");
		}

		$this->namedRoutes[$name] = $route;
	}

	protected function createRoute($methods, $path, $controller, $name, array $options)
	{
		$route = new Route($methods, $path, $controller, $name, $options);

		foreach ($this->currentHooks as $hook) {
			$route->addHook($hook[0], $hook[1]);
		}

		return $route;
	}

	/**
	 * {@inheritdoc}
	 */
	public function getRoute($name)
	{
		if (!isset($this->namedRoutes[$name])) {
			throw new \InvalidArgumentException("Route with name $name not found.");
		}

		return $this->namedRoutes[$name];
	}

	/**
	 * {@inheritdoc}
	 */
	public function dispatch(Request $request)
	{
		$route = $this->getRouteForRequest($request);

		return $this->getResponse($request, $route, $route->getParams());
	}

	/**
	 * Get the Route object corresponding to a given request.
	 *
	 * @param  Request $request
	 *
	 * @return Route
	 *
	 * @throws NotFoundHttpException
	 * @throws MethodNotAllowedHttpException
	 */
	public function getRouteForRequest(Request $request)
	{
		$method = $request->getMethod();
		$path = $request->getPathInfo() ?: '/';

		$result = $this->getDispatcher()
			->dispatch($method, $path);

		if ($result[0] == \FastRoute\Dispatcher::NOT_FOUND) {
			throw new NotFoundHttpException("No route match for path $path");
		} else if ($result[0] == \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) {
			throw new MethodNotAllowedHttpException($result[1],
				"Method $method not allowed for path $path");
		} else if ($result[0] !== \FastRoute\Dispatcher::FOUND) {
			throw new \RuntimeException('Unknown result from FastRoute: '.$result[0]);
		}

		return $this->matchRoute($result[1], $result[2], $request);
	}

	protected function matchRoute(Route $route, array $params, Request $request)
	{
		$route->setParams($params);

		if ($this->eventDispatcher !== null) {
			$event = new Events\RouteMatchedEvent($request, $route);
			$this->eventDispatcher->dispatch('route.match', $event);
			$route = $event->getRoute();
		}

		return $route;
	}

	protected function getResponse(Request $request, Route $route, array $params)
	{
		// convert route params into container params
		$params = $this->getContainerParams($route, $params, $request);

		$this->currentRoute = $route;

		if ($this->eventDispatcher !== null) {
			$event = new Events\BeforeEvent($request, $route);
			$this->eventDispatcher->dispatch("route.before", $event);

			foreach ($route->getBeforeHooks() as $hook) {
				$this->eventDispatcher->dispatch("route.before.$hook", $event);
			}
		}

		// if the event has been dispatched, check if the event has a response
		// that should override the route's response. if the event doesn't have
		// a response, check if the event has a controller that should override
		// the route's controller
		if (isset($event)) {
			$response = $event->getResponse();
			if (!$response) {
				$callable = $event->getController() ?: $route->getController();
			}
		} else {
			$callable = $route->getController();
		}

		// if the event hasn't been dispatched, or the event hasn't had a
		// response set onto it, invoke the controller
		if (!isset($response) || !$response) {
			$constructorArgs = $route->getOption('constructor_params');
			$response = $this->invoker->invoke($callable, $params, $constructorArgs);
		}

		if (!$response instanceof Response) {
			if (is_array($response) || $response instanceof \stdClass) {
				$response = new JsonResponse($response);
			} else {
				$response = new Response($response);
			}
		}

		if ($this->eventDispatcher !== null) {
			$event = new Events\AfterEvent($request, $route, $response);
			$this->eventDispatcher->dispatch("route.after", $event);

			foreach ($route->getAfterHooks() as $hook) {
				$this->eventDispatcher->dispatch("route.after.$hook", $event);
			}

			if ($event->getResponse() !== $response) {
				$response = $event->getResponse();
			}
		}

		$this->currentRoute = null;

		return $response;
	}

	protected function getContainerParams(Route $route, array $routeParams, Request $request)
	{
		$params = [];

		if ($extraParams = $route->getOption('params')) {
			$params = $extraParams;
		}

		// the container expects a dollar sign in front of non-class function
		// arguments
		foreach ($routeParams as $key => $value) {
			$params["\$$key"] = $value;
		}

		// this allows controllers to type-hint against the Request class to get
		// access to it directly
		$params['Symfony\Component\HttpFoundation\Request'] = $request;

		return $params;
	}

	protected function getDispatcher()
	{
		if ($this->dispatchData !== null) {
			$dispatchData = $this->dispatchData;
		} else if ($this->routeCollector !== null) {
			$dispatchData = $this->generateDispatchData();
		} else {
			throw new \RuntimeException('No dispatch data or route collector set');
		}

		return new Dispatcher($dispatchData);
	}

	protected function generateDispatchData()
	{
		$data = $this->routeCollector->getData();

		if ($this->cachePath !== null) {
			$filesys = new LockingFilesystem;
			$php = '<?php return '.var_export($data, true).";\n";
			$filesys->write($this->cachePath, $php);
		}

		return $data;
	}
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Http;

use Autarky\Providers\AbstractProvider;

class CookieProvider extends AbstractProvider
{
	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$cookieQueue = new CookieQueue;
		$this->app->getContainer()->instance('Autarky\Http\CookieQueue', $cookieQueue);
		$this->app->addMiddleware(['Autarky\Http\CookieMiddleware', $cookieQueue]);
	}
}


<?php

/**
 * Moo_EditableFieldLiteral is an object representing blank slate where you can add HTML / Images / Flash created by CMS
 * admin.
 *
 * @package editablefield
 *
 * @author  Mohamed Alsharaf <mohamed.alsharaf@gmail.com>
 */
class Moo_EditableFieldLiteral extends Moo_EditableField
{
    private static $singular_name = 'HTML Block';
    private static $plural_name   = 'HTML Blocks';

    /**
     * List of allowed custom settings fields.
     *
     * @var array
     */
    protected $customSettingsFields = [
        'Content',
    ];

    /**
     * Get extra configuration fields.
     *
     * @return array
     */
    public function getFieldConfiguration()
    {
        $customSettings = unserialize($this->CustomSettings);
        $content        = (isset($customSettings['Content'])) ? $customSettings['Content'] : '';
        $textAreaField  = new TextareaField(
            $this->getSettingName('Content'), 'HTML', $content
        );
        $textAreaField->setRows(4);
        $textAreaField->setColumns(20);

        return [
            $textAreaField,
        ];
    }

    protected function initFormField()
    {
        $label   = $this->Title ? "$this->Title" : '';
        $classes = $this->Title ? '' : ' nolabel';

        return new LiteralField(
            "LiteralField[$this->ID]",
            "
Name' class='field text$classes'>$label
" . $this->getSetting('Content') . '

'
        );
    }
}


<?php

namespace BurnBright\ExternalURLField;

use BurnBright\ExternalURLField\ExternalURLField;
use SilverStripe\ORM\FieldType\DBVarchar;

class ExternalURL extends DBVarchar
{
    private static $casting = array(
        "Domain" => "ExternalURL",
        "URL" => "ExternalURL"
    );

    /**
     * 2083 is the lowest common denominator when it comes to url lengths.
     */
    public function __construct($name = null, $size = 2083, $options = array())
    {
        parent::__construct($name, $size, $options);
    }

    /**
     * Remove ugly parts of a url to make it nice
     */
    public function Nice()
    {
        if ($this->value && $parts = parse_url($this->URL())) {
            $remove = array('scheme', 'user', 'pass', 'port', 'query', 'fragment');
            foreach ($remove as $part) {
                unset($parts[$part]);
            }

            return rtrim(http_build_url($parts), "/");
        }
    }

    /**
     * Get just the domain of the url.
     */
    public function Domain()
    {
        if ($this->value) {
            return parse_url($this->URL(), PHP_URL_HOST);
        }
    }

    /**
     * Remove the www subdomain, if present.
     */
    public function NoWWW()
    {
        return ltrim($this->value, "www.");
    }

    /**
     * Scaffold the ExternalURLField for this ExternalURL
     */
    public function scaffoldFormField($title = null, $params = null)
    {
        $field = new ExternalURLField($this->name, $title);
        $field->setMaxLength($this->getSize());

        return $field;
    }

    public function forTemplate()
    {
        if ($this->value) {
            return $this->URL();
        }
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Logging;

use Autarky\Providers\AbstractProvider;
use Autarky\Container\Factory\Definition;

/**
 * Logging provider.
 *
 * Provides a channel manager which can store multiple loggers.
 */
class LoggingProvider extends AbstractProvider
{
	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$dic = $this->app->getContainer();

		$dic->define('Autarky\Logging\ChannelManager', function() {
			return new ChannelManager();
		});
		$dic->share('Autarky\Logging\ChannelManager');

		$factory = new Definition(['Autarky\Logging\ChannelManager', 'getChannel']);
		$factory->addScalarArgument('$channel', 'string', false, null);
		$dic->define('Psr\Log\LoggerInterface', $factory);
	}
}


<?php

namespace DMR\Mapping\Driver;

use \SimpleXMLElement;

/**
 * The Xml driver abstract class, defines the metadata extraction
 * function common among all drivers used on file based drivers.
 *
 * @author Marcos Passos <marcos@marcospassos.com>
 */
abstract class Xml extends File
{
    const DOCTRINE_NAMESPACE_URI = 'http://doctrine-project.org/schemas/orm/doctrine-mapping';

    /**
     * Gets attribute value.
     *
     * @param SimpleXMLElement $node The instance of SimpleXMLElement
     * @param string           $name The name of attribute
     *
     * @return string
     */
    protected function getAttribute(SimpleXmlElement $node, $name)
    {
        $attributes = $node->attributes();

        return (string) $attributes[$name];
    }

    /**
     * Gets boolean attribute value.
     *
     * @param SimpleXMLElement $node The instance of SimpleXMLElement
     * @param string           $name The name of attribute
     *
     * @return boolean
     */
    protected function getBooleanAttribute(SimpleXmlElement $node, $name)
    {
        return 'true' === strtolower($this->getAttribute($node, $name));
    }

    /**
     * Checks whether an attribute exist under a specific node.
     *
     * @param SimpleXMLElement $node The instance of SimpleXMLElement
     * @param string           $name The name of attribute
     *
     * @return boolean
     */
    protected function isAttributeSet(SimpleXmlElement $node, $name)
    {
        $attributes = $node->attributes();

        return isset($attributes[$name]);
    }

    /**
     * {@inheritDoc}
     */
    protected function loadMappingFile($file)
    {
        $xmlElement = simplexml_load_file($file);
        $types = array('mapped-superclass', 'entity', 'document');

        foreach ($types as $type) {
            if (isset($xmlElement->$type)) {
                $className = $this->getAttribute($xmlElement->$type, 'name');

                return array($className => $xmlElement->$type);
            }
        }

        return null;
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Errors;

use Exception;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Response;
use Whoops\Run;
use Whoops\Handler\PrettyPageHandler;

/**
 * The default default error handler. Returns a whoops error screen if the
 * filp/whoops package is installed, otherwise a simple symfony error screen.
 *
 * @internal
 */
class DefaultErrorHandler implements ErrorHandlerInterface
{
	/**
	 * Whether or not debug is enabled.
	 *
	 * @var boolean
	 */
	protected $debug;

	/**
	 * @param boolean $debug
	 */
	public function __construct($debug)
	{
		$this->debug = (bool) $debug;
	}

	/**
	 * {@inheritdoc}
	 */
	public function handle(Exception $exception)
	{
		if ($this->debug && class_exists('Whoops\Run')) {
			return $this->handleWithWhoops($exception);
		}

		return $this->handleWithSymfony($exception);
	}

	protected function handleWithWhoops(Exception $exception)
	{
		$whoops = new Run();
		$whoops->allowQuit(false);
		$whoops->writeToOutput(false);
		$whoops->pushHandler(new PrettyPageHandler());

		return $whoops->handleException($exception);
	}

	protected function handleWithSymfony(Exception $exception)
	{
		if (!$exception instanceof FlattenException) {
			$exception = FlattenException::create($exception);
		}

		$handler = new ExceptionHandler($this->debug);

		return Response::create(
			$handler->getHtml($exception),
			$exception->getStatusCode(),
			$exception->getHeaders()
		);
	}
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Http;

use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHandler;

use Autarky\Providers\AbstractProvider;

/**
 * Service provider for symfony's session classes.
 */
class SessionProvider extends AbstractProvider
{
	/**
	 * @var \Autarky\Config\ConfigInterface
	 */
	protected $config;

	/**
	 * @var \Autarky\Container\ContainerInterface
	 */
	protected $dic;

	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$this->config = $this->app->getConfig();
		$this->dic = $this->app->getContainer();

		$this->dic->define('Autarky\Http\SessionHandlerFactory', function() {
			return new SessionHandlerFactory($this->dic, $this->config);
		});
		$this->dic->share('Autarky\Http\SessionHandlerFactory');
		$this->dic->define('SessionHandlerInterface', [$this, 'makeSessionHandler']);
		$this->dic->share('SessionHandlerInterface');

		$this->dic->define('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface',
			[$this, 'makeSessionStorage']);
		$this->dic->share('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface');

		$this->dic->define('Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag', function() {
			return new AttributeBag('_autarky_attributes');
		});
		$this->dic->alias(
			'Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag',
			'Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface'
		);

		$this->dic->define('Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag', function() {
			return new AutoExpireFlashBag('_autarky_flashes');
		});
		$this->dic->alias(
			'Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag',
			'Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface'
		);

		$this->dic->define('Symfony\Component\HttpFoundation\Session\Session',
			[$this, 'makeSession']);
		$this->dic->share('Symfony\Component\HttpFoundation\Session\Session');
		$this->dic->alias(
			'Symfony\Component\HttpFoundation\Session\Session',
			'Symfony\Component\HttpFoundation\Session\SessionInterface'
		);

		$this->app->addMiddleware(['Autarky\Http\SessionMiddleware', $this->app]);
	}

	/**
	 * Make the session handler.
	 *
	 * @return \SessionHandlerInterface
	 */
	public function makeSessionHandler()
	{
		$handler = $this->dic->resolve('Autarky\Http\SessionHandlerFactory')
			->makeHandler($this->config->get('session.handler'));

		if ($this->config->get('session.write_check') === true) {
			$handler = new WriteCheckSessionHandler($handler);
		}

		return $handler;
	}

	/**
	 * Make the session storage.
	 *
	 * @return \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface
	 */
	public function makeSessionStorage()
	{
		$storage = $this->config->get('session.storage');

		if ($storage == 'mock_array') {
			return new MockArraySessionStorage;
		}
		if ($storage == 'mock_file') {
			return new MockFileSessionStorage;
		}

		$handler = $this->dic->resolve('SessionHandlerInterface');

		if ($storage == 'bridge') {
			return new PhpBridgeSessionStorage($handler);
		}

		$options = $this->config->get('session.storage_options', []);

		if ($storage == 'native') {
			return new NativeSessionStorage($options, $handler);
		}

		if (!is_string($storage)) {
			$storage = gettype($storage);
		}

		throw new \RuntimeException("Unknown session storage driver: $storage");
	}

	/**
	 * Make the session object.
	 *
	 * @return \Symfony\Component\HttpFoundation\Session\Session
	 */
	public function makeSession()
	{
		$session = new Session(
			$this->dic->resolve('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface'),
			$this->dic->resolve('Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface'),
			$this->dic->resolve('Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface')
		);

		$session->setName($this->config->get('session.cookie.name', 'autarky_session'));

		return $session;
	}
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Routing;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\EventDispatcher\Event;

use Autarky\Container\ContainerAwareTrait;

/**
 * Trait for controller functionality. Any class that implements this trait
 * should also implement the interface Autarky\Container\ContainerAwareInterface
 * - the interface's methods are implemented by the trait, but you still need to
 * implement the interface on the class.
 */
trait ControllerTrait
{
	use ContainerAwareTrait;

	/**
	 * Render a template.
	 *
	 * @param  string $name Name of the view.
	 * @param  array  $data Data to pass to the view.
	 *
	 * @return string
	 */
	protected function render($name, array $data = array())
	{
		return $this->container->resolve('Autarky\TwigTemplating\TemplatingEngine')
			->render($name, $data);
	}

	/**
	 * Generate the URL to a route.
	 *
	 * @param  string $name   Name of the route.
	 * @param  array  $params Route parameters.
	 *
	 * @return string
	 */
	protected function url($name, array $params = array())
	{
		return $this->container->resolve('Autarky\Routing\UrlGenerator')
			->getRouteUrl($name, $params);
	}

	/**
	 * Get the session manager.
	 *
	 * @return \Symfony\Component\HttpFoundation\Session\Session
	 */
	protected function getSession()
	{
		return $this->container->resolve('Symfony\Component\HttpFoundation\Session\Session');
	}

	/**
	 * Flash something to the session.
	 *
	 * @param  string $key
	 * @param  mixed  $value
	 *
	 * @return void
	 */
	protected function flash($key, $value)
	{
		$this->getSession()
			->getFlashBag()
			->set($key, $value);
	}

	/**
	 * Flash an array of messages to the session.
	 *
	 * @param  array  $messages
	 *
	 * @return void
	 */
	protected function flashMessages($messages)
	{
		$flashBag = $this->getSession()
			->getFlashBag();

		foreach ((array) $messages as $message) {
			$flashBag->add('_messages', $message);
		}
	}

	/**
	 * Flash input to session.
	 *
	 * @param  \Symfony\Component\HttpFoundation\Request $request Optional
	 *
	 * @return void
	 */
	protected function flashInput(Request $request = null)
	{
		if ($request === null) {
			$request = $this->container
				->resolve('Symfony\Component\HttpFoundation\RequestStack')
				->getCurrentRequest();
		}

		$this->flash('_old_input', $request->request->all());
	}

	/**
	 * Get old input flashed to the session.
	 *
	 * @return array
	 */
	protected function getOldInput()
	{
		return $this->getSession()
			->getFlashBag()
			->peek('_old_input', []);
	}

	/**
	 * Get the event dispatcher instance.
	 *
	 * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
	 */
	protected function getEventDispatcher()
	{
		return $this->container->resolve('Symfony\Component\EventDispatcher\EventDispatcherInterface');
	}

	/**
	 * Dispatch an event.
	 *
	 * @param  string $name
	 * @param  Event  $event
	 *
	 * @return mixed
	 */
	protected function dispatchEvent($name, Event $event)
	{
		return $this->getEventDispatcher()
			->dispatch($name, $event);
	}

	/**
	 * Log a message.
	 *
	 * @param  string $level   https://github.com/php-fig/log/blob/master/Psr/Log/LogLevel.php
	 * @param  string $message
	 * @param  array  $context
	 *
	 * @return void
	 */
	protected function log($level, $message, array $context = array())
	{
		$this->getLogger()
			->log($level, $message, $context);
	}

	/**
	 * Get the logger instance.
	 *
	 * @return \Psr\Log\LoggerInterface
	 */
	protected function getLogger()
	{
		return $this->container->resolve('Psr\Log\LoggerInterface');
	}

	/**
	 * Create a response.
	 *
	 * @param  string  $content
	 * @param  integer $statusCode
	 *
	 * @return \Symfony\Component\HttpFoundation\Response
	 */
	protected function response($content, $statusCode = 200)
	{
		return new Response($content, $statusCode);
	}

	/**
	 * Create a redirect response.
	 *
	 * @param  string  $name       Name of the route to redirect to
	 * @param  array   $params     Route parameters
	 * @param  integer $statusCode Default: 302
	 *
	 * @return \Symfony\Component\HttpFoundation\RedirectResponse
	 */
	protected function redirect($name, array $params = array(), $statusCode = 302)
	{
		return new RedirectResponse($this->url($name, $params), $statusCode);
	}

	/**
	 * Create a JSON response.
	 *
	 * @param  array   $data
	 * @param  integer $statusCode
	 *
	 * @return \Symfony\Component\HttpFoundation\JsonResponse
	 */
	protected function json(array $data, $statusCode = 200)
	{
		return new JsonResponse($data, $statusCode);
	}
}


<?php

/**
 * This file is part of the Pathfinder package.
 *
 * (c) bitExpert AG
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types = 1);

namespace bitExpert\Pathfinder\Middleware;

use bitExpert\Pathfinder\Router;
use bitExpert\Pathfinder\RoutingResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class BasicRoutingMiddleware implements RoutingMiddleware
{
    /**
     * @var Router
     */
    protected $router;
    /**
     * @var string
     */
    protected $routingResultAttribute;

    /**
     * Creates a new {@link \bitExpert\Pathfinder\Middleware\BasicRoutingMiddleware}.
     *
     * @param Router $router
     * @param string $routingResultAttribute
     */
    public function __construct(Router $router, string $routingResultAttribute)
    {
        $this->router = $router;
        $this->routingResultAttribute = $routingResultAttribute;
    }

    /**
     * {@inheritdoc}
     */
    public function getRoutingResultAttribute() : string
    {
        return $this->routingResultAttribute;
    }

    /**
     * {@inheritdoc}
     */
    public function getRouter() : Router
    {
        return $this->router;
    }

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return ResponseInterface
     */
    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        callable $next = null
    ) : ResponseInterface {
        $result = $this->router->match($request);
        $request = $this->applyRoutingResult($request, $result);

        if ($next) {
            $response = $next($request->withAttribute($this->routingResultAttribute, $result), $response);
        }

        return $response;
    }

    /**
     * Offers possibility to manipulate the request according to routing result.
     * Returns a new {@link \Psr\Http\Message\ServerRequestInterface}.
     *
     * @param ServerRequestInterface $request
     * @param RoutingResult $routingResult
     * @return ServerRequestInterface
     */
    protected function applyRoutingResult(
        ServerRequestInterface $request,
        RoutingResult $routingResult
    ) : ServerRequestInterface {
        $routingParams = $routingResult->getParams();
        $params = array_merge($request->getQueryParams(), $routingParams);
        return $request->withQueryParams($params);
    }
}


<?php
namespace Nubs\Vectorix;

use Exception;

/**
 * This class represents an immutable Euclidean vector and its associated
 * operations.
 *
 * Instances of this class will not change state.  Any operations on the vector
 * will return a new vector with the new state.
 */
class Vector
{
    /** @type array<int|float> The components of the vector. */
    protected $_components;

    /**
     * Initialize the vector with its components.
     *
     * @api
     * @param array<int|float> $components The components of the vector.
     */
    public function __construct(array $components)
    {
        $this->_components = $components;
    }

    /**
     * Creates a null/zero-length vector of the given dimension.
     *
     * @api
     * @param int $dimension The dimension of the vector to create.  Must be at least 0.
     * @return self The zero-length vector for the given dimension.
     * @throws Exception if the dimension is less than zero.
     */
    public static function nullVector($dimension)
    {
        if ($dimension < 0) {
            throw new Exception('Dimension must be zero or greater');
        }

        if ($dimension === 0) {
            return new static([]);
        }

        return new static(array_fill(0, $dimension, 0));
    }

    /**
     * Get the components of the vector.
     *
     * @api
     * @return array<int|float> The components of the vector.
     */
    public function components()
    {
        return $this->_components;
    }

    /**
     * Get the dimension/cardinality of the vector.
     *
     * @api
     * @return int The dimension/cardinality of the vector.
     */
    public function dimension()
    {
        return count($this->components());
    }

    /**
     * Returns the length of the vector.
     *
     * @api
     * @return float The length/magnitude of the vector.
     */
    public function length()
    {
        $sumOfSquares = 0;
        foreach ($this->components() as $component) {
            $sumOfSquares += pow($component, 2);
        }

        return sqrt($sumOfSquares);
    }

    /**
     * Check whether the given vector is the same as this vector.
     *
     * @api
     * @param self $b The vector to check for equality.
     * @return bool True if the vectors are equal and false otherwise.
     */
    public function isEqual(self $b)
    {
        return $this->components() === $b->components();
    }

    /**
     * Checks whether the two vectors are of the same dimension.
     *
     * @api
     * @param self $b The vector to check against.
     * @return bool True if the vectors are of the same dimension, false otherwise.
     */
    public function isSameDimension(self $b)
    {
        return $this->dimension() === $b->dimension();
    }

    /**
     * Checks whether the two vectors are of the same vector space.
     *
     * @api
     * @param self $b The vector to check against.
     * @return bool True if the vectors are the same vector space, false otherwise.
     */
    public function isSameVectorSpace(self $b)
    {
        return array_keys($this->components()) === array_keys($b->components());
    }

    /**
     * Adds two vectors together.
     *
     * @api
     * @param self $b The vector to add.
     * @return self The sum of the two vectors.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function add(self $b)
    {
        $this->_checkVectorSpace($b);

        $bComponents = $b->components();
        $sum = [];
        foreach ($this->components() as $i => $component) {
            $sum[$i] = $component + $bComponents[$i];
        }

        return new static($sum);
    }

    /**
     * Subtracts the given vector from this vector.
     *
     * @api
     * @param self $b The vector to subtract from this vector.
     * @return self The difference of the two vectors.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function subtract(self $b)
    {
        return $this->add($b->multiplyByScalar(-1));
    }

    /**
     * Computes the dot product, or scalar product, of two vectors.
     *
     * @api
     * @param self $b The vector to multiply with.
     * @return int|float The dot product of the two vectors.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function dotProduct(self $b)
    {
        $this->_checkVectorSpace($b);

        $bComponents = $b->components();
        $product = 0;
        foreach ($this->components() as $i => $component) {
            $product += $component * $bComponents[$i];
        }

        return $product;
    }

    /**
     * Computes the cross product, or vector product, of two vectors.
     *
     * @api
     * @param self $b The vector to multiply with.
     * @return self The cross product of the two vectors.
     * @throws Exception if the vectors are not 3-dimensional.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function crossProduct(self $b)
    {
        $this->_checkVectorSpace($b);
        if ($this->dimension() !== 3) {
            throw new Exception('Both vectors must be 3-dimensional');
        }

        $tc = $this->components();
        $bc = $b->components();
        list($k0, $k1, $k2) = array_keys($tc);
        $product = [
            $k0 => $tc[$k1] * $bc[$k2] - $tc[$k2] * $bc[$k1],
            $k1 => $tc[$k2] * $bc[$k0] - $tc[$k0] * $bc[$k2],
            $k2 => $tc[$k0] * $bc[$k1] - $tc[$k1] * $bc[$k0],
        ];

        return new static($product);
    }

    /**
     * Computes the scalar triple product of three vectors.
     *
     * @api
     * @param self $b The second vector of the triple product.
     * @param self $c The third vector of the triple product.
     * @return int|float The scalar triple product of the three vectors.
     * @throws Exception if the vectors are not 3-dimensional.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function scalarTripleProduct(self $b, self $c)
    {
        return $this->dotProduct($b->crossProduct($c));
    }

    /**
     * Computes the vector triple product of three vectors.
     *
     * @api
     * @param self $b The second vector of the triple product.
     * @param self $c The third vector of the triple product.
     * @return self The vector triple product of the three vectors.
     * @throws Exception if the vectors are not 3-dimensional.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function vectorTripleProduct(self $b, self $c)
    {
        return $this->crossProduct($b->crossProduct($c));
    }

    /**
     * Multiplies the vector by the given scalar.
     *
     * @api
     * @param int|float $scalar The real number to multiply by.
     * @return self The result of the multiplication.
     */
    public function multiplyByScalar($scalar)
    {
        $result = [];
        foreach ($this->components() as $i => $component) {
            $result[$i] = $component * $scalar;
        }

        return new static($result);
    }

    /**
     * Divides the vector by the given scalar.
     *
     * @api
     * @param int|float $scalar The real number to divide by.
     * @return self The result of the division.
     * @throws Exception if the $scalar is 0.
     */
    public function divideByScalar($scalar)
    {
        if ($scalar == 0) {
            throw new Exception('Cannot divide by zero');
        }

        return $this->multiplyByScalar(1.0 / $scalar);
    }

    /**
     * Return the normalized vector.
     *
     * The normalized vector (or unit vector) is the vector with the same
     * direction as this vector, but with a length/magnitude of 1.
     *
     * @api
     * @return self The normalized vector.
     * @throws Exception if the vector length is zero.
     */
    public function normalize()
    {
        return $this->divideByScalar($this->length());
    }

    /**
     * Project the vector onto another vector.
     *
     * @api
     * @param self $b The vector to project this vector onto.
     * @return self The vector projection of this vector onto $b.
     * @throws Exception if the vector length of $b is zero.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function projectOnto(self $b)
    {
        $bUnit = $b->normalize();
        return $bUnit->multiplyByScalar($this->dotProduct($bUnit));
    }

    /**
     * Returns the angle between the two vectors.
     *
     * @api
     * @param self $b The vector to compute the angle between.
     * @return float The angle between the two vectors in radians.
     * @throws Exception if either of the vectors are zero-length.
     * @throws Exception if the vectors are not in the same vector space.
     * @see self::_checkVectorSpace() For exception information.
     */
    public function angleBetween(self $b)
    {
        $denominator = $this->length() * $b->length();
        if ($denominator == 0) {
            throw new Exception('Cannot divide by zero');
        }

        return acos($this->dotProduct($b) / $denominator);
    }

    /**
     * Checks that the vector spaces of the two vectors are the same.
     *
     * The vectors must be of the same dimension and have the same keys in their
     * components.
     *
     * @internal
     * @param self $b The vector to check against.
     * @return void
     * @throws Exception if the vectors are not of the same dimension.
     * @throws Exception if the vectors' components down have the same keys.
     */
    protected function _checkVectorSpace(self $b)
    {
        if (!$this->isSameDimension($b)) {
            throw new Exception('The vectors must be of the same dimension');
        }

        if (!$this->isSameVectorSpace($b)) {
            throw new Exception('The vectors\' components must have the same keys');
        }
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Routing;

use Symfony\Component\HttpFoundation\RequestStack;

/**
 * URL generator.
 */
class UrlGenerator
{
	/**
	 * @var Router
	 */
	protected $router;

	/**
	 * @var RoutePathGeneratorInterface
	 */
	protected $routePathGenerator;

	/**
	 * @var RequestStack
	 */
	protected $requests;

	/**
	 * The root URL to use for assets, if any.
	 *
	 * @var null|string
	 */
	protected $assetRoot;

	/**
	 * @param Router                      $router
	 * @param RoutePathGeneratorInterface $routePathGenerator
	 * @param RequestStack                $requests
	 * @param bool                        $validateParams
	 */
	public function __construct(
		Router $router,
		RoutePathGeneratorInterface $routePathGenerator,
		RequestStack $requests,
		$validateParams = false
	) {
		$this->router = $router;
		$this->routePathGenerator = $routePathGenerator;
		$this->requests = $requests;
		$this->setValidateParams($validateParams);
	}

	/**
	 * Set the root URL for assets. Useful if you're using CDNs.
	 *
	 * @param string $assetRoot
	 */
	public function setAssetRoot($assetRoot)
	{
		$this->assetRoot = rtrim($assetRoot, '/');
	}

	/**
	 * Set whether the regex pattern of route parameters should be validated on
	 * runtime.
	 *
	 * @param bool $validateParams
	 */
	public function setValidateParams($validateParams)
	{
		$this->routePathGenerator->setValidateParams($validateParams);
	}

	/**
	 * Get the URL to a named route.
	 *
	 * @param  string $name
	 * @param  array  $params
	 * @param  bool   $relative
	 *
	 * @return string
	 */
	public function getRouteUrl($name, array $params = array(), $relative = false)
	{
		$route = $this->router->getRoute($name);

		$routeParams = [];
		$query = [];
		foreach ($params as $key => $value) {
			if (is_int($key)) {
				$routeParams[] = $value;
			} else {
				$query[$key] = $value;
			}
		}

		$path = $this->routePathGenerator->getRoutePath($route, $routeParams);

		if ($query) {
			$path .= '?'.http_build_query($query);
		}

		if ($relative) {
			$root = $this->requests->getCurrentRequest()
				->getBaseUrl();
		} else {
			$root = $this->getRootUrl();
		}

		return $root . $path;
	}

	/**
	 * Get the URL to an asset.
	 *
	 * @param  string  $path
	 * @param  boolean $relative
	 *
	 * @return string
	 */
	public function getAssetUrl($path, $relative = false)
	{
		if (substr($path, 0, 1) !== '/') {
			$path = '/'.$path;
		}

		if ($this->assetRoot !== null) {
			$base = $this->assetRoot;
		} else if ($relative) {
			$base = $this->requests
				->getCurrentRequest()
				->getBaseUrl();
		} else {
			$base = $this->getRootUrl();
		}

		return $base . $path;
	}

	/**
	 * Get the root URL. Used to generate URLs to assets.
	 *
	 * @return string
	 */
	public function getRootUrl()
	{
		$request = $this->requests->getCurrentRequest();
		$host = $request->getHttpHost();
		$base = $request->getBaseUrl();

		return rtrim("//$host/$base", '/');
	}
}


<?php

/**
 * Moo_EditableFieldDate is an object representing date field created by CMS admin.
 *
 * @package editablefield
 *
 * @author  Mohamed Alsharaf <mohamed.alsharaf@gmail.com>
 */
class Moo_EditableFieldDate extends Moo_EditableField
{
    private static $singular_name = 'Date Field';
    private static $plural_name   = 'Date Fields';

    /**
     * List of allowed custom settings fields.
     *
     * @var array
     */
    protected $customSettingsFields = [
        'DefaultToToday',
    ];

    /**
     * Get extra configuration fields.
     *
     * @return array
     */
    public function getFieldConfiguration()
    {
        $default = ($this->getSetting('DefaultToToday')) ? $this->getSetting('DefaultToToday') : false;
        $label   = _t('Moo_EditableField.DEFAULTTOTODAY', 'Default to Today?');

        return [
            new CheckboxField($this->getSettingName('DefaultToToday'), $label, $default),
        ];
    }

    protected function initFormField()
    {
        $defaultValue = ($this->getSetting('DefaultToToday')) ? date('Y-m-d') : $this->Default;
        $field        = new DateField($this->Name, $this->Title, $defaultValue);
        $field->setConfig('showcalendar', true);

        return $field;
    }
}


<?php

namespace Aptoma\Silex\Provider;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Extends Guzzle service provider for Silex to provide global plugin sipport
 */
class GuzzleServiceProvider implements ServiceProviderInterface
{
    /**
     * Register Guzzle with Silex
     *
     * @param Container $app App container to register with
     */
    public function register(Container $app)
    {
        $app['guzzle.handler_stack'] = function () {
            $stack = HandlerStack::create();

            return $stack;
        };

        $app['guzzle'] = function () use ($app) {
            $client = new HttpClient([
                'handler' => $app['guzzle.handler_stack']
            ]);

            return $client;
        };
    }
}


<?php

namespace Aptoma\Security\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Aptoma\Security\Authentication\Token\ApiKeyToken;
use Aptoma\Security\User\ApiKeyUserProviderInterface;
use Aptoma\Security\Encoder\SaltLessPasswordEncoderInterface;

class ApiKeyAuthenticationProvider implements AuthenticationProviderInterface
{
    /**
     * Encoder used to encode the API key
     *
     * We're using a saltless password encoder.
     * There is no way of looking up the salt since we don't know who the user is
     * The encoder can of course implement a static, common salt for all passwords
     *
     * @var SaltLessPasswordEncoderInterface
     */
    private $encoder;

    /**
     * User provider
     * @var ApiKeyUserProviderInterface
     */
    private $userProvider;

    public function __construct(ApiKeyUserProviderInterface $userProvider, SaltLessPasswordEncoderInterface $encoder)
    {
        $this->userProvider = $userProvider;
        $this->encoder = $encoder;
    }

    /**
     * Authenticate the user based on an API key
     *
     * @param TokenInterface $token
     */
    public function authenticate(TokenInterface $token)
    {
        $user = $this->userProvider->loadUserByApiKey($this->encoder->encodePassword($token->getCredentials()));

        if (!$user || !($user instanceof UserInterface)) {
            throw new AuthenticationException('Bad credentials');
        }

        $token = new ApiKeyToken($token->getCredentials(), $user->getRoles());
        $token->setUser($user);

        return $token;
    }

    public function supports(TokenInterface $token)
    {
        return $token instanceof ApiKeyToken;
    }
}


<?php

/**
 * Moo_EditableFieldText is an object representing text field created by CMS admin.
 *
 * @package editablefield
 *
 * @author  Mohamed Alsharaf <mohamed.alsharaf@gmail.com>
 */
class Moo_EditableFieldText extends Moo_EditableField
{
    private static $singular_name = 'Text Field';
    private static $plural_name   = 'Text Fields';

    /**
     * List of allowed custom settings fields.
     *
     * @var array
     */
    protected $customSettingsFields = [
        'MinLength', 'MaxLength', 'Rows',
    ];

    /**
     * Get extra configuration fields.
     *
     * @return array
     */
    public function getFieldConfiguration()
    {
        $min = ($this->getSetting('MinLength')) ? $this->getSetting('MinLength') : '';
        $max = ($this->getSetting('MaxLength')) ? $this->getSetting('MaxLength') : '';

        $rows = ($this->getSetting('Rows')) ? $this->getSetting('Rows') : '1';

        return [
            $learnMoreField = FieldGroup::create(
                _t('Moo_EditableFieldText.TEXTLENGTH', 'Text length'),
                new NumericField($this->getSettingName('MinLength'), 'Min', $min),
                new NumericField($this->getSettingName('MaxLength'), 'Max', $max)
            ),
            new NumericField($this->getSettingName('Rows'), _t('Moo_EditableFieldText.NUMBERROWS', 'Number of rows'), $rows),
        ];
    }

    /**
     * @return TextareaField|TextField
     */
    protected function initFormField()
    {
        if ($this->getSetting('Rows') && $this->getSetting('Rows') > 1) {
            $textareaField = new TextareaField($this->Name, $this->Title);
            $textareaField->setRows($this->getSetting('Rows'));

            return $textareaField;
        }

        return new TextField($this->Name, $this->Title, null, $this->getSetting('MaxLength'));
    }
}


<?php

/**
 * Moo_EditableFieldMemberList is an object representing member dropdown field created by CMS admin.
 *
 * @package editablefield
 *
 * @author  Mohamed Alsharaf <mohamed.alsharaf@gmail.com>
 */
class Moo_EditableFieldMemberList extends Moo_EditableField
{
    private static $singular_name   = 'Member List Field';
    private static $plural_name     = 'Member List Fields';

    /**
     * List of allowed custom settings fields.
     *
     * @var array
     */
    protected $customSettingsFields = [
        'GroupID',
    ];

    /**
     * Get extra configuration fields.
     *
     * @return array
     */
    public function getFieldConfiguration()
    {
        $groupID = ($this->getSetting('GroupID')) ? $this->getSetting('GroupID') : 0;
        $groups  = DataObject::get('Group');

        if ($groups) {
            $groups = $groups->map('ID', 'Title');
        }

        return [
            new DropdownField($this->getSettingName('GroupID'), _t('Moo_EditableField.GROUP', 'Group'), $groups, $groupID),
        ];
    }

    protected function initFormField()
    {
        if ($this->getSetting('GroupID')) {
            $members = Member::map_in_groups($this->getSetting('GroupID'));

            return new DropdownField($this->Name, $this->Title, $members);
        }

        return false;
    }
}


<?php

namespace DMR\Mapping;

use Doctrine\Common\Persistence\ManagerRegistry;

/**
 * Agnostic metadata reader.
 *
 * AgnosticReader uses a ManagerRegistry to get the necessary
 * resources used by reader to read the class's metadata. The
 * advantage of this implementation over the SimpleReader is
 * that this one automatically guesses the manager based on
 * the given object so that you can read the metadata's from
 * an entity or a document in a transparent way.
 *
 * @author Marcos Passos <marcos@marcospassos.com>
 */
class AgnosticReader extends AbstractReader
{
    /**
     * @var array
     */
    protected $registries;

    /**
     * Constructor.
     */
    public function __construct(array $registries = null)
    {
    	$this->registries = array();

    	if (!$registries) {
            return;
        }

        foreach ($registries as $registry) {
            if (!$registry instanceof ManagerRegistry) {
                throw new \RuntimeException('The registry must implement interface Doctrine\Common\Persistence\ManagerRegistry.');
            }

            $this->addManagerRegistry($registry);
        }
    }

    /**
     * Adds a manager registry.
     *
     * @param ManagerRegistry $registry
     */
    public function addManagerRegistry(ManagerRegistry $registry)
    {
    	if (!in_array($registry, $this->registries, true)) {
    		$this->registries[] = $registry;
    	}
    }

    public function getRegistries()
    {
    	return $this->registries;
    }

    protected function getManagerForClass($class)
    {
    	foreach ($this->registries as $registry) {
    		if (($manager = $registry->getManagerForClass($class)) != null) {
    			return $manager;
    		}
    	}

    	throw new \RuntimeException(sprintf('There is no manager registered for class "%s"', $class));
    }
}


<?php

namespace Singo;

use Silex\Application as SilexApplication;
use Stack\Builder;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Application
 * @package Singo
 */
class Application extends SilexApplication
{
    use ServiceInitializator;
    use ModuleBooter;

    /**
     * @var Builder
     */
    public $builder;

    /**
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        parent::__construct($values);

        if (! defined("APP_PATH")) {
            define("APP_PATH", $this["app.path"]);
        }

        if (! defined("PUBLIC_PATH")) {
            define("PUBLIC_PATH", $this["app.public.path"]);
        }

        $this->builder = new Builder();
    }

    /**
     * @param Request $request
     */
    public function run(Request $request = null)
    {
        /**
         * resolve stack middleware for our apps
         */
        $app = $this->builder->resolve($this);

        /**
         * override current apps with stacked http kernel
         */
        if ($request === null) {
            $request =  Request::createFromGlobals();
        }

        $response = $app->handle($request);
        $response->send();
        $this->terminate($request, $response);
    }

    /**
     * register command for our application
     * @param array $commands
     * @param callable $handler
     */
    public function registerCommands(array $commands, callable $handler)
    {
        foreach ($commands as $command) {
            $handler_id = "app.handler." . join('', array_slice(explode("\\", $command), -1));
            $this[$handler_id] = $handler;
        }
    }

    /**
     * register our event subscriber
     * @param string $class
     * @param callable $callback
     */
    public function registerSubscriber($class, callable $callback)
    {
        $service_id = "event." . strtolower(str_replace("\\", ".", $class));

        $this[$service_id] = $callback;

        $this["dispatcher"]->addSubscriberService($service_id, $class);
    }

    /**
     * register stack middleware
     * @param string $class
     */
    public function registerStackMiddleware($class)
    {
        if (func_num_args() === 0) {
            throw new \InvalidArgumentException("Missing argument(s) when calling registerStackMiddlerware");
        }

        if (! class_exists($class) && ! is_callable($class)) {
            throw new \InvalidArgumentException("{$class} not found or not callable");
        }

        call_user_func_array([$this->builder, "push"], func_get_args());
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Routing;

use Autarky\Container\ContainerInterface;

/**
 * {@inheritdoc}
 *
 * @internal
 */
class Invoker implements InvokerInterface
{
	/**
	 * @var ContainerInterface
	 */
	protected $container;

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

	/**
	 * {@inheritdoc}
	 */
	public function invoke($callable, array $params = [], $constructorArgs = [])
	{
		if (is_string($callable) && strpos($callable, '::') !== false) {
			$callable = explode('::', $callable, 2);
		}

		if (is_array($callable) && is_string($callable[0]) && $constructorArgs) {
			$callable[0] = $this->container->resolve($callable[0], $constructorArgs);
		}

		return $this->container->invoke($callable, $params);
	}
}


<?php

namespace BW\Captcha;

/*
 * This is a reCAPTCHA PHP SDK.
 *    - Documentation and latest version of source for PHP:
 *          https://developers.google.com/recaptcha/docs/php
 */
class Recaptcha
{

    /**
     * Current version of reCAPTCHA PHP SDK
     */
    const VERSION = '1.11.1';

    /**
     * The reCAPTCHA API server URL
     */
    const RECAPTCHA_API_SERVER = 'http://www.google.com/recaptcha/api';

    /**
     * The reCAPTCHA API secure server URL
     */
    const RECAPTCHA_API_SECURE_SERVER = 'https://www.google.com/recaptcha/api';

    /**
     * The reCAPTCHA API verify server URL
     */
    const RECAPTCHA_VERIFY_SERVER = 'www.google.com';

    /**
     * @var string The client public key
     */
    private $publicKey;

    /**
     * @var string The client private key
     */
    private $privateKey;

    /**
     * @var boolean Whether valid user input or no
     */
    protected $valid = false;

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

    /**
     * The constructor of objects
     *
     * @param string $publicKey The client public key
     * @param string $privateKey The client private key
     */
    public function __construct($publicKey = '', $privateKey = '')
    {
        $this->setPublicKey($publicKey);
        $this->setPrivateKey($privateKey);
    }

    /**
     * @see $this->getHtml()
     */
    public function __toString()
    {
        return $this->getHtml();
    }

    /**
     * Gets the challenge HTML (javascript and non-javascript version).
     * This is called from the browser, and the resulting reCAPTCHA HTML widget
     * is embedded within the HTML form it was called from.
     *
     * @param string $error The error given by reCAPTCHA (optional, default is null)
     * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
     * @return string The HTML to be embedded in the user's form.
     * @throws \Exception
     */
    public function getHtml($error = null, $use_ssl = false) {
        if ( ! $this->getPublicKey()) {
            throw new \Exception('To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create');
        }

        if (true === $use_ssl) {
            $server = self::RECAPTCHA_API_SECURE_SERVER;
        } else {
            $server = self::RECAPTCHA_API_SERVER;
        }

        $errorpart = '';
        if ($error) {
            $errorpart = "&error=" . $error;
        }

        return ''. PHP_EOL
                .''. PHP_EOL
                .'    getPublicKey() . $errorpart . '" height="300" width="500" frameborder="0">
'. PHP_EOL
                .'    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>'. PHP_EOL
                .'    <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>'. PHP_EOL
                .''. PHP_EOL;
    }

    /**
     * Calls an HTTP POST function to verify if the user's guess was correct
     *
     * @param array $extraParams An array of extra variables to post to the server
     * @return $this
     * @throws \Exception
     */
    public function checkAnswer($extraParams = array()) {
        $remoteIp = $_SERVER["REMOTE_ADDR"];
        $challenge = $_POST["recaptcha_challenge_field"];
        $response = $_POST["recaptcha_response_field"];

        if ( ! $this->getPrivateKey()) {
            throw new \Exception("To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create");
        }

        if ( ! $remoteIp) {
            throw new \Exception("For security reasons, you must pass the remote ip to reCAPTCHA");
        }

        if ( ! $challenge) { // discard spam submissions
            $this->valid = false;
            $this->error = 'incorrect-captcha-sol';
        } else { // or check user input
            $response = $this->httpPost(self::RECAPTCHA_VERIFY_SERVER, '/recaptcha/api/verify',
                    array(
                        'privatekey' => $this->getPrivateKey(),
                        'remoteip' => $remoteIp,
                        'challenge' => $challenge,
                        'response' => $response,
                    ) + $extraParams
                );

            $answers = explode("\n", $response[1]);
            if (trim($answers[0]) == 'true') {
                $this->valid = true;
            } else {
                $this->valid = false;
                $this->error = $answers[1];
            }
        }

        return $this;
    }

    /**
     * Submits an HTTP POST to a reCAPTCHA server
     *
     * @param string $host
     * @param string $path
     * @param array $data
     * @param int port
     * @return array response
     * @throws \Exception
     */
    protected function httpPost($host, $path, array $data, $port = 80) {
        $req = $this->qsencode($data);

        $http_request  = "POST {$path} HTTP/1.0\r\n";
        $http_request .= "Host: {$host}\r\n";
        $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
        $http_request .= "Content-Length: " . strlen($req) . "\r\n";
        $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
        $http_request .= "\r\n";
        $http_request .= $req;

        $response = '';
        if(false == ($fs = @fsockopen($host, (int)$port, $errno, $errstr, 10))) {
            throw new \Exception('Could not open socket');
        }

        fwrite($fs, $http_request);
        while ( ! feof($fs)) {
            $response .= fgets($fs, 1160); // One TCP-IP packet
        }
        fclose($fs);

        $response = explode("\r\n\r\n", $response, 2);
        return $response;
    }

    /**
     * Encodes the given data into a query string format
     *
     * @param array $data An array of string elements to be encoded
     * @return string Encoded request
     */
    protected function qsencode(array $data = array()) {
        $req = '';

        if ($data) {
            foreach ($data as $key => $value) {
                $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
            }
            $req = substr($req, 0, strlen($req) - 1); // Cut the last '&'
        }

        return $req;
    }

    /**
     * Check user input
     *
     * @return bool Whether valid user input or no
     */
    public function isValid() {
        return $this->valid;
    }

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

    /**
     * Get the public key
     *
     * @return string The public key
     */
    public function getPublicKey()
    {
        return $this->publicKey;
    }

    /**
     * Set the public key
     *
     * @param string $publicKey The public key
     * @return $this
     */
    public function setPublicKey($publicKey)
    {
        $this->publicKey = (string)$publicKey;
        return $this;
    }

    /**
     * Get the private key
     *
     * @return string The private key
     */
    public function getPrivateKey()
    {
        return $this->privateKey;
    }

    /**
     * Set the private key
     *
     * @param string $privateKey The private key
     * @return $this
     */
    public function setPrivateKey($privateKey)
    {
        $this->privateKey = (string)$privateKey;
        return $this;
    }

    public function includeOriginalFunctions() {
        $path = dirname(__FILE__) . '/../../../recaptcha/recaptchalib.php';
        if (is_file($path)) {
            require_once $path;
        }
        return $this;
    }

}


<?php

namespace DMR\Mapping\Driver;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;

/**
 * The chain mapping driver enables chained mapping driver support.
 *
 * @author Marcos Passos <marcos@marcospassos.com>
 */
class Chain implements DriverInterface
{
    /**
     * @var Driver|null
     */
    private $defaultDriver;

    /**
     * @var Driver[]
     */
    private $drivers = array();

    /**
     * Adds a nested driver.
     *
     * @param DriverInterface $driver    The instance of DriverInterface
     * @param string          $namespace The namespace
     */
    public function addDriver(DriverInterface $driver, $namespace)
    {
        $this->drivers[$namespace] = $driver;
    }

    /**
     * Gets the array of nested drivers.
     *
     * @return Driver[] $drivers
     */
    public function getDrivers()
    {
        return $this->drivers;
    }

    /**
     * Gets the default driver.
     *
     * @return Driver|null
     */
    public function getDefaultDriver()
    {
        return $this->defaultDriver;
    }

    /**
     * Sets the default driver.
     *
     * @param DriverInterface $driver
     */
    public function setDefaultDriver(DriverInterface $driver)
    {
        $this->defaultDriver = $driver;
    }

    /**
     * {@inheritDoc}
     */
    public function read(ClassMetadata $classMetadata, array &$metatada)
    {
        foreach ($this->drivers as $namespace => $driver) {
            if (strpos($classMetadata->name, $namespace) === 0) {
                $driver->read($classMetadata, $metatada);

                return;
            }
        }

        if (null !== $this->defaultDriver) {
            $this->defaultDriver->read($classMetadata, $metatada);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getOriginalDriver()
    {
        // not needed here
    }

    /**
     * {@inheritDoc}
     */
    public function setOriginalDriver(MappingDriver $driver)
    {
        // not needed here
    }
}


<?php
/**
 * This file is part of the Pathfinder package.
 *
 * (c) bitExpert AG
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types = 1);

namespace bitExpert\Pathfinder;

/**
 * Class representing the outcome of a routing process
 *
 * @api
 */
class RoutingResult
{
    const FAILED_BAD_REQUEST = 400;
    const FAILED_NOT_FOUND = 404;
    const FAILED_METHOD_NOT_ALLOWED = 405;
    /**
     * @var bool
     */
    protected $success;
    /**
     * @var Route
     */
    protected $route;
    /**
     * @var array
     */
    protected $params;
    /**
     * @var int
     */
    protected $failure;

    /**
     * Creates a new {@link bitExpert\Pathfinder\RoutingResult}.
     *
     * Constructor is set private to enforce usage of factory methods for success or failure.
     */
    private function __construct()
    {
        $this->route = null;
        $this->params = [];
    }

    /**
     * Factory method to create a {@link \bitExpert\Pathfinder\RoutingResult}
     * if the routing process succeeded.
     *
     * @param Route $route
     * @param array $params
     * @return RoutingResult
     */
    public static function forSuccess(Route $route, array $params = []) : RoutingResult
    {
        $result = new self();
        $result->success = true;
        $result->route = $route;
        $result->params = $params;

        return $result;
    }

    /**
     * Factory method to create a new {@link bitExpert\Pathfinder\RoutingResult}.
     *
     * Target may be set optionally if any fallback / default target needs to be set.
     *
     * @param int $failure
     * @param Route | null $route
     * @return RoutingResult
     */
    public static function forFailure($failure, Route $route = null) : RoutingResult
    {
        $result = new self();
        $result->success = false;
        $result->failure = $failure;
        $result->route = $route;

        return $result;
    }

    /**
     * Returns the route determined by the routing process.
     *
     * If success == false, it may carry the first found possible candidate
     * which does not fulfill all criteria to match exactly.
     *
     * @return Route|null
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * Returns the failure reason if success == false.
     */
    public function getFailure() : int
    {
        return $this->failure;
    }

    /**
     * Returns the params key/value pairs determined by the routing process.
     *
     * @return array
     */
    public function getParams() : array
    {
        return $this->params;
    }

    /**
     * Returns whether the routing process succeeded.
     *
     * @return bool
     */
    public function succeeded() : bool
    {
        return $this->success;
    }

    /**
     * Returns whether the routing process failed.
     *
     * @return bool
     */
    public function failed() : bool
    {
        return !$this->success;
    }

    /**
     * Returns whether the result carries a route.
     *
     * @return bool
     */
    public function hasRoute() : bool
    {
        return (null !== $this->route);
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Http;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Autarky\Application;

/**
 * Session middleware.
 */
class SessionMiddleware implements HttpKernelInterface
{
	/**
	 * @var HttpKernelInterface
	 */
	protected $kernel;

	/**
	 * @var SessionInterface
	 */
	protected $session;

	/**
	 * Whether the sessions should always be started. Normal behaviour is to
	 * start the sesion whenever an operation is requested from it.
	 *
	 * @var bool
	 */
	protected $forceStart;

	/**
	 * Additional cookie parameters to add to the session ID cookie.
	 *
	 * @var array
	 */
	protected $cookies;

	/**
	 * @param HttpKernelInterface $kernel
	 * @param Application         $app
	 */
	public function __construct(HttpKernelInterface $kernel, Application $app)
	{
		$this->kernel = $kernel;
		$this->session = $app->getContainer()
			->resolve('Symfony\Component\HttpFoundation\Session\SessionInterface');
		$this->forceStart = $app->getConfig()
			->get('session.force', false);
		$this->cookies = $app->getConfig()
			->get('session.cookies', []);
	}

	/**
	 * {@inheritdoc}
	 */
	public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
	{
		// always set the session onto the request object.
		$request->setSession($this->session);

		// we only need to manage the session for the master request.
		// subrequests will have the session available anyways, but we will
		// be closing and setting the cookie for the master request only.
		if ($type !== HttpKernelInterface::MASTER_REQUEST) {
			return $this->kernel->handle($request, $type, $catch);
		}

		// the session may have been manually started before the middleware is
		// invoked - in this case, we cross our fingers and hope the session has
		// properly initialised itself
		if (!$this->session->isStarted()) {
			$this->initSession($request);
		}

		$response = $this->kernel->handle($request, $type, $catch);

		// if the session has started, save it and attach the session cookie. if
		// the session has not started, there is nothing to save and there is no
		// point in attaching a cookie to persist it.
		if ($this->session->isStarted()) {
			$this->closeSession($request, $response);
		}

		return $response;
	}

	protected function initSession(Request $request)
	{
		// the name of the session cookie name.
		$sessionName = $this->session->getName();

		// if a session cookie exists, load the appropriate session ID.
		if ($request->cookies->has($sessionName)) {
			$this->session->setId($request->cookies->get($sessionName));
		}

		// in some rare cases you may want to force the session to start on
		// every request.
		if ($this->forceStart) {
			$this->session->start();
		}
	}

	protected function closeSession(Request $request, Response $response)
	{
		// save all session data
		$this->session->save();

		// attach the session cookie
		$response->headers->setCookie($this->makeCookie($request));
	}

	protected function makeCookie(Request $request)
	{
		// merge native PHP session cookie params with custom ones.
		$params = array_replace(session_get_cookie_params(), $this->cookies);

		// if the cookie lifetime is not 0 (closes when browser window closes),
		// add the request time and the lifetime to get the expiration time of
		// the cookie.
		if ($params['lifetime'] !== 0) {
			$params['lifetime'] = $request->server->get('REQUEST_TIME') + $params['lifetime'];
		}

		return new Cookie(
			$this->session->getName(),
			$this->session->getId(),
			$params['lifetime'],
			$params['path'],
			$params['domain'],
			$params['secure'],
			$params['httponly']
		);
	}
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Database;

use Autarky\Config\ConfigInterface;

/**
 * Manager for multiple database connections in the form of PDO instances and
 * configuration data.
 */
class ConnectionManager
{
	/**
	 * @var ConfigInterface
	 */
	protected $config;

	/**
	 * @var ConnectionFactory
	 */
	protected $factory;

	/**
	 * The default connection to use
	 *
	 * @var string
	 */
	protected $defaultConnection;

	/**
	 * PDO instances.
	 *
	 * @var \PDO[]
	 */
	protected $instances = [];

	/**
	 * Constructor.
	 *
	 * @param ConfigInterface $config
	 * @param ConnectionFactoryInterface $factory
	 * @param string|null $defaultConnection If null, "database.connection" is
	 * retrieved from $config
	 */
	public function __construct(
		ConfigInterface $config,
		ConnectionFactoryInterface $factory,
		$defaultConnection = null
	) {
		$this->config = $config;
		$this->factory = $factory;
		$this->defaultConnection = $defaultConnection ?: $config->get('database.connection');
	}

	/**
	 * Get a PDO instance.
	 *
	 * @param  string|null $connection Null fetches the default connection.
	 *
	 * @return \PDO
	 */
	public function getPdo($connection = null)
	{
		if ($connection === null) {
			$connection = $this->defaultConnection;
		}

		if (isset($this->instances[$connection])) {
			return $this->instances[$connection];
		}

		$config = $this->getConnectionConfig($connection);

		return $this->instances[$connection] = $this->factory->makePdo($config, $connection);
	}

	/**
	 * Get the configuration array for a specific connection.
	 *
	 * @param  string $connection The name of the connection.
	 *
	 * @return array
	 *
	 * @throws \InvalidArgumentException If connection is not defined
	 */
	public function getConnectionConfig($connection = null)
	{
		if ($connection === null) {
			$connection = $this->defaultConnection;
		}

		$config = $this->config->get("database.connections.$connection");

		if (!$config) {
			if (!is_string($connection)) {
				$connection = gettype($connection);
			}

			throw new \InvalidArgumentException("No config found for connection: $connection");
		}

		return $config;
	}
}


<?php

/**
 * Moo_EditableFieldAdmin is an admin class for managing the editable fields in the system.
 *
 * @author  Mohamed Alsharaf <mohamed.alsharaf@gmail.com>
 */
class Moo_EditableFieldAdmin extends ModelAdmin
{
    private static $url_segment    = 'editablefield';
    private static $menu_title     = 'Editable fields';
    private static $managed_models = [
        'Moo_EditableField',
        'Moo_EditableFieldGroup',
    ];
    private static $menu_icon = 'editablefield/images/icon.png';

    public function getEditForm($id = null, $fields = null)
    {
        $form = parent::getEditForm($id, $fields);

        // Customise the grid field to show icon and title
        $gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
        $config    = $gridField->getConfig();

        $config->getComponentByType('GridFieldDataColumns')
            ->setDisplayFields([
                'Type'  => 'Type',
                'Title' => 'Title',
            ])->setFieldFormatting([
                'Type' => function ($_, Moo_EditableField $field) {
                    return $field->getIconTag();
                },
            ]);

        $adder = new GridFieldAddNewMultiClass();
        $adder->setClasses($this->getCreatableFields());
        $config
            ->removeComponentsByType('GridFieldAddNewButton')
            ->addComponent($adder);

        return $form;
    }

    /**
     * Return a {@link ArrayList} of all the addable fields to populate the add
     * field menu.
     *
     * @return array
     */
    private function getCreatableFields()
    {
        $fields = ClassInfo::subclassesFor('Moo_EditableField');
        $output = [];

        if (!empty($fields)) {
            array_shift($fields); // get rid of subclass 0
            asort($fields); // get in order

            foreach ($fields as $field => $title) {
                // Skip an abstract class
                if ($field == 'Moo_EditableFieldMultipleOption') {
                    continue;
                }

                // Get the nice title and strip out field
                $niceTitle = _t($field . '.SINGULARNAME', $title);
                if ($niceTitle) {
                    $output[$field] = $niceTitle;
                }
            }
        }

        return $output;
    }
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Http;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;

use Autarky\Config\ConfigInterface;
use Autarky\Container\ClassResolverInterface;

/**
 * Session handler factory.
 *
 * @internal
 */
class SessionHandlerFactory
{
	/**
	 * @var ClassResolverInterface
	 */
	protected $container;

	/**
	 * @var ConfigInterface
	 */
	protected $config;

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

	/**
	 * Constructor.
	 *
	 * @param ClassResolverInterface $container
	 * @param ConfigInterface    $config
	 */
	public function __construct(
		ClassResolverInterface $container,
		ConfigInterface $config
	) {
		$this->container = $container;
		$this->config = $config;
		$this->factories = [
			'native'    => [$this, 'makeNativeHandler'],
			'file'      => [$this, 'makeFileHandler'],
			'pdo'       => [$this, 'makePdoHandler'],
			'mongo'     => [$this, 'makeMongoHandler'],
			'memcache'  => [$this, 'makeMemcacheHandler'],
			'memcached' => [$this, 'makeMemcachedHandler'],
			'null'      => [$this, 'makeNullHandler'],
		];
	}

	/**
	 * Define a handler factory.
	 *
	 * @param  string   $ident
	 * @param  callable $factory
	 *
	 * @return void
	 */
	public function defineFactory($ident, callable $factory)
	{
		$this->factories[$ident] = $factory;
	}

	/**
	 * Make a handler.
	 *
	 * @param  string $ident
	 *
	 * @return \SessionHandlerInterface
	 *
	 * @throws \InvalidArgumentException If ident is invalid
	 */
	public function makeHandler($ident)
	{
		if (!isset($this->factories[$ident])) {
			throw new \InvalidArgumentException("Unknown session handler: $ident");
		}

		return $this->factories[$ident]();
	}

	protected function makeNativeHandler()
	{
		return new \SessionHandler;
	}

	protected function makeFileHandler()
	{
		return new NativeFileSessionHandler($this->getSessionPath());
	}

	protected function makePdoHandler()
	{
		$pdo = $this->container->resolve('Autarky\Database\ConnectionManager')
			->getPdo($this->config->get('session.db_connection'));
		$options = $this->config->get('session.handler_options', []);
		return new PdoSessionHandler($pdo, $options);
	}

	protected function makeMongoHandler()
	{
		return new MongoDbSessionHandler($this->container->resolve('MongoClient'),
			$this->config->get('session.handler_options', []));
	}

	protected function makeMemcacheHandler()
	{
		return new MemcacheSessionHandler($this->container->resolve('Memcache'),
			$this->config->get('session.handler_options', []));
	}

	protected function makeMemcachedHandler()
	{
		return new MemcachedSessionHandler($this->container->resolve('Memcached'),
			$this->config->get('session.handler_options', []));
	}

	protected function makeNullHandler()
	{
		return new NullSessionHandler;
	}

	protected function getSessionPath()
	{
		if ($this->config->has('path.session')) {
			return $this->config->get('path.session');
		}

		if ($this->config->has('path.storage')) {
			return $this->config->get('path.storage').'/session';
		}

		return null;
	}
}


<?php

namespace Rumpel\MarvelUniverse;

use GuzzleHttp\Client;

class AbstractSuperHeroApi
{
    /**
     * @var string
     */
    private $baseUrl = 'http://gateway.marvel.com/v1/public/';

    /**
     * @var Client
     */
    protected $client;
    protected $slug;

    /**
     * @param Client $client
     */
    public function __construct(Client $client) {

        $this->client = $client;
    }

    /**
     * Get resource by id
     * @param $characterId
     * @return mixed|string
     */
    public function getById($characterId)
    {
        try {
            $result = $this->client->get($this->slug . '/' . $characterId);
        } catch (RequestException $e) {
            $return['request'] = $e->getRequest() . "\n";
            if ($e->hasResponse()) {
                return $return['response'] = $e->getResponse() . "\n";

            }
        }

        return $result->json();
    }

    /**
     * Get all from resource
     * @param array $filterAttributes
     * @return mixed
     */
    public function getAll(array $filterAttributes = [])
    {
        $filters = ['query' => [$filterAttributes]];

        try {
            $result = $this->client->get($this->slug, $filters);
        } catch (RequestException $e) {
            $return['request'] = $e->getRequest() . "\n";
            if ($e->hasResponse()) {
                return $return['response'] = $e->getResponse() . "\n";

            }
        }

        return $result->json();

    }

}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Console;

use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Command\Command as SymfonyCommand;

use Autarky\Application as AutarkyApplication;
use Autarky\Console\Command as AutarkyCommand;

/**
 * {@inheritdoc}
 */
class Application extends SymfonyApplication
{
	/**
	 * The Autarky Application object instance.
	 *
	 * @var AutarkyApplication
	 */
	protected $app;

	/**
	 * Set the Autarky application instance.
	 *
	 * @param AutarkyApplication $app
	 */
	public function setAutarkyApplication(AutarkyApplication $app)
	{
		$this->app = $app;
	}

	/**
	 * {@inheritdoc}
	 */
	public function add(SymfonyCommand $command)
	{
		if ($command instanceof AutarkyCommand) {
			$command->setAutarkyApplication($this->app);
		}

		return parent::add($command);
	}
}


<?php

/**
 * This file is part of the Pathfinder package.
 *
 * (c) bitExpert AG
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types = 1);

namespace bitExpert\Pathfinder;

use bitExpert\Slf4PsrLog\LoggerFactory;

abstract class AbstractRouter implements Router
{
    /**
     * @var \Psr\Log\LoggerInterface the logger instance.
     */
    protected $logger;
    /**
     * @var Route[]
     */
    protected $routes;

    /**
     * Creates a new {@link \bitExpert\Pathfinder\AbstractRouter}.
     *
     * @param Route[] routes
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
    public function __construct(array $routes = [])
    {
        $this->routes = [];
        $this->setRoutes($routes);
        $this->logger = LoggerFactory::getLogger(__CLASS__);
    }

    /**
     * Matches given variables against given matchers and returns
     * if all vars pass all matchers.
     *
     * @param Route $route The route to test the values against
     * @param array $params The names variables and values
     * @return bool
     */
    protected function matchParams(Route $route, array $params) : bool
    {
        $matchers = $route->getMatchers();

        foreach ($params as $name => $value) {
            if (!isset($matchers[$name])) {
                continue;
            }

            $valueMatchers = $matchers[$name];
            foreach ($valueMatchers as $matcher) {
                if (!$matcher($value)) {
                    $this->logger->debug(sprintf(
                        'Value "%s" for param "%s" did not match criteria of matcher "%s"',
                        $value,
                        $name,
                        get_class($matcher)
                    ));
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Validates given params against the required ones and
     * checks for matcher violations afterwards.
     *
     * @param Route $route
     * @param array $params
     * @param array $requiredParams
     * @throws \InvalidArgumentException
     */
    protected function validateParams(Route $route, array $params, array $requiredParams)
    {
        $identifier = $this->getRouteIdentifier($route);
        $givenParams = array_keys($params);

        $missingParams = array_diff($requiredParams, $givenParams);

        if (count($missingParams) > 0) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Error while validating params "%s": Required parameters "%s" are missing',
                    $identifier,
                    implode(', ', $missingParams)
                )
            );
        }

        if (!$this->matchParams($route, $params)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Error while validing params for target "%s": Params don\'t fulfill their matcher\'s criteria',
                    $identifier
                )
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function addRoute(Route $route)
    {
        // get the specific path matcher for this route
        $pathMatcher = $this->getPathMatcherForRoute($route);

        $this->routes[] = [
            'pathMatcher' => $pathMatcher,
            'route' => $route
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function setRoutes(array $routes)
    {
        $this->routes = [];
        foreach ($routes as $route) {
            $this->addRoute($route);
        }
    }

    /**
     * Returns the identifier string for given route.
     *
     * @param Route $route
     * @return string
     */
    protected function getRouteIdentifier(Route $route) : string
    {
        return empty($route->getName()) ? $route->getTarget() : $route->getName();
    }

    /**
     * Returns the internal identifier of the given route
     * used for matching the request.
     *
     * @param Route $route
     * @return string
     */
    abstract protected function getPathMatcherForRoute(Route $route) : string;
}


<?php
/**
 * This file is part of the Autarky package.
 *
 * (c) Andreas Lutro <anlutro@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Autarky\Events;

use Symfony\Component\Console\Application;

use Autarky\Container\ContainerInterface;
use Autarky\Providers\AbstractProvider;

/**
 * Simple service provider that binds a share instance of symfony's event
 * dispatcher onto the container.
 */
class EventDispatcherProvider extends AbstractProvider
{
	/**
	 * {@inheritdoc}
	 */
	public function register()
	{
		$dic = $this->app->getContainer();

		$dic->share('Autarky\Events\EventDispatcher');

		$dic->alias('Autarky\Events\EventDispatcher',
			'Symfony\Component\EventDispatcher\EventDispatcherInterface');

		$dic->resolvingAny(function($obj, ContainerInterface $dic) {
			if ($obj instanceof EventDispatcherAwareInterface) {
				$obj->setEventDispatcher($dic->resolve('Autarky\Events\EventDispatcher'));
			}
		});
	}

	/**
	 * {@inheritdoc}
	 */
	public function registerConsole(Application $console)
	{
		$eventDispatcher = $this->app->getContainer()
			->resolve('Symfony\Component\EventDispatcher\EventDispatcherInterface');
		$console->setDispatcher($eventDispatcher);
	}
}


<?php
namespace Aptoma\Ftp;

use Aptoma\Ftp\Exception\FtpException;
use Aptoma\Ftp\Exception\VerifySizeException;
use Psr\Log\LoggerInterface;

/**
 * Ftp wraps the native ftp functions in a nicer OO interface
 */
class Ftp
{
    private $connection;
    /**
     * @var LoggerInterface
     */
    private $logger;

    private $hostname;
    private $username;
    private $password;

    public function __construct($hostname, $username, $password, LoggerInterface $logger)
    {
        if (!extension_loaded('ftp')) {
            throw new FtpException('Missing FTP PHP extension.');
        }
        $this->hostname = $hostname;
        $this->username = $username;
        $this->password = $password;
        $this->logger = $logger;
    }

    /**
     * @param bool $state
     * @return bool
     */
    public function setPassiveMode($state)
    {
        return ftp_pasv($this->getConnection(), $state);
    }

    /**
     * @param $path
     */
    public function mkdir($path)
    {
        $this->logger->info('mkdir ' . $path);
        $parts = explode('/', $path);

        $mkTemp = '';
        foreach ($parts as $dir) {
            if ($dir == '') {
                continue;
            }
            $mkTemp .= '/' . $dir;
            $this->logger->debug('mkdir: ' . $mkTemp);
            if (@ftp_mkdir($this->getConnection(), $mkTemp)) {
                $this->logger->debug('mkdir success');
            }
        }
    }

    /**
     * @param $target
     * @param $origin
     * @param int $mode
     * @return bool
     */
    public function put($target, $origin, $mode = FTP_BINARY)
    {
        $this->logger->debug(sprintf('FTP: put from %s to %s', $origin, $target));
        return ftp_put($this->getConnection(), $target, $origin, $mode);
    }

    /**
     * @param $source
     * @param $target
     * @return bool
     */
    public function move($source, $target)
    {
        $this->logger->debug(sprintf('FTP: move from %s to %s', $source, $target));
        return ftp_rename($this->getConnection(), $source, $target);
    }

    /**
     * @param $path
     * @return bool
     */
    public function delete($path)
    {
        $this->logger->debug('FTP: delete ' . $path);
        return ftp_delete($this->getConnection(), $path);
    }

    /**
     * @param array $paths
     */
    public function preparePaths(array $paths)
    {
        foreach ($paths as $path) {
            $this->logger->debug('FTP: preparePath ' . $path);
            $this->mkdir(dirname($path));
        }
    }

    /**
     * @param $file
     * @return int
     */
    public function getSize($file)
    {
        return ftp_size($this->getConnection(), $file);
    }

    /**
     * @param $originSize
     * @param $target
     * @param null $tempTarget
     * @return bool
     */
    public function checkIfAlreadyUploaded($originSize, $target, $tempTarget = null)
    {
        $this->logger->debug('FTP: check if already uploaded', array($originSize, $target, $tempTarget));
        $targetSize = $this->getSize($target);
        $this->logger->debug('Public size: ' . $targetSize);
        $this->logger->debug('Origin size: ' . $originSize);
        if ($targetSize > 0 && $targetSize === $originSize) {
            $this->logger->info('Remote file exists, and has same size. Return.');

            return true;
        }
        if ($targetSize > 0 && $targetSize !== $originSize) {
            $this->logger->info('Remote file exists, but has different size. Remove and replace.');
            $this->delete($target);
        }

        if ($tempTarget) {
            $this->logger->debug('Temp target provided, check this one.');
            if ($this->checkIfAlreadyUploaded($originSize, $tempTarget)) {
                return $this->move($tempTarget, $target);
            } else {
                return false;
            }
        } else {
            $this->logger->debug('No temp target provided, upload needed.');
            return false;
        }
    }

    /**
     * Verify that uploaded file is the same as origin file, and if so, move to public folder
     *
     * @param $originSize
     * @param $tmpDestination
     * @param $publicDestination
     * @return bool
     * @throws FtpException
     * @throws VerifySizeException
     */
    public function verifyAndMoveUploadedFile(
        $originSize,
        $tmpDestination,
        $publicDestination
    ) {
        $remoteTempSize = $this->getSize($tmpDestination);
        $this->logger->debug('Temp size: ' . $remoteTempSize);
        $this->logger->debug('Origin size: ' . $originSize);
        if ($remoteTempSize <= 0) {
            throw new VerifySizeException('Uploaded file has size ' . $remoteTempSize);
        }

        if ($remoteTempSize !== $originSize) {
            throw new VerifySizeException(
                sprintf(
                    'Uploaded file has wrong size. Expected %s, got %s.',
                    $originSize,
                    $remoteTempSize
                )
            );
        }

        $this->logger->info('OK: Uploaded temp file has right size.');
        if (!$this->move($tmpDestination, $publicDestination)) {
            throw new FtpException('Error renaming uploaded file from temp to public.');
        }

        $remotePublicSize = $this->getSize($publicDestination);
        $this->logger->debug('Renamed size: ' . $remotePublicSize);
        if ($remotePublicSize <= 0) {
            throw new VerifySizeException('Renamed file has size ' . $remotePublicSize);
        }

        if ($remotePublicSize !== $originSize) {
            throw new VerifySizeException(
                sprintf(
                    'Renamed file has wrong size. Expected %s, got %s.',
                    $originSize,
                    $remotePublicSize
                )
            );
        }
        $this->logger->info('OK: Renamed file has right size.');

        return true;
    }

    /**
     * @return resource
     * @throws Exception\FtpException
     */
    private function getConnection()
    {
        if (!$this->connection) {
            $this->connection = ftp_connect($this->hostname);
            if (!$this->connection) {
                throw new FtpException(sprintf('Error connecting to FTP server at %s.', $this->hostname));
            }

            ftp_login($this->connection, $this->username, $this->password);
        }

        return $this->connection;
    }
}