<?php

namespace Unite\UnisysApi\Providers;

use Barryvdh\Cors\HandleCors;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Laravel\Passport\Http\Middleware\CheckClientCredentials;
use Spatie\Permission\Middlewares\PermissionMiddleware;
use Spatie\Permission\Middlewares\RoleMiddleware;
use Unite\UnisysApi\Http\Middleware\Authorize;
use Unite\UnisysApi\Http\Middleware\CacheResponse;
use Unite\UnisysApi\Http\Middleware\HttpsProtocol;

class MiddlewareServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @param Router $router
     * @return void
     */
    public function boot(Router $router)
    {
        /** @var \Illuminate\Foundation\Http\Kernel $kernel */
        $kernel = $this->app->make(Kernel::class);

        $kernel->pushMiddleware(HttpsProtocol::class);
        $kernel->pushMiddleware(HandleCors::class);

        $router->aliasMiddleware('role', RoleMiddleware::class);
        $router->aliasMiddleware('permission', PermissionMiddleware::class);
        $router->aliasMiddleware('client', CheckClientCredentials::class);
        $router->aliasMiddleware('authorize', Authorize::class);
        $router->aliasMiddleware('cache', CacheResponse::class);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Streams;

use Generics\Util\Interpolator;

/**
 * This class provides a memory stream for both input and output
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class MemoryStream implements InputOutputStream
{
    use Interpolator {
        interpolate as tinterpolate;
    }

    /**
     * The local memory buffer
     *
     * @var string
     */
    private $memory;

    /**
     * Current position in memory buffer
     *
     * @var int
     */
    private $current;

    /**
     * Whether it is possible to perform reading action
     *
     * @var boolean
     */
    private $ready;

    /**
     * Whether stream is closed
     *
     * @var boolean
     */
    private $closed;

    /**
     * Create a new MemoryStream
     *
     * @param InputStream $in
     *            optional existing input stream - will be copied
     */
    public function __construct(InputStream $in = null)
    {
        $this->memory = "";
        if ($in != null) {
            $copy = clone $in;
            $copy->reset();
            while ($copy->ready()) {
                $this->memory .= $copy->read();
            }
            $copy->close();
        }
        $this->current = 0;
        $this->ready = true;
        $this->closed = false;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::close()
     */
    public function close()
    {
        unset($this->memory);
        $this->current = 0;
        $this->ready = false;
        $this->closed = true;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::ready()
     */
    public function ready(): bool
    {
        return $this->ready;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::write()
     */
    public function write($buffer)
    {
        if ($this->closed) {
            throw new StreamException("Stream is not open");
        }
        $this->memory .= $buffer;
        $this->ready = true;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\InputStream::read()
     */
    public function read($length = 1, $offset = null): string
    {
        if ($this->closed) {
            throw new StreamException("Stream is not open");
        }

        if ($offset !== null) {
            $this->current = intval($offset);
        }

        if (strlen($this->memory) <= $this->current) {
            $this->ready = false;
            return "";
        }

        if (strlen($this->memory) - $this->current < $length) {
            $length = strlen($this->memory) - $this->current;
        }

        $out = substr($this->memory, $this->current, $length);
        $this->current += $length;

        if ($this->current == strlen($this->memory)) {
            $this->ready = false;
        }

        return $out;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Countable::count()
     */
    public function count(): int
    {
        if ($this->closed) {
            throw new StreamException("Stream is not open");
        }
        if (! isset($this->memory)) {
            return 0;
        }
        return strlen($this->memory);
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Resettable::reset()
     */
    public function reset()
    {
        if ($this->closed) {
            throw new StreamException("Stream is not open");
        }
        $this->current = 0;
        $this->ready = true;
    }

    /**
     * Write to stream by interpolation of context vars into a string
     *
     * @param string $string
     *            The string to interpolate, may contains placeholders in format {placeholder}.
     * @param array $context
     *            The context array containing the associative replacers and its values.
     */
    public function interpolate($string, array $context)
    {
        $this->write($this->tinterpolate($string, $context));
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::isWriteable()
     */
    public function isWriteable(): bool
    {
        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\OutputStream::flush()
     */
    public function flush()
    {
        if ($this->closed) {
            throw new StreamException("Stream is not open");
        }

        unset($this->memory);
        $this->memory = "";
        $this->reset();
    }

    /**
     *
     * {@inheritdoc}
     * @see \Generics\Streams\Stream::isOpen()
     */
    public function isOpen(): bool
    {
        return true;
    }

    /**
     * Retrieve the whole memory string content
     *
     * @return string
     */
    public function slurp(): string
    {
        $str = "";
        while ($this->ready()) {
            $str .= $this->read($this->count());
        }

        return $str;
    }
}


<?php

declare(strict_types=1);

namespace Chiron\Container;

class Definition implements DefinitionInterface
{
    /** @var array */
    public $assigns = [];

    /**
     * {@inheritdoc}
     */
    public function assign(string $paramName, $target): DefinitionInterface
    {
        $this->assigns[$paramName] = $target;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function assignMany(array $params = []): DefinitionInterface
    {
        $this->assigns = $params + $this->assigns;

        return $this;
    }

    public function getAssigns(): array
    {
        return $this->convertAssign($this->assigns);
    }

    /**
     * @param array $arguments
     *
     * @return array
     */
    // TODO : code à virer
    protected function convertAssign(array $arguments): array
    {
        $argumentsToReturn = [];
        foreach ($arguments as $key => $value) {
            if (is_array($value)) {
                if (array_key_exists('value', $value)) {
                    $argumentsToReturn[$key] = $value['value'];
                }
                //} else {
            //    if ($this->container->has($value)) {
            //        $argumentsToReturn[$key] = $this->container->get($value);
            //    }
            }
        }

        return $argumentsToReturn;
    }

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

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

    /**
     * @var bool
     */
    protected $shared = false;

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

    /**
     * Constructor.
     *
     * @param string $id
     * @param mixed  $concrete
     */
    public function __construct(string $id, $concrete = null)
    {
        $concrete = $concrete ?? $id;
        $this->alias = $id;
        $this->concrete = $concrete;
    }

    /**
     * {@inheritdoc}
     */
    public function setAlias(string $id): DefinitionInterface
    {
        $this->alias = $id;

        return $this;
    }

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

    /**
     * {@inheritdoc}
     */
    public function setShared(bool $shared = true): DefinitionInterface
    {
        $this->shared = $shared;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function isShared(): bool
    {
        return $this->shared;
    }

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

    /**
     * {@inheritdoc}
     */
    public function setConcrete($concrete): DefinitionInterface
    {
        $this->concrete = $concrete;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addArgument($arg): DefinitionInterface
    {
        $this->arguments[] = $arg;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addArguments(array $args): DefinitionInterface
    {
        foreach ($args as $arg) {
            $this->addArgument($arg);
        }

        return $this;
    }
}


<?php

namespace ThemeManager;

use Illuminate\Support\Collection;

class ThemeCollection extends Collection
{
    /**
     * @var bool
     */
    protected $exceptionOnInvalid = false;

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

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

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

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

    /**
     * Create a new theme collection.
     *
     * @param mixed   $items
     * @param bool $themesFolder
     * @param array   $requiredFields
     * @param bool $exceptionOnInvalid
     */
    public function __construct($items = [], $themesFolder = false, array $requiredFields = [], $exceptionOnInvalid = false)
    {
        $this->requiredFields = $requiredFields;
        $this->exceptionOnInvalid = $exceptionOnInvalid;

        if (is_string($themesFolder)) {
            $themesFolder = realpath($themesFolder);
            $this->themesFolders[$themesFolder] = $themesFolder;
        }
        $this->separateInvalidItems($items);

        parent::__construct($items);

        /* @var $theme Theme */
        foreach ($this->items as $theme) {
            if ($theme instanceof Theme) {
                $this->themeNames[] = $theme->getName();
            }
        }
    }

    /**
     * @param mixed          $items
     * @param string|bool $addPath
     *
     * @return static
     */
    public function merge($items, $addPath = false)
    {
        $themesPaths = $this->getThemesPaths();
        /* @var $themeCollection $this */
        $themeCollection = parent::merge($items);

        $themeCollection->requiredFields = $this->requiredFields;
        $themeCollection->exceptionOnInvalid = $this->exceptionOnInvalid;

        if ($addPath !== false) {
            $themesPaths[] = realpath($addPath);
        }
        foreach ($themesPaths as $path) {
            $themeCollection->themesFolders[$path] = $path;
        }

        return $themeCollection;
    }

    /**
     * @return array
     */
    public function getRequiredFields()
    {
        return $this->requiredFields;
    }

    /**
     * @return bool
     */
    public function getExceptionOnInvalid()
    {
        return $this->exceptionOnInvalid;
    }

    /**
     * @return array
     */
    public function getThemesPaths()
    {
        return $this->themesFolders;
    }

    /**
     * @param string $themesFolder
     *
     * @return bool
     */
    public function pathExists($themesFolder)
    {
        return is_string($themesFolder) && in_array(realpath($themesFolder), $this->themesFolders);
    }

    /**
     * @param $items
     *
     * @return $this
     */
    public function separateInvalidItems(&$items)
    {
        foreach ($items as $key => $theme) {
            if ($theme instanceof Theme && $theme->hasError()) {
                $this->invalidThemes[] = $theme;
                unset($items[$key]);
            }
        }
        array_values(array_filter($items));

        return $this;
    }

    /**
     * @return int
     */
    public function invalidCount()
    {
        return count($this->invalidThemes);
    }

    /**
     * @return array
     */
    public function getInvalidThemes()
    {
        return $this->invalidThemes;
    }

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

    /**
     * @return array
     */
    public function getValidThemes()
    {
        return $this->all();
    }

    /**
     * @param $name
     *
     * @return bool|Theme
     */
    public function getTheme($name)
    {
        /* @var $theme Theme */
        foreach ($this->items as $theme) {
            if ($theme instanceof Theme && $theme->getName() == $name) {
                return $theme;
            }
        }

        return false;
    }

    /**
     * @return array
     */
    public function allThemeNames()
    {
        return $this->themeNames;
    }

    /**
     * @param $name
     *
     * @return bool
     */
    public function themeExists($name)
    {
        return in_array($name, $this->themeNames) && ! is_null($this->getTheme($name));
    }
}


<?php

namespace hypeJunction\Prototyper\Elements;

class Form {

	/**
	 * Elgg entity
	 * @var \ElggEntity
	 */
	private $entity;

	/**
	 * Action name
	 * @var string
	 */
	private $action;

	/**
	 * Collection of fields
	 * @var FieldCollection
	 */
	private $fields;

	/**
	 * Constructor
	 *
	 * @param \ElggEntity     $entity Entity
	 * @param string          $action Action name
	 * @param FieldCollection $fields Fields
	 */
	public function __construct(\ElggEntity $entity, $action, FieldCollection $fields) {
		$this->entity = $entity;
		$this->action = $action;
		$this->fields = $fields;
	}

	/**
	 * Filter fields
	 *
	 * @param callable $filter
	 * @return self
	 */
	public function filter(callable $filter) {
		$this->fields = $this->fields->filter($filter);
		return $this;
	}

	/**
	 * Returns form body HTML
	 * @return string
	 */
	public function viewBody() {

		// Get sticky values
		$sticky_values = hypePrototyper()->prototype->getStickyValues($this->action);
		hypePrototyper()->prototype->clearStickyValues($this->action);

		// Get validation errors and messages
		$validation_status = hypePrototyper()->prototype->getValidationStatus($this->action);
		hypePrototyper()->prototype->clearValidationStatus($this->action);

		// Prepare fields
		$i = 0;
		foreach ($this->fields as $field) {

			if (!$field instanceof Field) {
				continue;
			}

			if ($field->getInputView() === false) {
				continue;
			}

			$shortname = $field->getShortname();
			if (isset($sticky_values[$shortname])) {
				$field->setStickyValue($sticky_values[$shortname]);
			}

			if (isset($validation_status[$shortname])) {
				$field->setValidation($validation_status[$shortname]['status'], $validation_status[$shortname]['messages']);
			}

			$output .= $field->viewInput(array(
				'index' => $i,
				'entity' => $this->entity,
			));

			$i++;
		}

		$submit = elgg_view('prototyper/input/submit', array(
			'entity' => $this->entity,
			'action' => $this->action,
		));

		$output .= elgg_format_element('div', array(
			'class' => 'elgg-foot',
				), $submit);

		return $output;
	}

	/**
	 * View full form
	 *
	 * @param array $vars View vars
	 * @return string
	 */
	function view(array $vars = array()) {
		$attrs = $this->getFormAttributes();
		return elgg_view('input/form', array_merge($attrs, $vars));
	}

	/**
	 * Returns form attributes
	 * @return array
	 */
	public function getFormAttributes() {
		return array(
			'body' => $this->viewBody(),
			'enctype' => $this->getEncoding(),
			'action' => "action/$this->action",
		);
	}

	/**
	 * Returns form encoding
	 * @return string
	 */
	public function getEncoding() {
		if ($this->isMultipart()) {
			return 'multipart/form-data';
		}
		return 'application/x-www-form-urlencoded';
	}

	/**
	 * Checks if the form contains file inputs
	 * @return boolean
	 */
	function isMultipart() {
		foreach ($this->fields as $field) {
			if (!$field instanceof Field) {
				continue;
			}
			if ($field->getType() == 'file' || $field->getValueType() == 'file' || $field->getDataType()) {
				return true;
			}
		}
		return false;
	}

}


<?php
/**
 * @link      http://github.com/zetta-code/zend-bootstrap for the canonical source repository
 * @copyright Copyright (c) 2018 Zetta Code
 */

namespace Zetta\ZendBootstrap\View\Helper;

use RecursiveIteratorIterator;
use Zend\Navigation\AbstractContainer;
use Zend\Navigation\Page\AbstractPage;
use Zend\View\Exception;
use Zend\View\Helper\Navigation\Menu as ZendMenu;

class Menu extends ZendMenu
{
    /**
     * default CSS class to use for li elements
     *
     * @var string
     */
    protected $defaultLiClass = 'nav-item';

    /**
     * CSS class to use for the ul sub-menu element
     *
     * @var string
     */
    protected $subUlClass = 'dropdown-menu';

    /**
     * CSS class to use for the 1. level (NOT root level!) ul sub-menu element
     *
     * @var string
     */
    protected $subUlClassLevel1 = 'dropdown-menu';

    /**
     * CSS class to use for the active li sub-menu element
     *
     * @var string
     */
    protected $subLiClassLevel0 = 'dropdown';

    /**
     * CSS class to use for the active li sub-menu element
     *
     * @var string
     */
    protected $subLiClassLevelN = 'dropdown-submenu';

    /**
     * CSS class to use for the active li sub-menu element
     *
     * @var string
     */
    protected $subAClassLevel0 = 'dropdown-toggle';

    /**
     * CSS class to use for the active li sub-menu element
     *
     * @var string
     */
    protected $subAClassLevelN = 'dropdown-submenu-toggle';

    /**
     * HREF string to use for the sub-menu toggle element's HREF attribute,
     * to override current page's href/'htmlify' setting
     *
     * @var string
     */
    protected $hrefSubToggleOverride = null;

    /**
     * Partial view script to use for rendering menu link/item
     *
     * @var array
     */
    protected $pagePartials = [];

    /**
     * @inheritdoc
     */
    protected function renderNormalMenu(
        AbstractContainer $container,
        $ulClass,
        $indent,
        $minDepth,
        $maxDepth,
        $onlyActive,
        $escapeLabels,
        $addClassToListItem,
        $liActiveClass
    )
    {
        $html = '';

        // find deepest active
        $found = $this->findActive($container, $minDepth, $maxDepth);

        /* @var $escaper \Zend\View\Helper\EscapeHtmlAttr */
        $escaper = $this->view->plugin('escapeHtmlAttr');

        if ($found) {
            $foundPage = $found['page'];
            $foundDepth = $found['depth'];
        } else {
            $foundPage = null;
        }

        // create iterator
        $iterator = new RecursiveIteratorIterator(
            $container,
            RecursiveIteratorIterator::SELF_FIRST
        );

        if (is_int($maxDepth)) {
            $iterator->setMaxDepth($maxDepth);
        }

        // iterate container
        $prevDepth = -1;
        foreach ($iterator as $page) {
            $depth = $iterator->getDepth();
            $page->set('depth', $depth);
            $isActive = $page->isActive(true);
            if ($depth < $minDepth || !$this->accept($page)) {
                // page is below minDepth or not accepted by acl/visibility
                continue;
            } elseif ($onlyActive && !$isActive) {
                // page is not active itself, but might be in the active branch
                $accept = false;
                if ($foundPage) {
                    if ($foundPage->hasPage($page)) {
                        // accept if page is a direct child of the active page
                        $accept = true;
                    } elseif ($foundPage->getParent()->hasPage($page)) {
                        // page is a sibling of the active page...
                        if (!$foundPage->hasPages(!$this->renderInvisible)
                            || is_int($maxDepth) && $foundDepth + 1 > $maxDepth
                        ) {
                            // accept if active page has no children, or the
                            // children are too deep to be rendered
                            $accept = true;
                        }
                    }
                }
                if (!$accept) {
                    continue;
                }
            }

            // make sure indentation is correct
            $depth -= $minDepth;
            $myIndent = $indent . str_repeat('        ', $depth);
            if ($depth > $prevDepth) {
                // start new ul tag
                $ulClass = '' .
                    ($depth == 0 ? $this->getUlClass() :
                        ($depth == 1 ? $this->getSubUlClassLevel1() : $this->getSubUlClass())
                    );
                if (strlen($ulClass) > 0) {
                    $ulClass = ' class="' . $escaper($ulClass) . '"';
                }
                $html .= $myIndent . '
' . PHP_EOL;
            } elseif ($prevDepth > $depth) {
                // close li/ul tags until we're at current depth
                for ($i = $prevDepth; $i > $depth; $i--) {
                    $ind = $indent . str_repeat('        ', $i);
                    $html .= $ind . '
' . PHP_EOL;
                    $html .= $ind . '
' . PHP_EOL;
                }
                // close previous li tag
                $html .= $myIndent . '
' . PHP_EOL;
            } else {
                // close previous li tag
                $html .= $myIndent . '
' . PHP_EOL;
            }

            // render li tag and page
            $liClasses = [];

            // Is page active?
            if ($isActive) {
                $liClasses[] = $liActiveClass;
            }
            if (!empty($this->getDefaultLiClass())) {
                $liClasses[] = $this->getDefaultLiClass();
            }
            $isBelowMaxLevel = ($maxDepth > $depth) || ($maxDepth === null) || ($maxDepth === false);
            if ($page->hasPages(! $this->renderInvisible) && $isBelowMaxLevel) {
                $liClasses[] = ($depth == 0 ? $this->getSubLiClassLevel0() : $this->getSubLiClassLevelN());
            }
            // Add CSS class from page to

            if ($addClassToListItem && $page->getClass()) {
                $liClasses[] = $page->getClass();
            }
            if ($page->get('liClass')) {
                $liClasses[] = $page->get('liClass');
            }
            $liClass = empty($liClasses) ? '' : ' class="' . $escaper(implode(' ', $liClasses)) . '"';
            $html .= $myIndent . '
' . PHP_EOL
                . $myIndent . '        ' . $this->htmlify($page, $escapeLabels, $addClassToListItem) . PHP_EOL;

            // store as previous depth for next iteration
            $prevDepth = $depth;
        }

        if ($html) {
            // done iterating container; close open ul/li tags
            for ($i = $prevDepth + 1; $i > 0; $i--) {
                $myIndent = $indent . str_repeat('        ', $i - 1);
                $html .= $myIndent . '
' . PHP_EOL
                    . $myIndent . '
' . PHP_EOL;
            }
            $html = rtrim($html, PHP_EOL);
        }

        return $html;
    }

    /**
     * @inheritdoc
     */
    public function htmlify(AbstractPage $page, $escapeLabel = true, $addClassToListItem = false)
    {
        $partial = $this->getPagePartial(get_class($page));
        if ($partial) {
            return $this->htmlifyWithPartial($page, $escapeLabel, $addClassToListItem, $partial);
        }

        // get attribs for element
        $attribs = [
            'id' => $page->getId(),
            'title' => $this->translate($page->getTitle(), $page->getTextDomain()),
        ];

        $classnames = [];
        if ($addClassToListItem === false) {
            $class = $page->getClass();
            if (!empty($class)) {
                $classnames[] = $page->getClass();
            }
        }
        $maxDepth = $this->getMaxDepth();
        $depth = $page->get('depth');
        $isBelowMaxLevel = ($maxDepth > $depth) || ($maxDepth === null) || ($maxDepth === false);
        if ($page->hasPages(! $this->renderInvisible) && $isBelowMaxLevel) {
            $classnames[] = $depth == 0 ? $this->getSubAClassLevel0() : $this->getSubAClassLevelN();
            $attribs['data-toggle'] = 'dropdown';
        }
        $attribs['class'] = implode(" ", $classnames);

        // add additional attributes
        $attr = $page->get('attribs');
        if (is_array($attr)) {
            $attribs = $attribs + $attr;
        }

        // does page have a href?
        if ($page->hasPages(! $this->renderInvisible) && !empty($this->getHrefSubToggleOverride())) {
            $href = $this->getHrefSubToggleOverride();
        } else {
            $href = $page->getHref();
        }
        if ($href) {
            $element = 'a';
            $attribs['href'] = $href;
            $attribs['target'] = $page->getTarget();
        } else {
            $element = 'span';
        }

        $html = '<' . $element . $this->htmlAttribs($attribs) . '>';
        $addonLeft = $page->get('addon-left');
        if ($addonLeft) {
            $html .= $addonLeft;
        }
        $label = $this->translate($page->getLabel(), $page->getTextDomain());
        if ($escapeLabel === true) {
            /** @var \Zend\View\Helper\EscapeHtml $escaper */
            $escaper = $this->view->plugin('escapeHtml');
            $html .= $escaper($label);
        } else {
            $html .= $label;
        }
        $addonRight = $page->get('addon-right');
        if ($addonRight) {
            $html .= $addonRight;
        }
        $html .= '</' . $element . '>';

        return $html;
    }

    /**
     * Renders the given $page by invoking the partial view helper
     *
     * The container will simply be passed on as a model to the view script
     * as-is, and will be available in the partial script as 'container', e.g.
     * echo 'Number of pages: ', count($this->container);.
     *
     * @param  AbstractPage $page page to generate HTML for
     * @param  bool $escapeLabel Whether or not to escape the label
     * @param  bool $addClassToListItem Whether or not to add the page class to the list item
     * @param  string|array $partial [optional] partial view script to use.
     *                                    Default is to use the partial
     *                                    registered in the helper. If an array
     *                                    is given, it is expected to contain two
     *                                    values; the partial view script to use,
     *                                    and the module where the script can be
     *                                    found.
     * @return string
     * @throws Exception\RuntimeException if no partial provided
     * @throws Exception\InvalidArgumentException if partial is invalid array
     */
    public function htmlifyWithPartial(AbstractPage $page, $escapeLabel = true, $addClassToListItem = false, $partial = null)
    {
        if (null === $partial) {
            $partial = $this->getPartial();
        }

        if (empty($partial)) {
            throw new Exception\RuntimeException(
                'Unable to render menu: No partial view script provided'
            );
        }

        $model = [
            'page' => $page,
            'escapeLabel' => $escapeLabel,
            'addClassToListItem' => $addClassToListItem,
            'menu' => (clone $this),

        ];

        /** @var \Zend\View\Helper\Partial $partialHelper */
        $partialHelper = $this->view->plugin('partial');
        if (is_array($partial)) {
            if (count($partial) != 2) {
                throw new Exception\InvalidArgumentException(
                    'Unable to render menu: A view partial supplied as '
                    . 'an array must contain two values: partial view '
                    . 'script and module where script can be found'
                );
            }

            return $partialHelper($partial[0], $model);
        }

        return $partialHelper($partial, $model);
    }

    /**
     * Normalizes given render options.
     *
     * @param  array $options [optional] options to normalize
     * @return array
     */
    protected function normalizeOptions(array $options = [])
    {
        $options = parent::normalizeOptions($options);
        if (isset($options['subLiClassLevel0']) && $options['subLiClassLevel0'] !== null) {
            $options['subLiClassLevel0'] = (string) $options['subLiClassLevel0'];
        } else {
            $options['subLiClassLevel0'] = $this->getSubLiClassLevel0();
        }

        return $options;
    }

    /**
     * Get the Menu defaultLiClass
     * @return string
     */
    public function getDefaultLiClass()
    {
        return $this->defaultLiClass;
    }

    /**
     * Set the Menu defaultLiClass
     * @param string $defaultLiClass
     * @return Menu
     */
    public function setDefaultLiClass($defaultLiClass)
    {
        $this->defaultLiClass = $defaultLiClass;
        return $this;
    }

    /**
     * Get the Menu subUlClass
     * @return string
     */
    public function getSubUlClass()
    {
        return $this->subUlClass;
    }

    /**
     * Set the Menu subUlClass
     * @param string $subUlClass
     * @return Menu
     */
    public function setSubUlClass($subUlClass)
    {
        $this->subUlClass = $subUlClass;
        return $this;
    }

    /**
     * Get the Menu subUlClassLevel1
     * @return string
     */
    public function getSubUlClassLevel1()
    {
        return $this->subUlClassLevel1;
    }

    /**
     * Set the Menu subUlClassLevel1
     * @param string $subUlClassLevel1
     * @return Menu
     */
    public function setSubUlClassLevel1($subUlClassLevel1)
    {
        $this->subUlClassLevel1 = $subUlClassLevel1;
        return $this;
    }

    /**
     * Get the Menu subLiClassLevel0
     * @return string
     */
    public function getSubLiClassLevel0()
    {
        return $this->subLiClassLevel0;
    }

    /**
     * Set the Menu subLiClassLevel0
     * @param string $subLiClassLevel0
     * @return Menu
     */
    public function setSubLiClassLevel0($subLiClassLevel0)
    {
        $this->subLiClassLevel0 = $subLiClassLevel0;
        return $this;
    }

    /**
     * Get the Menu subLiClassLevelN
     * @return string
     */
    public function getSubLiClassLevelN()
    {
        return $this->subLiClassLevelN;
    }

    /**
     * Set the Menu subLiClassLevelN
     * @param string $subLiClassLevelN
     * @return Menu
     */
    public function setSubLiClassLevelN($subLiClassLevelN)
    {
        $this->subLiClassLevelN = $subLiClassLevelN;
        return $this;
    }

    /**
     * Get the Menu subAClassLevel0
     * @return string
     */
    public function getSubAClassLevel0()
    {
        return $this->subAClassLevel0;
    }

    /**
     * Set the Menu subAClassLevel0
     * @param string $subAClassLevel0
     * @return Menu
     */
    public function setSubAClassLevel0($subAClassLevel0)
    {
        $this->subAClassLevel0 = $subAClassLevel0;
        return $this;
    }

    /**
     * Get the Menu subAClassLevelN
     * @return string
     */
    public function getSubAClassLevelN()
    {
        return $this->subAClassLevelN;
    }

    /**
     * Set the Menu subAClassLevelN
     * @param string $subAClassLevelN
     * @return Menu
     */
    public function setSubAClassLevelN($subAClassLevelN)
    {
        $this->subAClassLevelN = $subAClassLevelN;
        return $this;
    }

    /**
     * Get the Menu hrefSubToggleOverride
     * @return string
     */
    public function getHrefSubToggleOverride()
    {
        return $this->hrefSubToggleOverride;
    }

    /**
     * Set the Menu hrefSubToggleOverride
     * @param string $hrefSubToggleOverride
     * @return Menu
     */
    public function setHrefSubToggleOverride($hrefSubToggleOverride)
    {
        $this->hrefSubToggleOverride = $hrefSubToggleOverride;
        return $this;
    }

    /**
     * Sets which partial view script to use for rendering menu
     * @param    string $page
     * @param    string|array $partial partial view script or null. If an array is
     *                                given, it is expected to contain two
     *                                values; the partial view script to use,
     *                                and the module where the script can be
     *                                found.
     * @return Menu
     */
    public function putPagePartial($page, $partial)
    {
        if (null === $partial || is_string($partial) || is_array($partial)) {
            $this->pagePartials[$page] = $partial;
        }

        return $this;
    }

    /**
     * Returns partial view script to use for rendering menu
     * @param string $page
     * @return string|array|null
     */
    public function getPagePartial($page)
    {
        if (isset($this->pagePartials[$page])) {
            return $this->pagePartials[$page];
        }

        return null;
    }
}


<?php

namespace hypeJunction\Prototyper\Elements;

class ActionController {

	/**
	 * Elgg entity
	 * @var \ElggEntity
	 */
	private $entity;

	/**
	 * Action name
	 * @var string
	 */
	private $action;

	/**
	 * Collection of fields
	 * @var FieldCollection
	 */
	private $fields;

	/**
	 * Constructor
	 *
	 * @param \ElggEntity     $entity Entity
	 * @param string          $action Action name
	 * @param FieldCollection $fields Fields
	 */
	public function __construct(\ElggEntity $entity, $action, FieldCollection $fields) {
		$this->entity = $entity;
		$this->action = $action;
		$this->fields = $fields;
	}

	/**
	 * Filter fields
	 *
	 * @param callable $filter
	 * @return self
	 */
	public function filter(callable $filter) {
		$this->fields = $this->fields->filter($filter);
		return $this;
	}

	/**
	 * Full action script
	 * Validates the input, updates the entity and forwards users with feedback
	 * @return void
	 */
	public function handle() {

		try {
			if ($this->validate()) {
				$result = $this->update();
			}
		} catch (\hypeJunction\Exceptions\ActionValidationException $ex) {
			register_error(elgg_echo('prototyper:validate:error'));
			forward(REFERER);
		} catch (\IOException $ex) {
			register_error(elgg_echo('prototyper:io:error', array($ex->getMessage())));
			forward(REFERER);
		} catch (\Exception $ex) {
			register_error(elgg_echo('prototyper:handle:error', array($ex->getMessage())));
			forward(REFERER);
		}

		if ($result) {
			system_message(elgg_echo('prototyper:action:success'));
			forward($this->entity->getURL());
		} else {
			register_error(elgg_echo('prototyper:action:error'));
			forward(REFERER);
		}
	}

	/**
	 * Validate user input
	 * @return bool
	 * @throws \hypeJunction\Exceptions\ActionValidationException
	 */
	public function validate() {

		hypePrototyper()->prototype->saveStickyValues($this->action);

		$valid = true;

		foreach ($this->fields as $field) {
			if (!$field instanceof Field) {
				continue;
			}

			$validation = $field->validate($this->entity);
			hypePrototyper()->prototype->setFieldValidationStatus($this->action, $field->getShortname(), $validation);

			if (!$validation->isValid()) {
				$valid = false;
			}
		}

		if (!$valid) {
			throw new \hypeJunction\Exceptions\ActionValidationException("Invalid input");
		}

		hypePrototyper()->prototype->clearStickyValues($this->action);
		return true;
	}

	/**
	 * Updates entity information with user input values
	 * @return \ElggEntity|false
	 */
	public function update() {

		hypePrototyper()->prototype->saveStickyValues($this->action);

		// first handle attributes
		foreach ($this->fields as $field) {
			if ($field->getDataType() == 'attribute') {
				$this->entity = $field->handle($this->entity);
			}
		}

		if (!$this->entity->save()) {
			return false;
		}

		foreach ($this->fields as $field) {
			if ($field->getDataType() !== 'attribute') {
				$this->entity = $field->handle($this->entity);
			}
		}

		if (!$this->entity->save()) {
			return false;
		}

		hypePrototyper()->prototype->clearStickyValues($this->action);
		return $this->entity;
	}

}


<?php
namespace yimaTheme;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\InitProviderInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\ModuleEvent;
use Zend\ModuleManager\ModuleManagerInterface;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\ViewHelperProviderInterface;
use Zend\ServiceManager\ServiceManager;

/**
 * Class Module
 * @package yimaTheme
 */
class Module implements
    InitProviderInterface,
    ServiceProviderInterface,
    ViewHelperProviderInterface,
    ConfigProviderInterface,
    AutoloaderProviderInterface
{
    /**
     * @var ModuleManagerInterface
     */
    protected $manager;

    /**
     * Initialize workflow
     *
     * @param \Zend\ModuleManager\ModuleManagerInterface $moduleModuleManager
     * @internal param \Zend\ModuleManager\ModuleManagerInterface $manager
     * @return void
     */
    public function init(ModuleManagerInterface $moduleModuleManager)
    {
        $events = $moduleModuleManager->getEventManager();
        $events->attach(
            ModuleEvent::EVENT_LOAD_MODULES_POST,
            array($this,'initThemeManager'),
            -100000
        );

        $events->attach(
            ModuleEvent::EVENT_LOAD_MODULES_POST,
            array($this,'onLoadModulesPostAddServices'),
            -100000
        );
    }

    /**
     * ! Because we wan't share by default set to false
     *
    * @param ModuleEvent $e
    */
    public function onLoadModulesPostAddServices(ModuleEvent $e)
    {
        /** @var $moduleManager \Zend\ModuleManager\ModuleManager */
        $moduleManager = $e->getTarget();
        // $sharedEvents = $moduleManager->getEventManager()->getSharedManager();

        /** @var $sm ServiceManager */
        $sm      = $moduleManager->getEvent()->getParam('ServiceManager');
        $sm->setInvokableClass('yimaTheme.ThemeObject', 'yimaTheme\Theme\Theme', false);
    }

    /**
     * Get Theme Manager Service and init them
     *
     * @param ModuleEvent $e
     * @throws \Exception
     */
    public function initThemeManager(ModuleEvent $e)
    {
        /** @var $moduleManager \Zend\ModuleManager\ModuleManager */
        $moduleManager = $e->getTarget();
        // $sharedEvents = $moduleManager->getEventManager()->getSharedManager();

        $sm = $moduleManager->getEvent()->getParam('ServiceManager');
        $themManager = $sm->get('yimaTheme.Manager');
        if (!$themManager instanceof ManagerInterface) {
            throw new \Exception(sprintf(
                    'yimaTheme theme manager most instance of "ManagerInterface" but "%s" given.'
                    , get_class($themManager)
            ));
        }

        $themManager->init();
    }

    /**
     * Expected to return \Zend\ServiceManager\Config object or array to
     * seed such an object.
     *
     * @return array|\Zend\ServiceManager\Config
     */
    public function getServiceConfig()
    {
        return array (
            'invokables' => array (
                'yimaTheme.Manager' => 'yimaTheme\Manager',
                'yimaTheme.Manager.ListenerAggregate' => 'yimaTheme\Manager\DefaultListenerAggregate',
                'yimaTheme.ThemeLocator' => 'yimaTheme\Theme\Locator',
                    // because of this is shared serv. and with cloning problem -
                    // (we have to reset each objects).
                    // this model service set with service method with share by -
                    // default set to false
                    // on init module
                    # 'yimaTheme.ThemeObject'  => 'yimaTheme\Theme\Theme',
            ),
        );
    }

    /**
     * Expected to return \Zend\ServiceManager\Config object or array to
     * seed such an object.
     *
     * @return array|\Zend\ServiceManager\Config
     */
    public function getViewHelperConfig()
    {
        return array(
            'invokables' => array(
                'theme' => 'yimaTheme\View\Helper\ThemeHelper',
            ),
        );
    }

    /**
     * Returns configuration to merge with application configuration
     *
     * @return array|\Traversable
     */
    public function getConfig()
    {
        return include __DIR__ . '/../../config/module.config.php';
    }

    /**
     * Return an array for passing to Zend\Loader\AutoloaderFactory.
     *
     * @return array
     */
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__,
                ),
            ),
        );
    }

}


<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Socket;

/**
 * This class provides a basic client socket implementation
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class ServerSocket extends Socket
{

    /**
     * Create a new server socket
     *
     * @param Endpoint $endpoint
     *            The endpoint to use
     *
     * @throws SocketException In case of creation of socket has failed or socket options could not be set.
     */
    public function __construct(Endpoint $endpoint)
    {
        parent::__construct($endpoint);
        if (! @socket_set_option($this->handle, SOL_SOCKET, SO_REUSEADDR, 1)) {
            $code = socket_last_error($this->handle);
            throw new SocketException(socket_strerror($code), array(), $code);
        }
    }

    /**
     * Creates a service at the given endpoint
     *
     * @throws SocketException in case of it is not possible to serve due to binding or listening error
     */
    public function serve(ServiceCallback $callback)
    {
        $this->bind();

        $this->listen();

        $runOn = true;

        while ($runOn) {
            $clientHandle = @socket_accept($this->handle);

            if (! is_resource($clientHandle)) {
                $code = socket_last_error($this->handle);
                throw new SocketException(socket_strerror($code), array(), $code);
            }

            $address = null;
            $port = 0;
            if (! @socket_getpeername($clientHandle, $address, $port)) {
                $code = socket_last_error($clientHandle);
                throw new SocketException(socket_strerror($code), array(), $code);
            }

            $client = new ClientSocket(new Endpoint($address, $port), $clientHandle);

            $runOn = boolval($callback->callback($client));
        }
    }

    /**
     * Bind the server socket to the given endpoint
     *
     * @throws SocketException in case of binding has failed
     */
    private function bind()
    {
        if (! @socket_bind($this->handle, $this->endpoint->getAddress(), $this->endpoint->getPort())) {
            $code = socket_last_error($this->handle);
            throw new SocketException(socket_strerror($code), array(), $code);
        }
    }

    /**
     * Listen to the binded socket endpoint
     *
     * @throws SocketException in case of listening is not possible
     */
    private function listen()
    {
        if (! @socket_listen($this->handle, 5)) {
            $code = socket_last_error($this->handle);
            throw new SocketException(socket_strerror($code), array(), $code);
        }
    }
}


<?php
/**
 * Abstract complex query class.
 *
 * @author    Iron Bound Designs
 * @since     1.0
 * @license   MIT
 * @copyright Iron Bound Designs, 2015.
 */

namespace IronBound\DBLogger;

use IronBound\DB\Model;
use IronBound\DB\Query\Builder;
use IronBound\DB\Query\Complex_Query;
use IronBound\DB\Query\Tag\From;
use IronBound\DB\Query\Tag\Where;
use IronBound\DB\Query\Tag\Where_Date;

/**
 * Class LogQuery
 * @package IronBound\DBLogger
 */
class LogQuery extends Complex_Query {

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

	/**
	 * Constructor.
	 *
	 * @param AbstractTable $table
	 * @param string        $model_class
	 * @param array         $args
	 */
	public function __construct( AbstractTable $table, $model_class, array $args ) {

		$this->model_class = $model_class;

		parent::__construct( $table, $args );
	}

	/**
	 * Get the default args.
	 *
	 * @since 1.0
	 *
	 * @return array
	 */
	protected function get_default_args() {
		return wp_parse_args( array(
			'level'        => '',
			'message'      => '',
			'group'        => '',
			'time'         => '',
			'user'         => '',
			'user__in'     => array(),
			'user__not_in' => array()
		), parent::get_default_args() );
	}

	/**
	 * Convert data to its object.
	 *
	 * @since 1.0
	 *
	 * @param \stdClass $data
	 *
	 * @return Model
	 */
	protected function make_object( \stdClass $data ) {

		$class = $this->model_class;

		return new $class( $data );
	}

	/**
	 * Build the sql query.
	 *
	 * @since 1.0
	 *
	 * @return string
	 */
	protected function build_sql() {

		$builder = new Builder();

		$select = $this->parse_select();
		$from   = new From( $this->table->get_table_name( $GLOBALS['wpdb'] ), 'q' );

		$where = new Where( 1, true, 1 );

		if ( ( $message = $this->parse_message() ) !== null ) {
			$where->qAnd( $message );
		}

		if ( ( $level = $this->parse_level() ) !== null ) {
			$where->qAnd( $level );
		}

		if ( ( $user = $this->parse_user() ) !== null ) {
			$where->qAnd( $user );
		}

		if ( ( $group = $this->parse_group() ) !== null ) {
			$where->qAnd( $group );
		}

		if ( ( $time = $this->parse_time() ) !== null ) {
			$where->qAnd( $time );
		}

		$order = $this->parse_order();
		$limit = $this->parse_pagination();

		$builder->append( $select )->append( $from );

		$builder->append( $where );
		$builder->append( $order );

		if ( $limit !== null ) {
			$builder->append( $limit );
		}

		return $builder->build();
	}

	/**
	 * Parse a partial search for a message.
	 *
	 * @since 1.0
	 *
	 * @return Where|null
	 */
	protected function parse_message() {

		if ( empty( $this->args['message'] ) ) {
			return null;
		}

		$like = esc_sql( $this->args['message'] );

		return new Where( 'message', 'LIKE', "%{$like}%" );
	}

	/**
	 * Parse the level where.
	 *
	 * @since 1.0
	 *
	 * @return Where|null
	 */
	protected function parse_level() {

		if ( empty( $this->args['level'] ) ) {
			return null;
		}

		return new Where( 'level', true, $this->args['level'] );
	}

	/**
	 * Parse the group where.
	 *
	 * @since 1.0
	 *
	 * @return Where|null
	 */
	protected function parse_group() {

		if ( empty( $this->args['group'] ) ) {
			return null;
		}

		return new Where( 'lgroup', true, $this->args['group'] );
	}

	/**
	 * Parse the user where.
	 *
	 * @since 1.0
	 *
	 * @return Where|null
	 */
	protected function parse_user() {

		if ( ! empty( $this->args['user'] ) ) {
			$this->args['user__in'] = array( $this->args['user'] );
		}

		return $this->parse_in_or_not_in_query( 'user', $this->args['user__in'], $this->args['user__not_in'] );
	}

	/**
	 * Parse the time query.
	 *
	 * @since 1.0
	 *
	 * @return Where_Date|null
	 */
	protected function parse_time() {
		if ( ! empty( $this->args['time'] ) ) {
			$date_query = new \WP_Date_Query( $this->args['time'], 'q.time' );

			return new Where_Date( $date_query );
		} else {
			return null;
		}
	}

	/**
	 * Translate a human given order by, to its corresponding column name.
	 *
	 * @since 1.0
	 *
	 * @param string $order_by
	 *
	 * @return string
	 */
	protected function translate_order_by_to_column_name( $order_by ) {

		switch ( $order_by ) {
			case 'group':
				return 'lgroup';
		}

		return $order_by;
	}
}


<?php

namespace Unite\UnisysApi\Http\Middleware;

use Closure;

class HttpsProtocol
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->secure() && env('APP_ENV') === 'production') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}


<?php

namespace Unite\UnisysApi\Providers;

use Unite\UnisysApi\Policies\UserNotificationPolicy;
use Unite\UnisysApi\Policies\UserPolicy;
use Unite\UnisysApi\Models\User;
use Carbon\Carbon;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        User::class => UserPolicy::class,
        DatabaseNotification::class => UserNotificationPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::define('hasPermission', function (User $user, string $permissionName) {
            if($user->isAdmin()) {
                return true;
            }

            return $user->hasPermissionTo($permissionName);
        });

        Passport::routes();

        Passport::tokensExpireIn(Carbon::now()->addDays(15));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }
}


<?php

namespace ThemeManager;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider as ServiceProviderSupport;

class ServiceProvider extends ServiceProviderSupport
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/config/theme-manager.php' => config_path('theme-manager.php'),
        ], 'theme');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('theme.manager', function () {
            $basePath = Config::get('theme-manager.base_path', null);
            $requiredFields = Config::get('theme-manager.required_fields', []);
            $exceptionOnInvalid = Config::get('theme-manager.exception_on_invalid', false);

            return new ThemeManager((new Starter)->start($basePath, $requiredFields, $exceptionOnInvalid));
        });
    }
}


<?php

namespace hypeJunction\Prototyper\Elements;

class MetadataField extends Field {

	const CLASSNAME = __CLASS__;

	/**
	 * {@inheritdoc}
	 */
	public function getValues(\ElggEntity $entity) {
		$values = array();
		$sticky = $this->getStickyValue();

		if ($sticky) {
			$keys = array_keys($sticky['value']);
			foreach ($keys as $i) {
				$md = new \stdClass();
				$md->id = $sticky['id'][$i];
				$md->name = $sticky['name'][$i];
				$md->value = $sticky['value'][$i];
				$md->access_id = $sticky['access_id'][$i];
				$md->owner_guid = $sticky['owner_guid'][$i];

				$values[$i] = $md;
			}
		} else if ($entity->guid) {
			$values = elgg_get_metadata(array(
				'guids' => (int) $entity->guid,
				'metadata_names' => $this->getShortname(),
				'limit' => 0,
			));
		}

		if (empty($values)) {
			$md = new \stdClass();
			$md->value = $this->getDefaultValue();
			$values = array($md);
		}

		return array_values($values);
	}

	/**
	 * {@inheritdoc}
	 */
	public function validate(\ElggEntity $entity) {

		$validation = new ValidationStatus();

		$metadata = get_input($this->getShortname(), array());
		$keys = array_keys(elgg_extract('value', $metadata, array()));

		if (empty($keys)) {
			if ($this->isRequired()) {
				$validation->setFail(elgg_echo('prototyper:validate:error:required', array($this->getLabel())));
			}
		} else {
			foreach ($keys as $i) {
				if ($metadata['name'][$i] == $this->getShortname()) {
					if (is_string($metadata['value'][$i])) {
						$value = strip_tags($metadata['value'][$i]);
					} else {
						$value = $metadata['value'][$i];
					}
					if (is_null($value) || $value == '') {
						if ($this->isRequired()) {
							$validation->setFail(elgg_echo('prototyper:validate:error:required', array($this->getLabel())));
						}
					} else {
						$validation = $this->applyValidationRules($value, $validation, $entity);
					}
				}
			}
		}

		return $validation;
	}

	/**
	 * {@inheritdoc}
	 */
	public function handle(\ElggEntity $entity) {

		$shortname = $this->getShortname();

		if ($entity->guid) {
			$current_metadata = elgg_get_metadata(array(
				'guids' => (int) $entity->guid,
				'metadata_names' => $shortname,
				'limit' => 0,
			));

			if (!empty($current_metadata)) {
				foreach ($current_metadata as $md) {
					$current_metadata_ids[] = $md->id;
				}
			}
		}

		if (empty($current_metadata_ids)) {
			$current_metadata_ids = array();
		}

		$future_metadata = get_input($this->getShortname(), array());

		$params = array(
			'field' => $this,
			'entity' => $entity,
			'metadata_name' => $shortname,
			'value' => $current_metadata,
			'future_value' => $future_metadata,
		);

		// Allow plugins to prevent metadata from being changed
		if (!elgg_trigger_plugin_hook('handle:metadata:before', 'prototyper', $params, true)) {
			return $entity;
		}

		$future_metadata_ids = elgg_extract('id', $future_metadata, array());

		$to_delete = array_diff($current_metadata_ids, $future_metadata_ids);
		if (!empty($to_delete)) {
			elgg_delete_metadata(array(
				'guids' => (int) $entity->guid,
				'metadata_ids' => $to_delete,
				'limit' => 0,
			));
		}

		$keys = array_keys(elgg_extract('name', $future_metadata, array()));

		$ids = array();
		foreach ($keys as $i) {

			$id = $future_metadata['id'][$i];
			$name = $future_metadata['name'][$i];
			$value = $future_metadata['value'][$i];
			$value_type = $this->getValueType();
			$input_type = $this->getType();
			if ($value_type == 'tags' || (!$value_type && $input_type == 'tags')) {
				$value = string_to_tag_array($value);
			}
			$access_id = $future_metadata['access_id'][$i];
			$owner_guid = $future_metadata['owner_guid'][$i];

			if (!is_array($value)) {
				if ($id) {
					update_metadata($id, $name, $value, '', $owner_guid, $access_id);
				} else {
					$id = create_metadata($entity->guid, $name, $value, '', $owner_guid, $access_id, true);
				}
				$ids[] = $id;
			} else {
				if ($id) {
					elgg_delete_metadata_by_id($id);
				}
				foreach ($value as $val) {
					$ids[] = create_metadata($entity->guid, $name, $val, '', $owner_guid, $access_id, true);
				}
			}
		}

		$params = array(
			'field' => $this,
			'entity' => $entity,
			'metadata_name' => $shortname,
			'value' => (count($ids)) ? elgg_get_metadata(array('metadata_ids' => $ids)) : array(),
			'previous_value' => $current_metadata,
		);

		elgg_trigger_plugin_hook('handle:metadata:after', 'prototyper', $params, true);

		return $entity;
	}

	/**
	 * {@inheritdoc}
	 */
	public static function getDataType() {
		return 'metadata';
	}

}


<?php
namespace yimaTheme\Theme;

use yimaTheme\Manager;
use yimaTheme\Resolvers;
use Zend\Mvc\MvcEvent;
use Zend\ServiceManager;

class Locator implements
    LocatorDefaultInterface,
    ServiceManager\ServiceLocatorAwareInterface
{
    /**
     * Name of template
     *
     * @var string
     */
    protected $name;

    /**
     * @var ServiceManager\ServiceManager
     */
    protected $serviceManager;

    /**
     * @var array[Resolvers\Aggregate] Resolvers Aggregate
     */
    protected $resolverObject = array();

    /**
     * Find Matched Theme and return object
     *
     * @return Theme|false
     */
    public function getPreparedThemeObject()
    {
        $name = $this->attainThemeName();
        $path = $this->attainPathName();

        $return = false;
        if ($name && $path) {
            // we are attained theme
            $return = $this->getThemeObject();
        	$return->setName($name);
        	$return->setThemesPath($path);
        }

        return $return;
    }

    /**
     * Get ThemeObject
     * : it must be unique new instance object theme -
     *   on each get request
     *
     * @return Theme
     * @throws \Exception
     */
    protected function getThemeObject()
    {
        $themeObject = $this->getServiceLocator()
            ->get('yimaTheme.ThemeObject');
        if (! $themeObject instanceof ThemeDefaultInterface) {
            throw new \Exception(
                sprintf(
                    'yimaTheme.ThemeObject must instanceof "\yimaTheme\Theme\ThemDefaultInterface" but "%s" given.',
                    get_class($themeObject)
                )
            );
        }

        return $themeObject;
    }

    /**
     * Get layout name according to MvcEvent on EVENT_DISPATCH
     *
     * @param MvcEvent $e
     *
     * @throws \Exception
     * @return string | false
     */
    public function getMvcLayout(MvcEvent $e)
    {
        try {
            $resolver = $this->getResolverObject('mvclayout_resolver_adapter', array('event_mvc' => $e));
        } catch (\Exception $e) {
            throw $e;
        }

        $layout = $resolver->getName();
        if (empty($layout) && ! ($layout === '0') ) {
            return false;
        }

        return $layout;
    }

    /**
     * Resolve to theme name by Aggregate services
     *
     * @return bool
     * @throws \Exception
     */
    protected function attainThemeName()
    {
        $themeName = $this->getResolverObject('resolver_adapter_service')
            ->getName();

        return (empty($themeName) && ! ($themeName === '0')) ? false : $themeName;
    }

    /**
     * Get Resolver Object used by Locator
     *
     * @TODO It Seems Have Conflict on Locator used Global-
     *       -Layout Resolver defined on merged config Against Theme Specific Resolver For Layout
     *
     * @param string $state   Setup configuration resolver
     * @param array  $options Options
     * @return Resolvers\Aggregate
     * @throws \Exception
     */
    public function getResolverObject($state = null, array $options = array())
    {
        if ($state == null && isset($this->resolverObject['last_resolver'])) {
            // latest invoked resolver
            return $this->resolverObject['last_resolver'];
        }

        if ($state != 'resolver_adapter_service' && $state != 'mvclayout_resolver_adapter')
            throw new \Exception('Invalid state name provided.');

        // create resolver state object from config
        $config = $this->getConfig();

        if (isset($config['theme_locator']))
            $config = $config['theme_locator'];
        else
            $config = array();

        if (!isset($config[$state]))
            throw new \Exception("Theme Resolver Service not present in config[$state].");

        $config = $config[$state];
        // is string, 'resolver_adapter' => 'resolver\service'
        if (is_string($config)) {
            $config = array(
                "{$config}" => 1
            );
        }

        if (isset($this->resolverObject[$state])) {
            $resolver = $this->resolverObject[$state];

            $this->resolverObject['last_resolver'] = $resolver;

            return $resolver;
        }
        else
            $resolver = new Resolvers\Aggregate();

        foreach ($config as $service => $priority)
        {
            if ($this->getServiceLocator()->has($service)) {
                $service = $this->getServiceLocator()->get($service);
            } else {
                if (!class_exists($service))
                    throw new \Exception("Resolver '$service' not found for yimaTheme as Service either Class.");

                $service = new $service();
            }

            if ($service instanceof Resolvers\LocatorResolverAwareInterface) {
                // inject themeLocator to access config and other things by resolver
                $service->setThemeLocator($this);
            }

            if ($service instanceof Resolvers\ConfigResolverAwareInterface) {
                // set yimaTheme config for resolver
                $service->setConfig($this->getConfig());
            }

            if (isset($options['event_mvc']))
                if ($service instanceof Resolvers\MvcResolverAwareInterface)
                	$service->setMvcEvent($options['event_mvc']);

            $resolver->attach($service, $priority);
        }

        $this->resolverObject[$state]          = $resolver;
        $this->resolverObject['last_resolver'] = $resolver;

        return $resolver;
    }

    /**
     * Get themes folder dir from config
     *
     * @return string
     */
    protected function attainPathName()
    {
        $path = false;

        // get default themes path by config {
        $config = $this->getConfig();
        if (isset($config['theme_locator']['themes_default_path'])) {
            $path = $config['theme_locator']['themes_default_path'];
        }
        // ... }

        // get theme specify path,
        // use case in modules that present a specify theme inside, like admin panel.
        $themeName = $this->attainThemeName();
        if (isset($config['themes']) && is_array($config['themes'])
            && isset($config['themes'][$themeName]))
        {
            if (array_key_exists('dir_path',$config['themes'][$themeName])) {
                $path = $config['themes'][$themeName]['dir_path'];
            }
        }

        return $path;
    }

    /**
     * Get default Manager theme_locator config
     *
     * @return array
     */
    protected function getConfig()
    {
        // get default manager config used by default theme locator
        $config = $this->getServiceLocator()->get('config');
        if (isset($config['yima-theme']) && is_array($config['yima-theme'])) {
            $config = $config['yima-theme'];
        } else {
            $config = array();
        }

        return $config;
    }

    // -- implement methods ----------------------------------------------------------------------------------------------------------

    /**
     * Set service locator
     *
     * @param ServiceManager\ServiceLocatorInterface $serviceLocator
     */
    public function setServiceLocator(ServiceManager\ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceManager = $serviceLocator;
    }

    /**
     * Get service locator
     *
     * @return ServiceManager\ServiceLocatorInterface
     */
    public function getServiceLocator()
    {
        return $this->serviceManager;
    }
}


<?php

namespace Unite\UnisysApi;

use Route;
use Unite\UnisysApi\Commands\PermissionsSync;
use Unite\UnisysApi\Commands\SetCompanyProfile;
use Unite\UnisysApi\Console\Commands\Install\UnisysApiInitializeEnv;
use Unite\UnisysApi\Console\Commands\Install\UnisysApiInstall;
use Illuminate\Support\ServiceProvider;
use Unite\UnisysApi\Console\Commands\Update;
use Unite\UnisysApi\Console\Commands\Users\ImportUsers;
use Unite\UnisysApi\Providers\AuthServiceProvider;
use Unite\UnisysApi\Providers\RouteServiceProvider;
use Unite\UnisysApi\Providers\ScheduleServiceProvider;
use Unite\UnisysApi\Providers\MiddlewareServiceProvider;
use Unite\UnisysApi\Services\SettingService;

class UnisysApiServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Route::patterns([
            'id'    => '^\d+$',
            'model' => '^\d+$',
        ]);

        $this->app->register(RouteServiceProvider::class);
        $this->app->register(AuthServiceProvider::class);
        $this->app->register(ScheduleServiceProvider::class);
        $this->app->register(MiddlewareServiceProvider::class);

        $this->commands([
            UnisysApiInitializeEnv::class,
            UnisysApiInstall::class,
            ImportUsers::class,
            PermissionsSync::class,
            SetCompanyProfile::class,
            Update::class,
        ]);

        if ($this->app->runningInConsole()) {
            $timestamp = date('Y_m_d_His', time());

            if (!class_exists('CreateUsersTable')) {
                $this->publishes([
                    __DIR__ . '/../database/migrations/create_users_table.php.stub' => database_path("/migrations/{$timestamp}_create_users_table.php"),
                ], 'migrations');
            }

            if (!class_exists('CreatePasswordResetsTable')) {
                $this->publishes([
                    __DIR__ . '/../database/migrations/create_password_resets_table.php.stub' => database_path("/migrations/{$timestamp}_create_password_resets_table.php"),
                ], 'migrations');
            }

            if (!class_exists('CreateInstalledModulesTable')) {
                $this->publishes([
                    __DIR__ . '/../database/migrations/create_installed_modules_table.php.stub' => database_path("/migrations/{$timestamp}_create_installed_modules_table.php"),
                ], 'migrations');
            }

            if (!class_exists('CreateSettingsTable')) {
                $this->publishes([
                    __DIR__ . '/../database/migrations/create_settings_table.php.stub' => database_path("/migrations/{$timestamp}_create_settings_table.php"),
                ], 'migrations');
            }

            $this->publishes([
                __DIR__ . '/../config/query-filter.php' => config_path('query-filter.php'),
            ], 'config');
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
            \Unite\UnisysApi\Exceptions\Handler::class
        );

        $this->app->singleton(
            \Illuminate\Foundation\Auth\User::class,
            \Unite\UnisysApi\Models\User::class
        );

        if ($this->app->environment() === 'local') {
//            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
            $this->app->register(\Mpociot\ApiDoc\ApiDocGeneratorServiceProvider::class);
        }

        $this->app->singleton('companyProfile', function ($app) {
            return $app['cache']->remember('companyProfile', 60*12, function () {
                return app(SettingService::class)->companyProfile();
            });
        });

        app()->config["filesystems.disks.uploads"] = [
            'driver' => 'local',
            'root'   => public_path('uploads'),
            'visibility' => 'public',
        ];

        app()->config["filesystems.disks.protectedUploads"] = [
            'driver' => 'local',
            'root'   => storage_path('app/uploads'),
            'visibility' => 'private',
        ];
    }
}


<?php
namespace WMS\Library\BusinessRulesEngine\Dumper;

/**
 * PhpRuleCollectionDumper creates a PHP class able representing a pre-populated rule collection.
 *
 * @author Andrew Moore <me@andrewmoore.ca>
 */
class PhpRuleCollectionDumper extends RuleCollectionDumper
{
    /**
     * Dumps a set of rules to a PHP class.
     *
     * Available options:
     *
     *  * class:      The class name
     *  * base_class: The base class name
     *
     * @param array $options An array of options
     *
     * @return string A PHP class representing the generator class
     *
     * @api
     */
    public function dump(array $options = array())
    {
        $options = array_merge(array(
            'class'      => 'ProjectRuleCollection',
            'base_class' => 'WMS\\Library\\BusinessRulesEngine\\RuleCollection',
        ), $options);

        return <<<EOF
<?php

use WMS\Library\BusinessRulesEngine\Rule;

/**
 * {$options['class']}
 *
 * This class has been auto-generated
 * by the WMS BusinessRulesEngine Library.
 */
class {$options['class']} extends {$options['base_class']}
{
    private static \$declaredRules = {$this->generateDeclaredRules()};

    /**
     * Constructor.
     */
    public function __construct()
    {
        foreach(self::\$declaredRules as \$ruleName => \$ruleInfo) {
            \$rule = new Rule(\$ruleInfo[0]);

            foreach(\$ruleInfo[1] as \$tagName => \$tagAttrs) {
                foreach(\$tagAttrs as \$tagAttrsInstance) {
                    \$rule->addTag(\$tagName, \$tagAttrsInstance);
                }
            }

            \$this->add(\$ruleName, \$rule);
        }
    }
}

EOF;
    }

    /**
     * Generates PHP code representing an array of defined rules
     * together with the routes properties (e.g. requirements).
     *
     * @return string PHP code
     */
    private function generateDeclaredRules()
    {
        $rules = "array(\n";
        foreach ($this->getRules()->all() as $name => $rule) {
            $properties = array();
            $properties[] = $rule->getExpression();
            $properties[] = $rule->getTags();

            $rules .= sprintf("        '%s' => %s,\n", $name, str_replace("\n", '', var_export($properties, true)));
        }
        $rules .= '    )';

        return $rules;
    }
}


<?php

namespace Zf2Forum\Model\Visit;

use Zf2Forum\Model\Thread\ThreadInterface;

class Visit implements VisitInterface
{
    /**
     * @var string
     */
    protected $ipAddress;

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

    /**
     * @var ThreadInterface
     */
    protected $thread;

    /**
     * setIpAddress - Sets the IP address.
     *
     * @param unknown_type $ipAddress
     * @return \Zf2Forum\Model\Visit\Visit
     */
    public function setIpAddress($ipAddress)
    {
        $this->ipAddress = $ipAddress;
        return $this;
    }

    /**
     * getIpAddress - Returns the IP address.
     */
    public function getIpAddress()
    {
        return $this->ipAddress;
    }

    /**
     * setVisitTime - Sets the visit time.
     *
     * @param unknown_type $visitTime
     * @return \Zf2Forum\Model\Visit\Visit
     */
    public function setVisitTime($visitTime)
    {
        if ($visitTime instanceof \DateTime) {
            $this->visitTime = $visitTime;
        } else {
            $this->visitTime = new \DateTime($visitTime);
        }
        return $this;
    }

    /**
     * getVisitTime - returns the visit time.
     */
    public function getVisitTime()
    {
        return $this->visitTime;
    }

    /**
     * setThread - Sets the thread.
     *
     * @param ThreadInterface $thread
     * @return \Zf2Forum\Model\Visit\Visit
     */
    public function setThread(ThreadInterface $thread)
    {
        $this->thread = $thread;
        return $this;
    }

    /**
     * getThread - returns the thread.
     */
    public function getThread()
    {
        return $this->thread;
    }
}


<?php

namespace hypeJunction\Prototyper\Elements;

class IconField extends UploadField {

	const CLASSNAME = __CLASS__;

	/**
	 * {@inheritdoc}
	 */
	public function getValues(\ElggEntity $entity) {
		return ($entity->icontime);
	}

	/**
	 * {@inheritdoc}
	 */

	/**
	 * {@inheritdoc}
	 */
	public function handle(\ElggEntity $entity) {

		$shortname = $this->getShortname();

		$icon_sizes = hypeApps()->iconFactory->getSizes($entity);
		$custom_icon_sizes = (array) $this->input_vars->{"icon_sizes"};
		$icon_sizes = array_merge($icon_sizes, $custom_icon_sizes);

		if (empty($icon_sizes)) {
			return $entity;
		}

		$image_upload_crop_coords = (array) get_input('image_upload_crop_coords', array());
		$ratio_coords = (array) elgg_extract($shortname, $image_upload_crop_coords, array());

		list($master_width, $master_height) = getimagesize($_FILES[$shortname]['tmp_name']);

		foreach ($icon_sizes as $icon_name => $icon_size) {
			$ratio = (int) $icon_size['w'] / (int) $icon_size['h'];
			$coords = (array) elgg_extract("$ratio", $ratio_coords, array());

			$x1 = (int) elgg_extract('x1', $coords);
			$x2 = (int) elgg_extract('x2', $coords);
			$y1 = (int) elgg_extract('y1', $coords);
			$y2 = (int) elgg_extract('y2', $coords);

			if ($x2 <= $x1 || $y2 <= $y1) {
				// do not crop
				$this->tmp_coords = false;
			} else {
				$this->tmp_coords = $coords;
				$this->tmp_coords['master_width'] = $master_width;
				$this->tmp_coords['master_height'] = $master_height;
			}

			if (!isset($icon_size['name'])) {
				$icon_size['name'] = $icon_name;
			}
			$this->tmp_icon_sizes = array(
				$icon_size['name'] => $icon_size,
			);
			$options = array(
				'icon_sizes' => $this->tmp_icon_sizes,
				'coords' => $this->tmp_coords,
			);

			elgg_register_plugin_hook_handler('entity:icon:sizes', 'object', array($this, 'getIconSizes'), 999);
			if (hypeApps()->iconFactory->create($entity, $_FILES[$shortname]['tmp_name'], $options)) {
				foreach (array('x1', 'x2', 'y1', 'y2') as $c) {
					$entity->{"_coord_{$ratio}_{$coord}"} = elgg_extract($c, $coords, 0);
					if ($ratio === 1) {
						$entity->$c = elgg_extract($c, $coords, 0);
					}
				}
			}
			elgg_unregister_plugin_hook_handler('entity:icon:sizes', 'object', array($this, 'getIconSizes'));
		}

		return $entity;
	}

	/**
	 * Callback for icon size hook
	 * We do not want to regenerate default icons
	 * @return array
	 */
	public function getIconSizes() {
		return $this->tmp_icon_sizes;
	}

}


<?php
namespace Nkey\Caribu\Mvc;

use Generics\Socket\InvalidUrlException;
use \Generics\GenericsException;
use \Nkey\Caribu\Mvc\Controller\AbstractController;
use \Nkey\Caribu\Mvc\Controller\ControllerException;
use \Nkey\Caribu\Mvc\Controller\Request;
use \Nkey\Caribu\Mvc\View\ViewException;
use \Nkey\Caribu\Mvc\View\View;
use \Psr\Log\LoggerAwareInterface;
use \Psr\Log\LoggerAwareTrait;
use \Psr\Log\NullLogger;
use Nkey\Caribu\Mvc\Router\AbstractRouter;

/**
 * The MVC Application main class
 *
 * This class provides all functions to route the request to
 * responsible controller and action. If no controller/action
 * could be found to match the request, the error controller
 * will be triggered.
 *
 * To work correctly all available controllers and views must
 * be registered before the request can be routed.
 *
 * The routing and rendering process will be performed by
 * calling the Application::serve() function
 *
 * @author Maik Greubel <greubel@nkey.de>
 *
 *         This file is part of Caribu MVC package
 */
final class Application implements LoggerAwareInterface
{
    use LoggerAwareTrait;

    /**
     * Retrieve the logging instance
     *
     * @return \Psr\Log\LoggerInterface The logging instance
     */
    private function getLogger()
    {
        return $this->logger;
    }

    /**
     * List of controllers
     *
     * @var array
     */
    private $controllers = null;

    /**
     * List of views
     *
     * @var array
     */
    private $views = null;

    /**
     * List of view controls
     *
     * @var array
     */
    private $viewControls = null;

    /**
     * The default controller
     *
     * @var string
     */
    private $defaultController = 'Index';

    /**
     * The default action
     *
     * @var string
     */
    private $defaultAction = 'index';

    /**
     * Singleton instance
     *
     * @var \Nkey\Caribu\Mvc\Application
     */
    private static $instance = null;

    /**
     * Default headers to send to client
     *
     * @var array
     */
    private $defaultHeaders = array();

    /**
     * The client request headers to override
     *
     * @var array
     */
    private $overridenClientHeaders = array();

    /**
     * Additional css files to include in view
     *
     * @var array
     */
    private $cssFiles = array();

    /**
     * Additional javascript files to include in view
     *
     * @var array
     */
    private $jsFiles = array();

    /**
     * Router object
     * @var AbstractRouter
     */
    private $router;

    /**
     * Get application instance
     *
     * @return \Nkey\Caribu\Mvc\Application
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Singleton constructor
     */
    private function __construct()
    {
        $this->setUp();
    }

    /**
     * Set up the default values
     *
     * @return Application Current application instance
     */
    public function setUp()
    {
        $this->controllers = array();
        $this->views = array();
        $this->viewControls = array();
        $this->setDefaults();
        $this->init();
        $this->setLogger(new NullLogger());

        return $this;
    }

    /**
     * Singleton instance
     */
    public function __clone()
    {
        throw new GenericsException("Cloning is prohibited");
    }

    /**
     * Init the application
     *
     * Register internally needed controller and view
     */
    public function init()
    {
        $this->registerController(\Nkey\Caribu\Mvc\Controller\ErrorController::class);
        $this->registerView(\Nkey\Caribu\Mvc\View\DefaultView::class);
    }

    /**
     * Set the default controller and action
     *
     * @param string $defaultController
     *            The default controller name if nothing is provided by request
     * @param string $defaultAction
     *            The default action name if nothing is provided by request
     * @return Application Current application instance
     */
    public function setDefaults($defaultController = 'Index', $defaultAction = 'index')
    {
        $this->defaultController = $defaultController;
        $this->defaultAction = $defaultAction;

        return $this;
    }

    /**
     * Register a new view
     *
     * @param string $view
     *            The view class
     * @param int $order
     *            Override the default order given by view class
     * @param string $applicationName
     *            The application name where the view will be available in
     *
     * @throws ViewException
     *
     * @return Application Current application instance
     */
    public function registerView($view, $order = null, $applicationName = 'default')
    {
        if (! class_exists($view)) {
            throw new ViewException("No such view class {view} found", array(
                'view' => $view
            ));
        }

        $v = new $view();
        if (! $v instanceof View) {
            throw new ViewException("View {view} is not in application scope", array(
                'view' => $view
            ));
        }
        $viewOrder = $v->getOrder();
        if (null !== $order) {
            $viewOrder = intval($order);
        }

        $settings = $v->getViewSettings();
        $this->views[$applicationName][$viewOrder][$settings->getViewSimpleName()] = $settings;

        return $this;
    }

    /**
     * Register a view control
     *
     * @param string $controlIdentifier
     *            The identifier under which the control will be registered
     * @param string $controlClass
     *            The class of control
     *
     * @return Application Current application instance
     */
    public function registerViewControl($controlIdentifier, $controlClass)
    {
        $this->viewControls[$controlIdentifier] = $controlClass;
        return $this;
    }

    /**
     * Unregister a given view
     *
     * @param string $view
     *            The view to unregister
     * @param string $applicationName
     *            Optional application name where the view is registered
     *
     * @return Application Current application instance
     */
    public function unregisterView($view, $order, $applicationName = 'default')
    {
        if (isset($this->views[$applicationName][$order][$view])) {
            unset($this->views[$applicationName][$order][$view]);
        }
        return $this;
    }

    /**
     * Get the best view for request
     *
     * @param Request $request
     *            The request to get best view for
     *
     * @return View The view best matched for the request
     *
     * @throws ViewException
     */
    private function getViewBestMatch(Request $request, $applicationName)
    {
        $best = null;

        if (count($this->views[$applicationName]) > 0) {
            foreach ($this->views[$applicationName] as $orderLevel => $views) {
                foreach ($views as $view) {
                    assert($view instanceof View);
                    if ($view->matchBoth($request->getController(), $request->getAction())) {
                        $best[$orderLevel] = $view;
                        continue 2;
                    }
                }
            }
        }
        if (null == $best) {
            throw new ViewException("No view found for request");
        }

        if (count($best) > 1) {
            krsort($best);
        }

        return reset($best);
    }

    /**
     * Register a new controller class
     *
     * @param string $controller
     *            The full qualified name of controller class to register
     * @param string $applicationName
     *            Optional name of application where controller will be registered in
     *
     * @return Application Current application instance
     *
     * @throws ControllerException
     */
    public function registerController($controller, $applicationName = 'default')
    {
    	if ( !$controller instanceof \Nkey\Caribu\Mvc\Controller\AbstractController ) {
	        if (! class_exists($controller)) {
	            throw new ControllerException("No such controller class {controller} found", array(
	                'controller' => $controller
	            ));
	        }
	        $c = new $controller();
	        if (! ($c instanceof AbstractController)) {
	            throw new ControllerException("Controller {controller} is not in application scope", array(
	                'controller' => $controller
	            ));
	        }
    	}
        else {
        	$c = $controller;
        }
        $settings = $c->getControllerSettings();
        $this->controllers[$applicationName][$settings->getControllerSimpleName()] = $settings;

        return $this;
    }

    /**
     * Start the application
     *
     * @param string $applicationName
     *            Optional application name to service the request for
     * @param array $serverVars
     *            The server variables provided by sapi
     * @param Request $request
     *            Optional previous generated request object
     * @param boolean $send
     *            Optional whether to send the output directly to client
     *
     * @throws ControllerException
     * @throws InvalidUrlException
     */
    public function serve($applicationName = 'default', $serverVars = array(), Request $request = null, $send = true)
    {
        if (null === $request) {
            $request = Request::parseFromServerRequest($serverVars, $this->defaultController, $this->defaultAction);
        }

        foreach ($this->overridenClientHeaders as $headerName => $headerValue) {
            $request->setParam($headerName, $headerValue);
        }

        $controller = $request->getController();
        $action = $request->getAction();

        $this->getLogger()->debug("[{remote}] Requested controller is {controller} and action is {action}", array(
            'remote' => $request->getRemoteHost(),
            'controller' => $controller,
            'action' => $action
        ));

        if ( null != $this->router && $this->router->hasRoute($action) ) {
        	$controllerInstance = $this->router->route($action, $request);
        	$action = $request->getAction();
        }
        else {
	        if (! isset($this->controllers[$applicationName][$controller])) {
	            $this->getLogger()->error("[{remote}] No such controller {controller}", array(
	                'remote' => $request->getRemoteHost(),
	                'controller' => $controller
	            ));
	            $controller = 'Error';
	            $action = 'error';
	        }

	        $controllerInstance = $this->controllers[$applicationName][$controller];
	        assert($controllerInstance instanceof AbstractController);
	        if (! $controllerInstance->hasAction($action)) {
	            $this->getLogger()->error("[{remote}] No such action {action}", array(
	                'remote' => $request->getRemoteHost(),
	                'action' => $action
	            ));
	            $controllerInstance = $this->controllers[$applicationName]['Error'];
	            $action = 'error';
	        }

	        $this->getLogger()->debug("[{remote}] Routing request to {controller}:{action}", array(
	            'remote' => $request->getRemoteHost(),
	            'controller' => $controller,
	            'action' => $action
	        ));
        }

        $view = $this->getViewBestMatch($request, $applicationName);

        $view->setCssFiles($this->cssFiles);
        $view->setJsFiles($this->jsFiles);

        foreach ($this->viewControls as $controlIdentifier => $controlClass) {
            $view->registerControl($controlClass, $controlIdentifier);
        }

        try {
            $response = $controllerInstance->call($action, $request, $view);
        } catch (\Exception $ex) {
            $controllerInstance = $this->controllers[$applicationName]['Error'];
            $action = 'exception';
            $request->setException($ex);
            $response = $controllerInstance->call($action, $request, $view);

            $outputBuffer = ob_get_clean();
            if (strlen($outputBuffer)) {
                $response->appendBody($outputBuffer);
            }
        }

        $responseCode = $response->getHttpCode();
        $responseType = sprintf('%s;%s', $response->getType(), $response->getEncoding());
        $responseContent = strval($response);
        $responseLen = strlen($responseContent);

        $this->getLogger()->debug("[{remote}] Response is type of {type}, length of {length} and code {code}", array(
            'remote' => $request->getRemoteHost(),
            'type' => $responseType,
            'length' => $responseLen,
            'code' => $responseCode
        ));

        if ($send) {
            header(sprintf("%s", $responseCode));
            header(sprintf("Content-Length: %d", $responseLen));
            header(sprintf("Content-Type: %s", $responseType));

            foreach ($this->defaultHeaders as $headerName => $headerValue) {
                header(sprintf("%s: %s", $headerName, $headerValue));
            }
            foreach ($response->getAdditionalHeaders() as $headerName => $headerValue) {
                header(sprintf("%s: %s", $headerName, $headerValue));
            }

            echo $responseContent;
        }

        return $response;
    }

    /**
     * Register a new Router
     *
     * @param AbstractRouter $router
     * @return Application the current application instance
     */
    public function registerRouter(AbstractRouter $router)
    {
    	$this->router = $router;
    	$this->router->setApplication($this);
    	return $this;
    }

    /**
     * Enable session handling
     *
     * @return Application The current application instance
     */
    public function enableSession()
    {
        session_start();

        return $this;
    }

    /**
     * Retrieve the default controller name
     *
     * @return string The name of default controller
     */
    public function getDefaultController()
    {
        return $this->defaultController;
    }

    /**
     * Retrieve the default action name
     *
     * @return string The name of default action
     */
    public function getDefaultAction()
    {
        return $this->defaultAction;
    }

    /**
     * Add a new header to specific value.
     *
     * Existing header will be overriden.
     *
     * @param string $name
     *            The header identifier
     * @param string $value
     *            The value to set
     *
     * @return Application The current application instance
     */
    public function addHeader($name, $value)
    {
        $this->defaultHeaders[$name] = $value;
        return $this;
    }

    /**
     * Add a header to overide a client request header
     *
     * @param string $name
     *            The header name to override
     * @param string $value
     *            The value to override
     *
     * @return Application The current application instance
     */
    public function addOverridenClientHeader($name, $value)
    {
        $this->overridenClientHeaders[$name] = $value;
        return $this;
    }

    /**
     * Add an uri for an additional javascript file
     *
     * @param string $file
     *
     * @return Application the current application instance
     */
    public function addJsFile($file)
    {
        $this->jsFiles[] = $file;
        return $this;
    }

    /**
     * Add an uri for an additional css file
     *
     * @param string $file
     *
     * @return Application the current application instance
     */
    public function addCssFile($file)
    {
        $this->cssFiles[] = $file;
        return $this;
    }
}