<?php

/**
 * @todo Description
 *
 * @package silverstripe-seo
 * @subpackage icons
 * @author Andrew Gerber <atari@graphiquesdigitale.net>
 * @version 1.0.0
 *
 */
class SEO_Icons_SiteTree_DataExtension extends DataExtension
{

    /* Overload Variable
    ------------------------------------------------------------------------------*/

    // none

    /* Overload Methods
    ------------------------------------------------------------------------------*/

    // CMS Fields
// 	public function updateCMSFields(FieldList $fields) {}

    /* Template Methods
    ------------------------------------------------------------------------------*/

    /**
     * Updates metadata with icons.
     *
     * @param SiteConfig $config
     * @param SiteTree $owner
     * @param $metadata
     *
     * @return void
     */
    public function updateMetadata(SiteConfig $config, SiteTree $owner, &$metadata)
    {

        //// HTML4 Favicon

        // @todo Perhaps create dynamic image, but just use favicon.ico for now

        //// Create Favicons

        $HTML5Favicon = $config->HTML5Favicon();
        $IOSPinicon = $config->IOSPinicon();
        $AndroidPinicon = $config->AndroidPinicon();
        $WindowsPinicon = $config->WindowsPinicon();

        //// iOS Pinicon

        if ($IOSPinicon->exists()) {
            $this->GenerateIOSPinicon($config, $owner, $metadata, $IOSPinicon);
        }

        //// HTML5 Favicon

        if ($HTML5Favicon->exists()) {
            $this->GenerateHTML5Favicon($owner, $metadata, $HTML5Favicon);
        }

        //// Android Pinicon Manifest

        if ($AndroidPinicon->exists()) {
            $this->GenerateAndroidPinicon($config, $owner, $metadata);
        }

        //// Windows Pinicon Manifest

        if ($WindowsPinicon->exists()) {
            $this->GenerateWindowsPinicon($config, $owner, $metadata, $WindowsPinicon);
        }

    }

    /**
     * Generates markup for the iOS pinicon
     *
     * @param SiteConfig $config
     * @param SiteTree $owner
     * @param string $metadata
     * @param Image $IOSPinicon
     *
     * @return void
     */
    protected function GenerateIOSPinicon(SiteConfig $config, SiteTree $owner, &$metadata, Image $IOSPinicon) {

        // header
        $metadata .= $this->owner->MarkupComment('iOS Pinned Icon');

        //// iOS Pinicon Title
        if ($config->fetchPiniconTitle()) {
            $metadata .= $owner->MarkupMeta('apple-mobile-web-app-title', $config->fetchPiniconTitle());
        }

        //// iOS Pinned Icon

        // For non-Retina (@1× display) iPhone, iPod Touch, and Android 2.1+ devices
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(57, 57)->getAbsoluteURL(), 'image/png'); // 57×57

        // @todo: What is this for ??
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(60, 60)->getAbsoluteURL(), 'image/png', '60x60');

        // For the iPad mini and the first- and second-generation iPad (@1× display) on iOS ≤ 6
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(72, 72)->getAbsoluteURL(), 'image/png', '72x72');

        // For the iPad mini and the first- and second-generation iPad (@1× display) on iOS ≥ 7
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(76, 76)->getAbsoluteURL(), 'image/png', '76x76');

        // For iPhone with @2× display running iOS ≤ 6
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(114, 114)->getAbsoluteURL(), 'image/png', '114x114');

        // For iPhone with @2× display running iOS ≥ 7
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(120, 120)->getAbsoluteURL(), 'image/png', '120x120');

        // For iPad with @2× display running iOS ≤ 6
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(144, 144)->getAbsoluteURL(), 'image/png', '144x144');

        // For iPad with @2× display running iOS ≥ 7
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(152, 152)->getAbsoluteURL(), 'image/png', '152x152');

        // For iPhone 6 Plus with @3× display
        $metadata .= $owner->MarkupLink('apple-touch-icon', $IOSPinicon->Fill(180, 180)->getAbsoluteURL(), 'image/png', '180x180');

    }

    /**
     * Generates markup for the HTML5 favicon
     *
     * @param SiteTree $owner
     * @param string $metadata
     * @param Image $HTML5Favicon
     *
     * @return void
     */
    protected function GenerateHTML5Favicon(SiteTree $owner, &$metadata, Image $HTML5Favicon) {

        // header
        $metadata .= $owner->MarkupComment('HTML5 Favicon');

//			// Android Chrome 32
        // @todo: Is the Android Chrome 32 196x196 px icon fully redundant ??
//			$metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(196,196)->getAbsoluteURL(), 'image/png', '196x196');

        // Android Chrome 37+ / HTML5 spec
        $metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(192, 192)->getAbsoluteURL(), 'image/png', '192x192');

        // Android Chrome 37+ / HTML5 spec
        $metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(128, 128)->getAbsoluteURL(), 'image/png', '128x128');

        // For Google TV
        $metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(96, 96)->getAbsoluteURL(), 'image/png', '96x96');

        // For Safari on Mac OS
        $metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(32, 32)->getAbsoluteURL(), 'image/png', '32x32');

        // The classic favicon, displayed in the tabs
        $metadata .= $owner->MarkupLink('icon', $HTML5Favicon->Fill(16, 16)->getAbsoluteURL(), 'image/png', '16x16');

    }

    /**
     * Generates markup for the Android pinicon
     *
     * @param SiteConfig $config
     * @param SiteTree $owner
     * @param $metadata
     *
     * @return void
     */
    protected function GenerateAndroidPinicon(SiteConfig $config, SiteTree $owner, &$metadata) {

        // header
        $metadata .= $owner->MarkupComment('Android Pinned Icon');

        //
        if ($config->fetchAndroidPiniconThemeColor()) {
            $metadata .= $owner->MarkupMeta('theme-color', $config->fetchAndroidPiniconThemeColor());
        }

        //
        $metadata .= $owner->MarkupLink('manifest', '/manifest.json');

    }

    /**
     * Generates markup for the Windows pinicon
     *
     * @param SiteConfig $config
     * @param SiteTree $owner
     * @param $metadata
     * @param Image $WindowsPinicon
     *
     * @return void
     */
    protected function GenerateWindowsPinicon(SiteConfig $config, SiteTree $owner, &$metadata, Image $WindowsPinicon) {

        // header
        $metadata .= $owner->MarkupComment('Windows Pinned Icon');

        // application name
        $appName = $config->fetchPiniconTitle();
        if (!$appName) {
            $appName = $config->Title;
        }
        $metadata .= $owner->MarkupMeta('application-name', $appName);

        // tile background color
        if ($config->fetchWindowsPiniconBackgroundColor()) {
            $metadata .= $owner->MarkupMeta('msapplication-TileColor', $config->fetchWindowsPiniconBackgroundColor());
        }

        // small tile
        $metadata .= $owner->MarkupMeta('msapplication-square70x70logo', $WindowsPinicon->Fill(70, 70)->getAbsoluteURL());

        // medium tile
        $metadata .= $owner->MarkupMeta('msapplication-square150x150logo', $WindowsPinicon->Fill(150, 150)->getAbsoluteURL());

        // @todo: Implement wide & tall tiles

        // wide tile
//			$metadata .= $owner->MarkupMeta('msapplication-square310x150logo', $WindowsPinicon->Fill(310,150)->getAbsoluteURL());

        // large tile
//			$metadata .= $owner->MarkupMeta('msapplication-square310x310logo', $WindowsPinicon->Fill(310,310)->getAbsoluteURL());

    }

}


<?php
/**
 * This file is part of SoloProyectos common library.
 *
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/event/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/event
 */
namespace soloproyectos\event;
use soloproyectos\event\EventListener;

/**
 * Class EventMediator.
 *
 * Any class able to dispatch or listen events.
 * This class implements the "mediator pattern". See for example:
 * http://blog.ircmaxell.com/2012/03/handling-plugins-in-php.html
 *
 * @package Event
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/event/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/event
 */
class EventMediator
{
    /**
     * Event listeners.
     * @var array of EventListener
     */
    private $_eventListeners = array();

    /**
     * Is the event process stopped?
     * @var boolean
     */
    private $_isStop = false;

    /**
     * Adds an event listener.
     *
     * @param string   $eventType Event type
     * @param Callable $listener  Listener
     *
     * @return void
     */
    public function on($eventType, $listener)
    {
        array_push($this->_eventListeners, new EventListener($eventType, $listener));
    }

    /**
     * Removes an event listener.
     *
     * When $listener is null, this function removes all listeners linked to the event type.
     *
     * @param string   $eventType Event type
     * @param Callable $listener  Listener (not required)
     *
     * @return void
     */
    public function off($eventType, $listener = null)
    {
        foreach ($this->_eventListeners as $i => $l) {
            if ($l->getType() == $eventType) {
                if ($listener === null || $l->getListener() === $listener) {
                    unset($this->_eventListeners[$i]);
                }
            }
        }
    }

    /**
     * Dispatches an event.
     *
     * @param string $eventType Event type or a list of event types
     * @param array  $data      Additional data (not required)
     *
     * @return void
     */
    public function trigger($eventType, $data = array())
    {
        $this->_isStop = false;
        foreach ($this->_eventListeners as $eventListener) {
            if ($this->_isStop) {
                break;
            }
            if ($eventListener->getType() == $eventType) {
                call_user_func_array($eventListener->getListener(), $data);
            }
        }
    }

    /**
     * Stops the event process.
     *
     * The listeners are called in the same order as they were registered. This function stops that
     * process.
     *
     * @return void
     */
    public function stop()
    {
        $this->_isStop = true;
    }
}


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

namespace cascade\components\db\behaviors\auditable;

use ArrayIterator;

/**
 * AuditPackage [[@doctodo class_description:cascade\components\db\behaviors\auditable\AuditPackage]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class AuditPackage extends \canis\base\Object implements \IteratorAggregate, \ArrayAccess, \Countable
{
    /**
     * @var [[@doctodo var_type:similarThreshold]] [[@doctodo var_description:similarThreshold]]
     */
    public $similarThreshold = 21600;
    /**
     * @var [[@doctodo var_type:_items]] [[@doctodo var_description:_items]]
     */
    protected $_items = [];
    /**
     * @var [[@doctodo var_type:direction]] [[@doctodo var_description:direction]]
     */
    public $direction = '_older';
    /**
     * @var [[@doctodo var_type:context]] [[@doctodo var_description:context]]
     */
    public $context = false;

    /**
     * @inheritdoc
     */
    public function __construct($dataSource, $context = false)
    {
        foreach ($dataSource->models as $item) {
            $this->add($item);
        }
        $this->direction = $dataSource->direction;
        $this->context = $context;
        parent::__construct();
    }

    /**
     * [[@doctodo method_description:count]].
     *
     * @return [[@doctodo return_type:count]] [[@doctodo return_description:count]]
     */
    public function count()
    {
        return $this->getCount();
    }

    /**
     * Returns the number of items in the collection.
     *
     * @return integer the number of items in the collection.
     */
    public function getCount()
    {
        return count($this->_items);
    }

    /**
     * Returns the item with the specified name.
     *
     * @param string $name the item name
     *
     * @return object the item with the specified name. Null if the named item does not exist.
     *
     * @see getValue()
     */
    public function get($name)
    {
        return isset($this->_items[$name]) ? $this->_items[$name] : null;
    }

    /**
     * Returns whether there is a item with the specified name.
     * Note that if a item is marked for deletion from browser, this method will return false.
     *
     * @param string $name the item name
     *
     * @return boolean whether the named item exists
     *
     * @see remove()
     */
    public function has($name)
    {
        return isset($this->_items[$name]);
    }

    /**
     * Adds a item to the collection.
     * If there is already a item with the same name in the collection, it will be removed first.
     *
     * @param object $item the item to be added
     *
     * @throws InvalidCallException if the item collection is read only
     */
    public function add($item)
    {
        $this->_items[$item->primaryKey] = $item;
    }

    /**
     * Removes a item.
     * If `$removeFromBrowser` is true, the item will be removed from the browser.
     * In this case, a item with outdated expiry will be added to the collection.
     *
     * @param string $item the item object or the name of the item to be removed.
     *
     * @throws InvalidCallException if the item collection is read only
     */
    public function remove($item)
    {
        if (is_object($item)) {
            unset($this->_items[$item->primaryKey]);
        } else {
            unset($this->_items[$item]);
        }
    }

    /**
     * Removes all items.
     *
     * @throws InvalidCallException if the item collection is read only
     */
    public function removeAll()
    {
        $this->_items = [];
    }

    /**
     * Returns the collection as a PHP array.
     *               The array keys are item names, and the array values are the corresponding item objects.
     *
     * @return array the array representation of the collection.
     */
    public function toArray()
    {
        $threads = [];
        $p = [];
        $p['timestamp'] = time();
        $p['direction'] = $this->direction;
        $p['activity'] = [];
        $p['objects'] = [];
        $p['lastItem'] = null;
        $p['mostRecentItem'] = null;
        $lastKey = null;
        $lastTimestamp = null;
        foreach ($this as $item) {
            $eventObject = $item->eventObject;
            $eventObject->context = $this->context;
            $package = $eventObject->package;
            if (empty($p['lastItem']) || (float)$package['timestamp'] < $p['lastItem']) {
                $p['lastItem'] = (float)$package['timestamp'];
            }
            if (empty($p['mostRecentItem']) || (float)$package['timestamp'] > $p['mostRecentItem']) {
                $p['mostRecentItem'] = (float)$package['timestamp'];
            }
            if (!isset($threads[$package['key']])) {
                $threads[$package['key']] = 0;
            }
            if ($package['key'] !== $lastKey
                || (abs((float)$package['timestamp'] - $lastTimestamp) > ($this->similarThreshold))) {
                if (isset($threads[$lastKey])) {
                    $threads[$lastKey]++;
                }
                $lastKey = $package['key'];
                $lastTimestamp = (float)$package['timestamp'];
            }
            $key = $package['key'] . '-' . $threads[$lastKey];
            if (isset($p['activity'][$key])) {
                $p['activity'][$key]['details'][$item->primaryKey] = $package['details'];
                continue;
            }
            $p['activity'][$key] = [];
            $p['activity'][$key]['id'] = $item->primaryKey;
            $p['activity'][$key]['primaryObject'] = $package['primaryObject'];
            $p['activity'][$key]['agent'] = $package['agent'];
            $p['activity'][$key]['story'] = $package['story'];
            $p['activity'][$key]['timestamp'] = $package['timestamp'];
            $p['activity'][$key]['details'] = [$item->primaryKey => $package['details']];

            foreach ($package['objects'] as $object) {
                if (isset($p['objects'][$object->primaryKey])) {
                    continue;
                }
                $p['objects'][$object->primaryKey] = $object->package;
                $p['objects'][$object->primaryKey]['descriptor'] = htmlspecialchars(strip_tags($p['objects'][$object->primaryKey]['descriptor']));
                unset($p['objects'][$object->primaryKey]['id']);
            }
        }
        //\d($p);exit;
        return $p;
    }

    /**
     * Returns whether there is a item with the specified name.
     * This method is required by the SPL interface `ArrayAccess`.
     * It is implicitly called when you use something like `isset($collection[$name])`.
     *
     * @param string $name the item name
     *
     * @return boolean whether the named item exists
     */
    public function offsetExists($name)
    {
        return $this->has($name);
    }

    /**
     * Returns the item with the specified name.
     * This method is required by the SPL interface `ArrayAccess`.
     * It is implicitly called when you use something like `$item = $collection[$name];`.
     * This is equivalent to [[get()]].
     *
     * @param string $name the item name
     *
     * @return Object the item with the specified name, null if the named item does not exist.
     */
    public function offsetGet($name)
    {
        return $this->get($name);
    }

    /**
     * Adds the item to the collection.
     * This method is required by the SPL interface `ArrayAccess`.
     * It is implicitly called when you use something like `$collection[$name] = $item;`.
     * This is equivalent to [[add()]].
     *
     * @param string $name the item name
     * @param Object $item the item to be added
     */
    public function offsetSet($name, $item)
    {
        $this->add($item);
    }

    /**
     * Removes the named item.
     * This method is required by the SPL interface `ArrayAccess`.
     * It is implicitly called when you use something like `unset($collection[$name])`.
     * This is equivalent to [[remove()]].
     *
     * @param string $name the item name
     */
    public function offsetUnset($name)
    {
        $this->remove($name);
    }

    /**
     * Get iterator.
     *
     * @return [[@doctodo return_type:getIterator]] [[@doctodo return_description:getIterator]]
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_items);
    }
}


<?php

require_once __DIR__ . "/../vendor/autoload.php";

use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\CssSelector\CssSelector;

/**
*
*/
class BotDomParser
{

  private $botList;
  private $currentBotName;

  public function __construct()
  {
    $this->currentBotName = '';
    $this->botList = [];
  }

  public function getBotList() {
    return $this->botList;
  }

  public function setBotList($newBotList) {
    $this->botList = $newBotList;
  }

  /**
   * Find bot names in the given DOM
   *
   * @param  [type] $dom [description]
   * @return void
   */
  public function parseBotNames() {
    $dom = $this->getDom('https://udger.com/resources/ua-list/crawlers');

    if (false === $dom) {
      throw new Exception("Fail to load bot list DOM.", E_WARNING);
    }

    $crawler = new Crawler();
    $crawler->addContent($dom);
    $crawler->filter('body #container table tr td > a')->each(function($node, $i) {
      $botName = $node->text();
      $this->addBotName($botName);
    });
  }

  /**
   * Get useragents of the given bot
   *
   * @param  [type] $botName [description]
   * @return void
   */
  public function parseBotUA($botName) {
    $dom = $this->getDom('https://udger.com/resources/ua-list/bot-detail?bot=' . $botName);

    if (false === $dom) {
      echo "Can not parse DOM" . PHP_EOL;
      return false;
    }

    $this->currentBotName = $botName;
    $crawlerBot = new Crawler();
    $crawlerBot->addContent($dom);
    $crawlerBot->filter('body #container table tr td > a')->each(function($el, $i) {
      if (strpos($el->attr('href'), '/resources/online-parser') !== false) {
        $botUA = $el->text();
        $this->addBotUA($botUA);
      }
    });

    return true;
  }

  private function addBotName($name) {
    $this->botList[$name] = [];
    echo "Add bot " . $name . PHP_EOL;
  }

  private function addBotUA($ua) {
    $this->botList[$this->currentBotName][] = $ua;
    echo "Add UA for bot " . $this->currentBotName . PHP_EOL;
  }

  /**
   * Get the dom tree of a given url
   *
   * @param  [type] $url [description]
   * @return [string] $dom
   */
  private function getDom($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $dom = curl_exec($ch);
    curl_close($ch);

    return $dom;
  }
}


<?php

namespace Reliv\Mustache\Resolver;

use Phly\Mustache\Resolver\ResolverInterface;
use Reliv\CacheRat\Service\Cache;

/**
 * @author James Jervis - https://github.com/jerv13
 */
class FileResolver implements ResolverInterface
{
    const DEFAULT_CACHE_KEY = 'ZrcmsMustacheFileResolver';

    protected $cache;
    protected $cacheKey;

    /**
     * @param Cache  $cache
     * @param string $cacheKey
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function __construct(
        Cache $cache,
        string $cacheKey = self::DEFAULT_CACHE_KEY
    ) {
        $this->cache = $cache;
        $this->cacheKey = $cacheKey;
        $this->cache->set($this->cacheKey, []);
    }

    /**
     * @param string $templatePath
     *
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function hasCache(string $templatePath)
    {
        $cache = $this->cache->get($this->cacheKey);

        return array_key_exists($templatePath, $cache);
    }

    /**
     * @param string $templatePath
     *
     * @return null
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function getCache(string $templatePath)
    {
        if (!$this->hasCache($templatePath)) {
            return null;
        }
        $cache = $this->cache->get($this->cacheKey);

        return $cache[$templatePath];
    }

    /**
     * @param string $templatePath
     * @param        $template
     *
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function setCache(string $templatePath, $template)
    {
        $cache = $this->cache->get($this->cacheKey);

        $cache[$templatePath] = $template;

        $this->cache->set($this->cacheKey, $cache);
    }

    /**
     * Resolve a template name to mustache content or a set of tokens.
     *
     * @param string $templatePath
     *
     * @return array|bool|null|string
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function resolve($templatePath)
    {
        $templatePathReal = realpath($templatePath);

        if ($templatePathReal === false) {
            throw new \Exception(
                'Template file does not exist: ' . $templatePath
            );
        }

        if ($this->hasCache($templatePathReal)) {
            return $this->getCache($templatePathReal);
        }

        $template = file_get_contents(
            $templatePathReal
        );

        $this->setCache($templatePathReal, $template);

        return $template;
    }
}


<?php

namespace Weew\Container;

use Exception;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionParameter;
use Weew\Container\Exceptions\ImplementationNotFoundException;
use Weew\Container\Exceptions\InvalidCallableFormatException;
use Weew\Container\Exceptions\UnresolveableArgumentException;
use Weew\Container\Exceptions\ValueNotFoundException;

class Reflector {
    /**
     * @param IContainer $container
     * @param $className
     * @param array $args
     *
     * @return object
     * @throws InterfaceIsNotInstantiableException
     */
    public function resolveClass(
        IContainer $container,
        $className,
        array $args = []
    ) {
        return $this->resolveConstructor($container, $className, $args);
    }

    /**
     * @param IContainer $container
     * @param $className
     * @param array $args
     *
     * @return object
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    protected function resolveConstructor(
        IContainer $container,
        $className,
        array $args = []
    ) {
        $class = new ReflectionClass($className);
        $constructor = $class->getConstructor();

        if ($constructor !== null) {
            $arguments = $this->resolveMethodArguments($container, $class, $constructor, $args);

            return $class->newInstanceArgs($arguments);
        }

        return $class->newInstance();
    }

    /**
     * @param IContainer $container
     * @param $instance
     * @param $methodName
     * @param array $args
     *
     * @return mixed
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    public function resolveMethod(
        IContainer $container,
        $instance, $methodName,
        array $args = []
    ) {
        $class = new ReflectionClass($instance);
        $method = $class->getMethod($methodName);
        $arguments = $this->resolveMethodArguments($container, $class, $method, $args);

        if ($method->isStatic()) {
            $instance = null;
        } else if (is_string($instance)) {
            $instance = $container->get($instance);
        }

        return $method->invokeArgs($instance, $arguments);
    }

    /**
     * @param IContainer $container
     * @param ReflectionClass $class
     * @param ReflectionMethod $method
     * @param array $args
     *
     * @return array
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    protected function resolveMethodArguments(
        IContainer $container,
        ReflectionClass $class,
        ReflectionMethod $method,
        array $args = []
    ) {
        try {
            return $this->buildArgumentsFromParameters(
                $container, $method->getParameters(), $args
            );
        } catch (UnresolveableArgumentException $ex) {
            $ex->setClassName($class->getName());
            $ex->setMethodName($method->getName());

            throw $ex;
        }
    }

    /**
     * @param IContainer $container
     * @param $callable
     * @param array $args
     *
     * @return mixed
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    public function resolveCallable(
        IContainer $container,
        $callable,
        array $args = []
    ) {
        if (is_string($callable) && function_exists($callable) || is_object($callable)) {
            return $this->resolveFunction($container, $callable, $args);
        } else if (is_array($callable) && is_callable($callable)) {
            return $this->resolveMethod($container, $callable[0], $callable[1], $args);
        } else {
            throw new InvalidCallableFormatException('Invalid callable given.');
        }
    }

    /**
     * @param IContainer $container
     * @param $functionName
     * @param array $args
     *
     * @return mixed
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    public function resolveFunction(
        IContainer $container,
        $functionName,
        array $args = []
    ) {
        $function = new ReflectionFunction($functionName);

        try {
            $arguments = $this->buildArgumentsFromParameters(
                $container, $function->getParameters(), $args
            );
        } catch (UnresolveableArgumentException $ex) {
            $ex->setFunctionName($function->isClosure() ? 'Closure' : $function->getName());

            throw $ex;
        }

        return $function->invokeArgs($arguments);
    }

    /**
     * @param IContainer $container
     * @param ReflectionParameter[] $parameters
     * @param array $args
     *
     * @return array
     * @throws Exception
     * @throws UnresolveableArgumentException
     */
    protected function buildArgumentsFromParameters(
        IContainer $container,
        array $parameters,
        array $args
    ) {
        $arguments = [];

        foreach ($parameters as $index => $parameter) {
            try {
                $arguments[] = $this->getParameterValue($container, $parameter, $args);
            } catch (UnresolveableArgumentException $ex) {
                $ex->setArgumentName($parameter->getName());
                $ex->setArgumentIndex($index + 1);

                throw $ex;
            }
        }

        return $arguments;
    }

    /**
     * @param IContainer $container
     * @param ReflectionParameter $parameter
     * @param array $args
     *
     * @return mixed
     * @throws Exception
     */
    protected function getParameterValue(
        IContainer $container,
        ReflectionParameter $parameter,
        array $args
    ) {
        $parameterName = $parameter->getName();

        if (array_has($args, $parameterName)) {
            return $args[$parameterName];
        }

        if ($parameter->getClass() !== null) {
            return $this->getParameterFromContainer($container, $parameter);
        }

        if ($parameter->isDefaultValueAvailable()) {
            return $parameter->getDefaultValue();
        }

        throw new UnresolveableArgumentException(
            s('Value not found for argument %s.', $parameterName)
        );
    }

    /**
     * @param IContainer $container
     * @param ReflectionParameter $parameter
     *
     * @return mixed
     * @throws Exception
     * @throws ValueNotFoundException
     */
    protected function getParameterFromContainer(
        IContainer $container,
        ReflectionParameter $parameter
    ) {
        try {
            return $container->get($parameter->getClass()->getName());
        } catch (Exception $ex) {
            $ignoreException = (
                $ex instanceof ValueNotFoundException ||
                $ex instanceof ImplementationNotFoundException
            );

            if ( ! ($ignoreException && $parameter->isDefaultValueAvailable())) {
                throw $ex;
            }
        }
    }
}


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

namespace CmsUser\Factory\Mvc\Controller;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    CmsUser\Mvc\Controller\IndexController,
    CmsUser\Options\ControllerOptionsInterface,
    CmsUser\Options\ModuleOptions;

class IndexControllerFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return IndexController
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $services = $serviceLocator->getServiceLocator();
        /* @var $options ControllerOptionsInterface */
        $options = $services->get(ModuleOptions::class);

        return new IndexController(
            $services->get('DomainServiceManager')->get($options->getUserEntityClass()),
            $options
        );
    }
}


<?php

namespace TaylorNetwork\LaravelHelpers;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use TaylorNetwork\LaravelHelpers\Commands\HelperMakeCommand;

class LaravelHelpersServiceProvider extends ServiceProvider
{
    /**
     * The path to package helpers
     *
     * @var string
     */
    protected $packageHelperPath;

    /**
     * Pattern to include package helpers by
     *
     * @var string
     */
    protected $packageHelperPattern;

    /**
     * The package helpers
     *
     * @var array
     */
    protected $packageHelpers;

    /**
     * The package helpers to include
     *
     * @var array
     */
    protected $packageInclude;

    /**
     * The user created helpers to include
     *
     * @var array
     */
    protected $customInclude;

    /**
     * The user created helpers to exclude
     *
     * @var array
     */
    protected $customExclude;

    /**
     * The namespace to store user created helpers
     *
     * @var string
     */
    protected $namespace;

    /**
     * LaravelHelpersServiceProvider constructor.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        parent::__construct($app);

        $this->packageHelperPath = __DIR__ . '/helpers';
        $this->packageHelperPattern = $this->packageHelperPath . '/{dashName}/src/{underscoreName}.php';
        $this->packageHelpers = glob($this->packageHelperPath.'/*');

        $this->packageInclude = config('laravel_helpers.helpers', ['*']);
        $this->customInclude = config('laravel_helpers.include', ['*']);
        $this->customExclude = config('laravel_helpers.exclude', []);
        $this->namespace = config('laravel_helpers.namespace', 'Helpers');
    }

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/config/laravel_helpers.php', 'laravel_helpers'
        );

        $this->registerCommands();
        $this->registerCustomHelpers();
        $this->registerPackageHelpers();
    }

    /**
     * Register Commands
     */
    public function registerCommands()
    {
        $this->commands([
            HelperMakeCommand::class,
        ]);
    }

    /**
     * Register the package helpers
     */
    public function registerPackageHelpers()
    {
        foreach($this->packageHelpers as $helper)
        {
            $dashName = last(explode('/', $helper));
            $underscoreName = str_replace('-', '_', $dashName);

            if(in_array('*', $this->packageInclude) ||
                in_array($dashName, $this->packageInclude) ||
                in_array($underscoreName, $this->packageInclude))
            {
                require_once $this->replaceVariables($this->packageHelperPattern, compact('dashName', 'underscoreName'));
            }
        }

    }

    /**
     * Register custom helpers
     */
    public function registerCustomHelpers()
    {
        foreach(glob(app_path($this->namespace.'/*')) as $helper)
        {
            $helperName = last(explode('/', $helper));
            if(!in_array($helperName, $this->customExclude))
            {
                if(in_array('*', $this->customInclude) || in_array($helperName, $this->customInclude))
                {
                    require_once $helper;
                }
            }
        }
    }

    /**
     * Replace variables in string with their values.
     *
     * @param $string
     * @param array $replaces
     * @return string
     */
    public function replaceVariables($string, $replaces = [])
    {
        $callback = function ($match) use ($replaces) {
            $variable = trim($match[0], '{}');

            if(array_key_exists($variable, $replaces))
            {
                return $replaces[$variable];
            }

            return $variable;
        };

        return preg_replace_callback('/{.*?}/', $callback, $string);
    }
}


<?php
/**
 * (c) Joffrey Demetz <joffrey.demetz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JDZ\Filesystem;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Exception;

/**
 * Path Helper
 *
 * @author Joffrey Demetz <joffrey.demetz@gmail.com>
 */
abstract class Path
{
  protected static $ROOT_PATH = '';

  public static function setRootPath($path)
  {
    self::$ROOT_PATH = $path;
  }

  /**
   * Checks if a path's permissions can be changed.
   *
   * @param   string  $path  Path to check.
   * @return   boolean  True if path can have mode changed.
   */
  public static function canChmod($path)
  {
    $perms = fileperms($path);
    if ($perms !== false)
    {
      if (@chmod($path, $perms ^ 0001))
      {
        @chmod($path, $perms);
        return true;
      }
    }

    return false;
  }

  /**
   * Chmods files and directories recursively to given permissions.
   *
   * @param   string  $path   Root path to begin changing mode [without trailing slash].
   * @param   string  $mode   Octal representation of the value to change mode.
   * @return   boolean  True if successful
   */
  public static function setPermissions($path, $mode=0777, $recursive=true)
  {
    $path = Path::clean($path);

    $fs = new Filesystem();

    try {
      $fs->chmod($path, $mode, 0000, $recursive);
    } catch(IOExceptionInterface $e){
      return false;
    }

    return true;
  }

  /**
   * Function to strip additional / or \ in a path name.
   *
   * @param   string  $path  The path to clean.
   * @param   string  $ds    Directory separator (optional).
   * @return   string  The cleaned path
   * @throws   Exception
   */
  public static function clean($path, $ds=DIRECTORY_SEPARATOR)
  {
    if ( !is_string($path) && !empty($path) ){
      return '';
      throw new Exception('Path::clean: $path is not a string or is empty.');
    }

    $path = trim($path);

    if ( empty($path) ){
      $path = self::$ROOT_PATH;
    }

    // Remove double slashes and backslashes and convert all slashes and backslashes to DIRECTORY_SEPARATOR
    // If dealing with a UNC path don't forget to prepend the path with a backslash.
    elseif ( $ds == '\\' && $path[0] == '\\' && $path[1] == '\\' ){
      $path = "\\" . preg_replace('#[/\\\\]+#', $ds, $path);
    }
    else {
      $path = preg_replace('#[/\\\\]+#', $ds, $path);
    }

    return $path;
  }
}


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

namespace RedKiteCms\Tools;

use RedKiteCms\Exception\General\RuntimeException;

/**
 * Class FilesystemTools collects several methods related to the filesystem
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Tools
 */
class FilesystemTools
{
    /**
     * Looks for the current slots dir. Slots are sought in cascade in pages folders, languages repeated slots and site
     * repeated slots
     *
     * @param $sourceDir
     * @param array $options
     *
     * @return null|string
     */
    public static function slotDir($sourceDir, array $options)
    {
        $paths = array(
            sprintf(
                '%s/pages/pages/%s/%s_%s/%s',
                $sourceDir,
                $options['page'],
                $options['language'],
                $options['country'],
                $options['slot']
            ),
            sprintf('%s/slots/%s/%s_%s', $sourceDir, $options['slot'], $options['language'], $options['country']),
            sprintf('%s/slots/%s', $sourceDir, $options['slot']),
        );

        return self::cascade($paths);
    }

    /**
     * Parses given folders and returns the first existing one
     *
     * @param array $folder
     *
     * @return null|string
     */
    public static function cascade(array $folders)
    {
        $result = null;
        foreach ($folders as $folder) {
            if (is_dir($folder)) {
                $result = $folder;

                break;
            }
        }

        return $result;
    }

    /**
     * Reads and locks a file from the filesystem
     *
     * @param $file
     *
     * @return string
     */
    public static function readFile($file)
    {
        if (!file_exists($file)) {
            return null;
        }

        $handle = fopen($file, 'r');
        if (!self::lockFile($handle, LOCK_SH | LOCK_NB)) {
            $exception = array(
                "message" => 'exception_file_cannot_be_locked_for_reading',
                "parameters" => array(
                    "%file%" => basename($file),
                )
            );
            throw new RuntimeException(json_encode($exception));
        }

        $contents = file_get_contents($file);
        self::unlockFile($handle);

        return $contents;
    }

    /**
     * Locks and write a file to the filesystem
     *
     * @param string $file
     * @param string $content
     */
    public static function writeFile($file, $content)
    {
        $handle = fopen($file, 'w');
        if (!self::lockFile($handle, LOCK_EX | LOCK_NB)) {
            $exception = array(
                "message" => 'exception_file_cannot_be_locked_for_writing',
                "parameters" => array(
                    "%file%" => basename($file),
                )
            );
            throw new RuntimeException(json_encode($exception));
        }
        if (fwrite($handle, $content) === false) {
            $exception = array(
                "message" => 'exception_file_cannot_be_written',
                "parameters" => array(
                    "%file%" => basename($file),
                )
            );
            throw new RuntimeException(json_encode($exception));
        }
        self::unlockFile($handle);
    }

    private static function lockFile($handle, $flags)
    {
        $locked = false;
        $tries = 5;
        while ($tries > 0) {
            $locked = flock($handle, $flags);
            if (false !== $locked) {
                break;
            }

            sleep(1);
            $tries--;
        }

        return $locked;
    }

    private static function unlockFile($handle)
    {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

/**
 * @link http://redis.io/commands/zunionstore
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ZUNIONSTORE extends RedisCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'ZUNIONSTORE';
    }

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        $options = array();
        $argc = count($arguments);

        if ($argc > 2 && is_array($arguments[$argc - 1])) {
            $options = $this->prepareOptions(array_pop($arguments));
        }

        if (is_array($arguments[1])) {
            $arguments = array_merge(
                array($arguments[0], count($arguments[1])),
                $arguments[1]
            );
        }

        parent::setArguments(array_merge($arguments, $options));
    }

    /**
     * Returns a list of options and modifiers compatible with Redis.
     *
     * @param array $options List of options.
     *
     * @return array
     */
    private function prepareOptions($options)
    {
        $opts = array_change_key_case($options, CASE_UPPER);
        $finalizedOpts = array();

        if (isset($opts['WEIGHTS']) && is_array($opts['WEIGHTS'])) {
            $finalizedOpts[] = 'WEIGHTS';

            foreach ($opts['WEIGHTS'] as $weight) {
                $finalizedOpts[] = $weight;
            }
        }

        if (isset($opts['AGGREGATE'])) {
            $finalizedOpts[] = 'AGGREGATE';
            $finalizedOpts[] = $opts['AGGREGATE'];
        }

        return $finalizedOpts;
    }
}


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

namespace cascade\components\base;

use Yii;

/**
 * ModuleSetExtension base class for a module set.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class ModuleSetExtension implements \yii\base\BootstrapInterface
{
    /**
     * Bootstrap the module set on load.
     *
     * @param Application $app the application parameter
     */
    public function bootstrap($app)
    {
        Yii::beginProfile(get_called_class());
        Yii::$app->modules = static::getModules();
        Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, [$this, 'beforeRequest']);
        Yii::endProfile(get_called_class());
        Yii::trace("Registered " . count(static::getModules()) . " modules in " . get_called_class());
    }

    /**
     * Actions to run before request starts.
     *
     * @param Event $event the event parameter
     */
    public function beforeRequest($event)
    {
    }

    /**
     * Get modules.
     *
     * @return array of the modules in the set
     */
    public static function getModules()
    {
        return [];
    }
}


<?php

/*
 * This file is part of the P13/DateTime package.
 *
 * (c) Wagner Sicca <wssicca@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace p13\datetime;

/**
 * Extensão da classe DateTime com funções
 * relacionadas somente ao tempo, ignorando a data
 *
 * @author Wagner Sicca <wssicca@gmail.com>
 * @namespace p13\datetime
 * @package p13\datetime
 */
class Time extends DateTime implements ExtensionInterface
{

    /**
     * Retorna a data no formato d/m/Y
     * @return string
     */
    public function __toString()
    {
        return $this->format('H:i');
    }

    /**
     * Faz o "cast" de \DateTime para p13\datetime\Time
     * @param \DateTime $time
     * @return Time
     */
    public static function cast($time)
    {
        return $time instanceof self ?
                $time :
                new self($time->format(self::ISO8601), $time->getTimezone());
    }

}


<?php
/**
 * This file is part of SoloProyectos common library.
 *
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http-controller/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http-controller
 */
namespace soloproyectos\http\data;
use soloproyectos\arr\Arr;
use soloproyectos\http\data\HttpDataInterface;

/**
 * Class HttpRequest.
 *
 * This class is used to access the request variables.
 *
 * @package Http\Data
 * @author  Gonzalo Chumillas <gchumillas@email.com>
 * @license https://github.com/soloproyectos-php/http-controller/blob/master/LICENSE The MIT License (MIT)
 * @link    https://github.com/soloproyectos-php/http-controller
 */
class HttpRequest implements HttpDataInterface
{
    /**
     * Gets a request attribute.
     *
     * @param string $name    HttpRequest attribute.
     * @param string $default Default value (not required)
     *
     * @return mixed
     */
    public function get($name, $default = "")
    {
        $param = Arr::get($_REQUEST, $name, $default);

        if ($_SERVER["REQUEST_METHOD"] == "GET" && is_string($param)) {
            $param = urldecode($param);
        }

        return $param;
    }

    /**
     * Sets a request attribute.
     *
     * @param string $name  HttpRequest attribute.
     * @param mixed  $value HttpRequest value.
     *
     * @return void
     */
    public function set($name, $value)
    {
        $_REQUEST[$name] = $value;
    }

    /**
     * Does the request attribute exist?
     *
     * @param string $name HttpRequest attribute.
     *
     * @return boolean
     */
    public function exist($name)
    {
        return Arr::exist($_REQUEST, $name);
    }

    /**
     * Deletes a request attribute.
     *
     * @param string $name HttpRequest attribute.
     *
     * @return void
     */
    public function delete($name)
    {
        Arr::delete($_REQUEST, $name);
    }
}


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

namespace cascade\components\web\form;

use canis\helpers\Html;
use Yii;

/**
 * Generator [[@doctodo class_description:cascade\components\web\form\Generator]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Generator extends \canis\base\Object implements \canis\web\RenderInterface
{
    /**
     * @var [[@doctodo var_type:_items]] [[@doctodo var_description:_items]]
     */
    protected $_items;
    /**
     * @var [[@doctodo var_type:form]] [[@doctodo var_description:form]]
     */
    public $form;

    /**
     * @var [[@doctodo var_type:models]] [[@doctodo var_description:models]]
     */
    public $models = [];

    /**
     * @var [[@doctodo var_type:isValid]] [[@doctodo var_description:isValid]]
     */
    public $isValid = true;
    /**
     * @var [[@doctodo var_type:class]] [[@doctodo var_description:class]]
     */
    public $class = '';
    /**
     * @var [[@doctodo var_type:ajax]] [[@doctodo var_description:ajax]]
     */
    public $ajax = false;

    /**
     * Set items.
     *
     * @param [[@doctodo param_type:items]] $items [[@doctodo param_description:items]]
     */
    public function setItems($items)
    {
        $this->_items = $items;
        if (isset($this->_items[0]) && is_array($this->_items[0])) {
            $this->_items = $this->_items[0];
        }
        foreach ($this->_items as $item) {
            $item->owner = $this;
            if (!$item->isValid) {
                $this->isValid = false;
            }
        }
    }

    /**
     * [[@doctodo method_description:generate]].
     *
     * @return unknown
     */
    public function generate()
    {
        if (empty($this->_items)) {
            return '';
        }
        $result = [];
        $formOptions = [
            'options' => ['class' => ''], //form-horizontal
            'enableClientValidation' => false,
        ];
        if (Yii::$app->request->isAjax) {
            Html::addCssClass($formOptions['options'], 'ajax');
        }

        if ($this->hasFile() && !isset($formOptions['options']['enctype'])) {
            $formOptions['options']['enctype'] = 'multipart/form-data';
        }

        list($this->form, $formStartRow) = ActiveForm::begin($formOptions, false);
        $result[] = $formStartRow;
        // $result[] = Html::beginForm('', 'post', array('class' => $this->class));
        $result[] = Html::beginTag('div', ['class' => '']);
        foreach ($this->_items as $item) {
            $result[] = $item->generate();
        }
        //if (!Yii::$app->request->isAjax) {
            $result[] = Html::beginTag('div', ['class' => 'row form-group submit-group']);
        $result[] = Html::beginTag('div', ['class' => 'col-sm-12']);
        $result[] = Html::submitButton('Save', ['class' => 'btn btn-primary']);
        $result[] = Html::endTag('div');
        $result[] = Html::endTag('div');
        //}
        $result[] = Html::endTag('div');
        $result[] = ActiveForm::end(false);

        return implode("\n", $result);
    }

    /**
     * [[@doctodo method_description:hasFile]].
     *
     * @return [[@doctodo return_type:hasFile]] [[@doctodo return_description:hasFile]]
     */
    public function hasFile()
    {
        foreach ($this->_items as $item) {
            if ($item->hasFile()) {
                return true;
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:output]].
     */
    public function output()
    {
        echo $this->generate();
    }
}


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

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\Content\Block\BlockFactory;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockAddedEvent;
use RedKiteCms\EventSystem\Event\Block\BlockAddingEvent;
use RedKiteCms\Tools\FilesystemTools;

/**
 * Class BlockManagerAdd is the object assigned to add a new block to the given slot
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerAdd extends BlockManager
{
    /**
     * Adds the block to the slot for the given language and page
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     *
     * @return string The saved content
     */
    public function add($sourceDir, array $options, $username)
    {
        $this->resolveAddOptions($options);
        $this->createContributorDir($sourceDir, $options, $username);

        $dir = $this
            ->init($sourceDir, $options, $username)
            ->getDirInUse()
        ;
        $blockName = $this->addBlockToSlot($dir, $options);
        $blockContent = $this->addBlock($dir, $options, $blockName);

        DataLogger::log(
            sprintf(
                'Block "%s" has been added to the "%s" slot on page "%s" for the "%s_%s" language',
                $blockName,
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );

        return $blockContent;
    }

    /**
     * Defines the options required by the add method
     *
     * @param array $options
     */
    protected function resolveAddOptions(array $options)
    {
        if ($this->optionsResolved) {
            // @codeCoverageIgnoreStart
            return;
            // @codeCoverageIgnoreEnd
        }

        $this->optionsResolver->clear();
        $this->optionsResolver->setRequired(
            array(
                'page',
                'language',
                'country',
                'slot',
                'blockname',
                'type',
                'position',
                'direction',
            )
        );

        $this->optionsResolver->resolve($options);
        $this->optionsResolved = true;
    }

    private function addBlock($dir, array $options, $blockName)
    {
        $filename = sprintf('%s/blocks/%s.json', $dir, $blockName);
        $block = BlockFactory::createBlock($options["type"]);
        $block->setName($blockName);
        $block->setSlotName($options["slot"]);
        $blockClass = get_class($block);
        $encodedBlock = $this->serializer->serialize($block, 'json');

        $event = Dispatcher::dispatch(
            BlockEvents::BLOCK_ADDING,
            new BlockAddingEvent($this->serializer, $filename, $encodedBlock, $blockClass)
        );
        $blockContent = $event->getFileContent();

        FilesystemTools::writeFile($filename, $blockContent);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_ADDED,
            new BlockAddedEvent($this->serializer, $filename, $encodedBlock, $blockClass)
        );

        return $blockContent;
    }
}


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

namespace cascade\components\web\browser;

use Yii;

/**
 * Response [[@doctodo class_description:cascade\components\web\browser\Response]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Response extends \canis\web\browser\Response
{
    /**
     * @inheritdoc
     */
    public $bundleClass = 'cascade\components\web\browser\Bundle';

    /**
     * [[@doctodo method_description:defaultInstructions]].
     *
     * @return [[@doctodo return_type:defaultInstructions]] [[@doctodo return_description:defaultInstructions]]
     */
    public static function defaultInstructions()
    {
        return [
            'offset' => 0,
        ];
    }
    /**
     * [[@doctodo method_description:parseStack]].
     *
     * @param [[@doctodo param_type:request]] $request [[@doctodo param_description:request]]
     *
     * @return [[@doctodo return_type:parseStack]] [[@doctodo return_description:parseStack]]
     */
    public static function parseStack($request)
    {
        $instructions = [];
        if (empty($request['stack'])) {
            return false;
        }

        $lastItem = array_pop($request['stack']);
        if (!isset($lastItem['type'])) {
            return false;
        }
        $instructions['id'] = $request['id'];
        $registryClass = Yii::$app->classes['Registry'];
        switch ($lastItem['type']) {
            case 'type': //object type
                $parentItem = false;
                $instructions['handler'] = 'objects';
                if (!empty($request['stack'])) {
                    $parentItem = array_pop($request['stack']);
                }
                $type = Yii::$app->collectors['types']->getOne($lastItem['id']);
                if (!$type) {
                    return false;
                }
                $instructions['type'] = $lastItem['id'];
                if ($parentItem && $parentItem['type'] === 'object' && !empty($parentItem['id'])) {
                    $instructions['parent'] = $parentItem['id'];
                }
            break;
            case 'object': //object type
                $object = $registryClass::getObject($lastItem['id']);
                if (!$object) {
                    return false;
                }
                $objectTypeItem = $object->objectTypeItem;
                $objectType = $objectTypeItem->object;
                if (!isset($request['modules'])) {
                    $request['modules'] = array_keys(Yii::$app->collectors['types']->getAll());
                }
                $possibleTypes = HandlerTypes::possibleTypes($objectType, $request['modules']);

                //\d(array_keys($possibleTypes));exit;
                if (empty($possibleTypes)) {
                    return false;
                } elseif (count($possibleTypes) === 1) {
                    $type = array_pop($possibleTypes);
                    $instructions['handler'] = 'objects';
                    $instructions['type'] = $type->systemId;
                    $instructions['parent'] = $object->primaryKey;
                } else {
                    $instructions['handler'] = 'types';
                    $instructions['limitTypes'] = array_keys($possibleTypes);
                }
            break;
        }

        return $instructions;
    }
}


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

namespace CmsUser\Service;

use Zend\Form\FormInterface,
    Zend\I18n\Translator\TranslatorAwareInterface,
    Zend\I18n\Translator\TranslatorAwareTrait,
    Zend\ServiceManager\ServiceManager,
    Zend\View\Model\ViewModel,
    CmsCommon\Crypt\PasswordGeneratorInterface,
    CmsCommon\Mapping\Common\PasswordableInterface,
    CmsCommon\Mapping\Common\StateableInterface,
    CmsCommon\Persistence\MapperInterface,
    CmsCommon\Service\DomainService,
    CmsMailer\Service\MailServiceAwareTrait,
    CmsMailer\Service\MailServiceInterface,
    CmsUser\Mapping\UserInterface,
    CmsUser\Options\UserServiceOptionsInterface,
    CmsUser\Persistence\UserMapperInterface;

/**
 * User service
 *
 * @author Dmitry Popov <d.popov@altgraphic.com>
 *
 * @method UserMapperInterface getMapper() Retrieves user mapper
 */
class UserService extends DomainService implements
        UserServiceInterface,
        TranslatorAwareInterface
{
    use MailServiceAwareTrait,
        TranslatorAwareTrait;

    /**
     * @var FormInterface
     */
    protected $registerForm;

    /**
     * @var FormInterface
     */
    protected $editProfileForm;

    /**
     * @var FormInterface
     */
    protected $changePasswordForm;

    /**
     * @var FormInterface
     */
    protected $resetPasswordForm;

    /**
     * @var FormInterface
     */
    protected $changeEmailForm;

    /**
     * @var FormInterface
     */
    protected $changeSecurityQuestionForm;

    /**
     * @var PasswordGeneratorInterface
     */
    protected $passwordGenerator;

    /**
     * {@inheritDoc}
     *
     * @param PasswordGeneratorInterface $passwordGenerator
     * @param MailServiceInterface $mailService
     */
    public function __construct(
        UserServiceOptionsInterface $options,
        ServiceManager $manager,
        PasswordGeneratorInterface $passwordGenerator,
        MailServiceInterface $mailService
    ) {
        $this->setClassName($options->getUserEntityClass());
        parent::__construct($options, $manager);
        $this->setPasswordGenerator($passwordGenerator);
        $this->setMailService($mailService);
    }

    /**
     * Register user
     *
     * @param array|UserInterface $data
     * @return UserInterface|void
     */
    public function register($data)
    {
        /* @var $user UserInterface */
        if (!($user = $this->hydrate($data, $this->getRegisterForm()))) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__FUNCTION__, $this, compact('user'));

        if ($user instanceof StateableInterface) {
            $user->setState($this->getOption('default_user_state'));
        }

        $user->setRegistrationToken($this->getRegistrationToken());

        if ($user instanceof PasswordableInterface) {
            $cryptoService = $this->getMapper()->getPasswordService();
            $password = $cryptoService->create($user->getPassword());
            $user->setPassword($password);
        }

        $viewModel = new ViewModel(compact('user'));
        $viewModel->setTemplate('mail-message/user-register');

        $mailService = $this->getMailService();
        $message = $mailService->getMessage();
        $message->setTo($user->getEmail(), $user->getDisplayName());

        $subject = 'Please, complete your registration!';
        if ($this->getTranslator() && $this->isTranslatorEnabled()) {
            $subject = $this->getTranslator()->translate(
                $subject,
                $this->getTranslatorTextDomain()
            );
        }
        $message->setSubject($subject);

        $mailService->setBody($viewModel)->sendMessage();

        $this->getMapper()->add($user)->save();

        $eventManager->trigger(__FUNCTION__ . '.post', $this, compact('user'));

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getRegisterForm()
    {
        if (null === $this->registerForm) {
            $sm = $this->getServiceLocator();
            $this->setRegisterForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\Register'));
        }

        return $this->registerForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setRegisterForm(FormInterface $form)
    {
        $this->registerForm = $form;
        return $this;
    }

    /**
     * Edit user profile
     *
     * @param array|UserInterface $data
     * @return UserInterface|void
     */
    public function editProfile($data)
    {
        /* @var $user UserInterface */
        if (!($user = $this->hydrate($data, $this->getEditProfileForm()))) {
            return;
        }

    	$eventManager = $this->getEventManager();
    	$eventManager->trigger(__FUNCTION__, $this, compact('user'));

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

    	$eventManager->trigger(__FUNCTION__ . '.post', $this, compact('user'));

    	return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getEditProfileForm()
    {
        if (null === $this->editProfileForm) {
            $sm = $this->getServiceLocator();
            $this->setEditProfileForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\EditProfile'));
        }

        return $this->editProfileForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setEditProfileForm(FormInterface $form)
    {
        $this->editProfileForm = $form;
        return $this;
    }

    /**
     * Confirm user email
     *
     * @param string $token
     * @return UserInterface|void
     */
    public function confirmEmail($token)
    {
        /* @var $user UserInterface */
        $user = $this->getMapper()->findOneBy(['registrationToken' => $token]);
        if (!$user instanceof UserInterface) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

        $user->setRegistrationToken($this->getRegistrationToken());
        $user->setEmailConfirmed(true);
        $this->getMapper()->update($user)->save();

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * Change user password
     *
     * @param array|UserInterface $data
     * @return UserInterface|void
     */
    public function changePassword($data)
    {
        /* @var $user UserInterface */
        if (!($user = $this->hydrate($data, $this->getChangePasswordForm()))) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

        $password = $user->getPassword();
        $passwordService = $this->getMapper()->getPasswordService();
        $user->setPassword($passwordService->create($password));
        $this->getMapper()->update($user)->save();

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getChangePasswordForm()
    {
        if (null === $this->changePasswordForm) {
            $sm = $this->getServiceLocator();
            $this->setChangePasswordForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\ChangePassword'));
        }

        return $this->changePasswordForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setChangePasswordForm(FormInterface $form)
    {
        $this->changePasswordForm = $form;
        return $this;
    }

    /**
     * Reset user password
     *
     * @param mixed $identity
     * @return UserInterface|void
     */
    public function resetPassword($identity)
    {
        $user = $this->getMapper()->findByIdentity($identity);
        if (!$user instanceof UserInterface) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

        $user->setRegistrationToken($this->getRegistrationToken());

        $viewModel = new ViewModel(compact('user'));
        $viewModel->setTemplate('mail-message/user-reset-password');

        $mailService = $this->getMailService();
        $message = $mailService->getMessage();
        $message->setTo($user->getEmail(), $user->getDisplayName());

        $subject = 'Please, confirm your request to change password!';
        if ($this->getTranslator() && $this->isTranslatorEnabled()) {
            $subject = $this->getTranslator()->translate(
                $subject,
                $this->getTranslatorTextDomain()
            );
        }
        $message->setSubject($subject);

        $mailService->setBody($viewModel)->sendMessage();

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

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getResetPasswordForm()
    {
        if (null === $this->resetPasswordForm) {
            $sm = $this->getServiceLocator();
            $this->setResetPasswordForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\ResetPassword'));
        }

        return $this->resetPasswordForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setResetPasswordForm(FormInterface $form)
    {
        $this->resetPasswordForm = $form;
        return $this;
    }

    /**
     * Password reset confirmation method
     *
     * @param string $token
     * @param UserInterface|void
     */
    public function confirmPasswordReset($token)
    {
        $user = $this->getMapper()->findOneBy(['registrationToken' => $token]);
        if (!$user instanceof UserInterface) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

        $user->setRegistrationToken($this->getRegistrationToken());
        $user->setEmailConfirmed(true);

        $password = $this->getPasswordGenerator()->generate();
        $passwordService = $this->getMapper()->getPasswordService();
        $user->setPassword($passwordService->create($password));

        $viewModel = new ViewModel(compact('user', 'password'));
        $viewModel->setTemplate('mail-message/user-change-password-success');

        $mailService = $this->getMailService();
        $message = $mailService->getMessage();
        $message->setTo($user->getEmail(), $user->getDisplayName());

        $subject = 'Your password has been changed!';
        if ($this->getTranslator() && $this->isTranslatorEnabled()) {
            $subject = $this->getTranslator()->translate(
                $subject,
                $this->getTranslatorTextDomain()
            );
        }
        $message->setSubject($subject);

        $mailService->setBody($viewModel)->sendMessage();

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

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * Change user email
     *
     * @param array|UserInterface $data
     * @return UserInterface|void
     */
    public function changeEmail($data)
    {
        /* @var $user UserInterface */
        if (!($user = $this->hydrate($data, $this->getChangeEmailForm()))) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

        $user->setEmailConfirmed(false);

        $viewModel = new ViewModel(compact('user'));
        $viewModel->setTemplate('mail-message/user-confirm-email');

        $mailService = $this->getMailService();
        $message = $mailService->getMessage();
        $message->setTo($user->getEmail(), $user->getDisplayName());

        $subject = 'Please, confirm your email!';
        if ($this->getTranslator() && $this->isTranslatorEnabled()) {
            $subject = $this->getTranslator()->translate(
                $subject,
                $this->getTranslatorTextDomain()
            );
        }
        $message->setSubject($subject);

        $mailService->setBody($viewModel)->sendMessage();

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

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getChangeEmailForm()
    {
        if (null === $this->changeEmailForm) {
            $sm = $this->getServiceLocator();
            $this->setChangeEmailForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\ChangeEmail'));
        }

        return $this->changeEmailForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setChangeEmailForm(FormInterface $form)
    {
        $this->changeEmailForm = $form;
        return $this;
    }

    /**
     * Change user security question
     *
     * @param array|UserInterface $data
     * @return UserInterface|void
     */
    public function changeSecurityQuestion($data)
    {
        /* @var $user UserInterface */
        if (!($user = $this->hydrate($data, $this->getChangeSecurityQuestionForm()))) {
            return;
        }

        $eventManager = $this->getEventManager();
        $eventManager->trigger(__METHOD__, $this, $user);

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

        $eventManager->trigger(__METHOD__ . '.post', $this, $user);

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function getChangeSecurityQuestionForm()
    {
        if (null === $this->changeSecurityQuestionForm) {
            $sm = $this->getServiceLocator();
            $this->setChangeSecurityQuestionForm($sm->getServiceLocator()
                ->get($this->formElementManager)->get('CmsUser\\Form\\ChangeSecurityQuestion'));
        }

        return $this->changeSecurityQuestionForm;
    }

    /**
     * @param FormInterface $form
     * @return self
     */
    public function setChangeSecurityQuestionForm(FormInterface $form)
    {
        $this->changeSecurityQuestionForm = $form;
        return $this;
    }

    /**
     * @return PasswordGeneratorInterface
     */
    public function getPasswordGenerator()
    {
        return $this->passwordGenerator;
    }

    /**
     * @param PasswordGeneratorInterface $generator
     * @return self
     */
    public function setPasswordGenerator(PasswordGeneratorInterface $generator)
    {
        $this->passwordGenerator = $generator;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function setMapper(MapperInterface $mapper)
    {
        if (!$mapper instanceof UserMapperInterface) {
            throw new \InvalidArgumentException(sprintf(
                'First argument must implement CmsUser\Persistence\UserMapperInterface; %s given',
                is_object($mapper) ? get_class($mapper) : gettype($mapper)
            ));
        }

        return parent::setMapper($mapper);
    }

    /**
     * @return string
     */
    protected function getRegistrationToken()
    {
        return md5(uniqid(mt_rand(), true));
    }
}


<?php

Web2All_Manager_Main::loadClass('Web2All_Table_ObjectList');

/**
 * Web2All Table Paged ObjectList class
 *
 * This class manages a list of Web2All_Table_Object's
 * (or an extension off). It makes use of special hooks exposed
 * in the Object.
 *
 * Usage sample:
 *  $filter=$this->Web2All->Plugin->Web2All_Intra_Service_WebServer($this->serviceDB);
 *  $filter->centralftp='web2all';
 *  $result=$this->Web2All->Plugin->Web2All_Table_PagedObjectList($filter);
 *  $result->setPageSize(30);
 *  $result->setPage(1);
 *  $result->setOrderBy('name ASC');
 *  $result->fetchData();
 *  foreach($result as $object){
 *    $object->debugDump();
 *  }
 *  echo "displaying page ".$result->getPage()." of ".$this->getTotalPages();
 *
 * @author Merijn van den Kroonenberg
 * @copyright (c) Copyright 2008 Web2All BV
 * @since 2008-04-25
 */
class Web2All_Table_PagedObjectList extends Web2All_Table_ObjectList {

  protected $pagesize;

  protected $resultcount;

  protected $orderby;

  protected $additionalextra;

  /**
   * constructor
   *
   * @param Web2All_Manager_Main $web2all
   * @param Web2All_Table_Object $obj
   */
  public function __construct(Web2All_Manager_Main $web2all,$obj) {
    parent::__construct($web2all,$obj);

    $table_countableobject_interface='Web2All_Table_ICountableObject';
    if (!($obj instanceof $table_countableobject_interface)) {
      throw new Exception('Web2All_Table_PagedObjectList::constructor: requires a '.$table_countableobject_interface.' as param');
    }

    $this->setPageSize(20);
    $this->orderby='';
  }

  /**
   * Gets how much results are on each page
   *
   * @return integer
   */
  public function getPageSize()
  {
    return $this->pagesize;
  }

  /**
   * Gets the current page number
   *
   * @return integer
   */
  public function getPage()
  {
    return floor($this->offset/$this->pagesize)+1;
  }

  /**
   * Gets the amount of pages
   *
   * @return integer
   */
  public function getTotalPages()
  {
    return ceil($this->getCount()/$this->pagesize);
  }

  /**
   * Sets how much results should be on each page
   *
   * @param integer $count
   */
  public function setPageSize($count)
  {
    $this->pagesize=$count;
  }

  /**
   * Sets which page to get.
   *
   * Numbering starts at page 1
   *
   * @param integer $number
   */
  public function setPage($number)
  {
    $this->setRange($this->pagesize,($number-1)*($this->pagesize));
  }

  /**
   * get the amount of results which were found
   * (ignoring pagination)
   *
   * @return integer
   */
  public function getCount(){

    if(is_null($this->resultcount)){
      $this->resultcount = $this->search_obj->getObjectQueryCount($this->additionalextra);
    }

    return $this->resultcount;

  }

  /**
   * remove the data from the list
   */
  public function clearList()
  {
    parent::clearList();

    $this->resultcount=null;
  }

  /**
   * Assign extra sql to append to query
   * Do this before calling fetchData()
   *
   * *NOTE* for sorting, use setOrderBy() and not this method
   *
   * @param string $extra
   */
  public function setExtra($extra)
  {
    $this->additionalextra=$extra;
  }

  /**
   * Sort the result
   * Do this before calling fetchData()
   *
   * *NOTE* do not include the string 'ORDER BY' in the param (implicit).
   *
   * @param string $order  order by value.
   */
  public function setOrderBy($order='')
  {
    if(!$order){
      $this->orderby='';
    }else{
      $this->orderby=' ORDER BY '.$order;
    }
  }

  /**
   * fetch all data from the database and store the
   * result in this object.
   *
   * after this method has been called, this object can be
   * treated as an array of Web2All_Table_IListableObject's
   *
   */
  public function fetchData()
  {
    $this->extra=$this->additionalextra.$this->orderby;
    parent::fetchData();
  }

}

?>


<?php

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

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

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\Js\Js;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class JsServiceProvider.
 */
class JsServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['js'] = function ($pimple) {
            $js = new Js($pimple['access_token']);
            $js->setCache($pimple['cache']);

            return $js;
        };
    }
}


<?php

class SDIS62_Db_Type_UUID extends Doctrine\DBAL\Types\Type
{
    const BINARY = 'binary';

    /**
     * {@inheritdoc}
     */
    public function getSqlDeclaration(array $fieldDeclaration, Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        return sprintf('BINARY(%d)', $fieldDeclaration['length']);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::BINARY;
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPhpValue($value, Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        if ($value !== null)
        {
            $value= unpack('H*', $value);
            $hash = array_shift($value);

            $uuid = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) .
                '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
                Zend_Debug::Dump($uuid);
            return $uuid;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        if ($value !== null)
        {
            Zend_Debug::Dump(pack('H*', str_replace('-', '', $value)));
            return pack('H*', str_replace('-', '', $value));
            // return "0x" . str_replace('-', '', $value);
        }
    }
}


<?php

namespace Bridge;

use Bridge\Exception\KeyNotFoundInSetException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Service.
 */
class Service implements RegistryAwareInterface
{
    /**
     * @var array Group collection
     */
    private $groups = array();

    /**
     * @var string Service name
     */
    private $name;

    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * @var Registry
     */
    private $registry;

    /**
     * @param Registry $registry
     */
    public function setRegistry(Registry $registry)
    {
        $this->registry = $registry;
    }

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

    /**
     * @return Registry
     */
    public function getRegistry()
    {
        return $this->registry;
    }

    /**
     * @param EventDispatcherInterface $dispatcher
     */
    public function setEventDispatcher($dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @return EventDispatcherInterface
     */
    public function getEventDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * Adds an event listener.
     *
     * @param string   $name
     * @param callable $listener
     *
     * @return $this
     */
    public function addEventListener($name, $listener)
    {
        $this->dispatcher->addListener($name, $listener);

        return $this;
    }

    /**
     * Adds an event subscriber.
     *
     * @param EventSubscriberInterface $subscriber
     *
     * @return $this
     */
    public function addEventSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->dispatcher->addSubscriber($subscriber);

        return $this;
    }

    /**
     * Adds a group.
     *
     * @param Group $group
     */
    public function addGroup(Group $group)
    {
        $group->setService($this);

        $this->groups[$group->getName()] = $group;
    }

    /**
     * Returns a group in the service based on name.
     *
     * @param string $name Group name
     *
     * @throws KeyNotFoundInSetException
     *
     * @return object Group object, if found.
     */
    public function getGroup($name)
    {
        if (array_key_exists($name, $this->groups)) {
            return $this->groups[$name];
        }

        throw new KeyNotFoundInSetException($name, array_keys($this->groups), 'groups');
    }

    /**
     * Returns groups.
     *
     * @return Group[]
     */
    public function getGroups()
    {
        return $this->groups;
    }

    /**
     * Returns service name.
     *
     * @return string Service name
     */
    public function getName()
    {
        return $this->name;
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Action;

use ItePHP\Core\Response;
use ItePHP\Core\ExecuteActionEvent;
use ItePHP\Core\Request;
use Pactum\ConfigContainer;

/**
 * Event for support authenticate user
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class AuthenticateEvent{

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

    /**
     * AuthenticateEvent constructor.
     * @param ConfigContainer $config
     */
	public function __construct(ConfigContainer $config){
        /**
         * @var ConfigContainer[] $authenticate
         */
		$authenticate=$config->getObject('authenticate');
        $this->maxTime=$authenticate->getValue('max-time');

	}

	/**
	 * Detect config authenticate.
	 *
	 * @param ExecuteActionEvent $event
	 */
	public function onExecuteAction(ExecuteActionEvent $event){
		$request=$event->getRequest();
		$authenticate=$request->getConfig()->getObject('authenticate');
		if($authenticate){
			$this->execute($event,$authenticate);
		}
	}

	/**
	 * Check authenticate.
	 *
	 * @param ExecuteActionEvent $event
	 * @param ConfigContainer $config
	 * @throws ValueNotFoundException
	 * @throws PermissionDeniedException
	 */
	private function execute(ExecuteActionEvent $event,$config){
		$request=$event->getRequest();
		$session=$request->getSession();

		try{
			$session->get('authenticate.user_id');
			if($this->maxTime>0){

				if($session->get('authenticate.epoch')<time()){ //deprecated session
					$session->clear();
					throw new ValueNotFoundException('authenticate.epoch');
				}
				$session->set('authenticate.epoch',time()+$this->maxTime);
			}

			if($config->getValue('auth-redirect')!==false){
				$response=$this->createResponseRedirect($config->getValue('auth-redirect'),$request);
				$event->setResponse($response);

			}
		}
		catch(ValueNotFoundException $e){
			if($config->getValue('unauth-redirect')!==false){
				$response=$this->createResponseRedirect($config->getValue('unauth-redirect'),$request);
				$event->setResponse($response);
			}
			else if($config->getValue('auth-redirect')!==false){
				//ignore
			}
			else{
				throw new PermissionDeniedException();
			}
		}

	}

	/**
	 * Check authenticate.
	 *
	 * @param string $redirect
	 * @param Request $request
	 * @return Response
	 */
	private function createResponseRedirect($redirect,Request $request){
		$response=new Response();
		if($request->isAjax()){
			$response->setStatusCode(401);
			$response->setHeader('X-Location',$redirect);
		}
		else{
			$response->redirect($redirect);
		}
		return $response;
	}

}


<?php
namespace Ecompassaro\Pagamento;

use Ecompassaro\Autenticacao\Manager as AutenticacaoManager;

class Manager
{
    private $repository;
    private $autenticacaoManager;

    public function __construct(Repository $repository, AutenticacaoManager $autenticacaoManager)
    {
        $this->repository = $repository;
        $this->autenticacaoManager = $autenticacaoManager;
    }

    /**
     * Obtem o Repository dessa entidade
     * @return PagamentoRepository
     */
    private function getRepository()
    {
        return $this->repository;
    }

    /**
     * Salva o pagamento passado por parâmetro
     * @param Pagamento $pagamento
     */
    public function salvar(Pagamento $pagamento)
    {
        return $this->getRepository()->save($pagamento);
    }

    /**
     * Obtem todas os pagamentos registrados
     */
    public function obterTodosPagamentos()
    {
        return $this->preencherLista($this->getRepository()->findAll());
    }

    /**
     * Gera um lista completa de pagamentos
     * @param array $pagamentos
     * @return array
     */
    private function preencherLista($pagamentos)
    {
        $resultado = array();
        foreach ($pagamentos as $pagamento) {
            $resultado[] = $pagamento->setAutenticacao($this->getAutenticacaoManager()->obterAutenticacaoBasica($pagamento->getAutenticacaoId()));
        }

        return $resultado;
    }

    /**
     * @return \Autenticacao\AutenticacaoManager
     */
    private function getAutenticacaoManager()
    {
        return $this->autenticacaoManager;
    }

    public function obterValorTotalPagamentos()
    {
        return $this->getRepository()->sumValor()['sum'];
    }
}


<?php

namespace Wookieb\Map;
use Wookieb\TypeCheck\TypeCheckInterface;

/**
 * Accepts only strict maps that have same key and value type checks
 *
 * @author Łukasz Kużyński "wookieb" <lukasz.kuzynski@gmail.com>
 */
class StrictMapTypeCheck implements TypeCheckInterface
{
    private $keyTypeCheck;
    private $valueTypeCheck;

    public function __construct(TypeCheckInterface $keyTypeCheck, TypeCheckInterface $valueTypeCheck)
    {
        $this->keyTypeCheck = $keyTypeCheck;
        $this->valueTypeCheck = $valueTypeCheck;
    }

    /**
     * {@inheritDoc}
     */
    public function isValidType($data)
    {
        return $data instanceof StrictMap &&
        $data->getKeyTypeCheck() == $this->keyTypeCheck &&
        $data->getValueTypeCheck() == $this->valueTypeCheck;
    }

    /**
     * {@inheritDoc}
     */
    public function getTypeDescription()
    {
        return vsprintf('strict maps of %s -> %s', array(
            $this->keyTypeCheck->getTypeDescription(),
            $this->valueTypeCheck->getTypeDescription()
        ));
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\Reminder\Command;

use Ruwork\Reminder\Manager\ReminderInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

final class RemindCommand extends Command
{
    use LockableTrait;

    protected static $defaultName = 'ruwork:reminder:remind';

    private $reminder;

    /**
     * {@inheritdoc}
     */
    public function __construct(ReminderInterface $reminder)
    {
        parent::__construct();
        $this->reminder = $reminder;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->addArgument('provider', InputArgument::REQUIRED)
            ->addOption('time', null, InputOption::VALUE_REQUIRED);
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->lock()) {
            $output->writeln('<error>The command is already running in another process.</error>');

            return 0;
        }

        if (null !== $time = $input->getOption('time')) {
            $time = new \DateTimeImmutable($time);
        }

        $this->reminder->remind($input->getArgument('provider'), $time);

        $output->writeln('<info>Done.</info>');

        $this->release();

        return 0;
    }
}