<?php

namespace Bavix\Router;

use Bavix\Exceptions;
use Bavix\Exceptions\Runtime;
use Bavix\Router\Rules\PatternRule;
use Bavix\Router\Rules\PrefixRule;

class Loader
{

    /**
     * @var array
     */
    protected $rules = [
        'http' => Rules\HttpRule::class,
        'prefix' => Rules\PrefixRule::class,
        'pattern' => Rules\PatternRule::class,
    ];

    /**
     * @var null|Rule
     */
    protected $parent;

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

    /**
     * Loader constructor.
     *
     * @param iterable $config
     * @param null|Rule $parent
     */
    public function __construct($config, ?Rule $parent = null)
    {
        $this->config = $config;
        $this->parent = $parent;
    }

    /**
     * @return PatternRule[]
     */
    public function simplify(): array
    {
        $routes = [];
        foreach ($this->routes() as $key => $route) {
            $routes[] = $this->_simplify($route, $key);
        }

        return \array_merge(...$routes);
    }

    /**
     * @return \Generator
     */
    public function routes(): \Generator
    {
        foreach ($this->config as $key => $item) {
            if (empty($item['type'])) {
                throw new Exceptions\NotFound\Data(
                    \sprintf('The type parameter for key `%s` is not found', $this->way($key))
                );
            }

            yield $key => $this->rule($item['type'], $key, $item);
        }
    }

    /**
     * @param string $key
     *
     * @return string
     */
    protected function way(string $key): string
    {
        if ($this->parent) {
            return $this->parent->getName() . '.' . $key;
        }
        return $key;
    }

    /**
     * @param string $type
     * @param string $key
     * @param array $item
     *
     * @return Rule
     */
    public function rule(string $type, string $key, array $item): Rule
    {
        if (!$this->validate($type)) {
            throw new Runtime(\sprintf('Undefined type `%s`', $type));
        }

        $class = $this->rules[$type];
        return new $class($key, $item, $this->parent);
    }

    /**
     * @param string $type
     *
     * @return bool
     */
    protected function validate(string $type): bool
    {
        return \array_key_exists($type, $this->rules);
    }

    /**
     * @param Rule $rule
     * @param string $key
     *
     * @return PatternRule[]
     */
    protected function _simplify(Rule $rule, string $key): array
    {
        if ($rule instanceof PatternRule) {
            return [$key => $rule];
        }

        /**
         * @var PrefixRule $rule
         */
        $rules = [];
        foreach ($rule->resolver() as $index => $item) {
            $location = $key . '.' . $index;
            $rules[] = $this->_simplify($item, $location);
        }

        return \array_merge(...$rules);
    }

}


<?php

/**
 * Contao Open Source CMS, Copyright (C) 2005-2015 Leo Feyer
 *
 * Module Download Statistics, Helperclass
 *
 *
 * PHP version 5
 * @copyright  Glen Langer 2011..2015 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    GLDLStats
 * @license    LGPL
 * @filesource
 * @see	       https://github.com/BugBuster1701/dlstats
 */

/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace BugBuster\DLStats;

/**
 * Class DlstatsHelper
 *
 * @copyright  Glen Langer 2011..2015 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    GLDLStats
 * @license    LGPL
 */
class DlstatsHelper extends \Controller
{

	/**
	 * The IP address
	 * @var string
	 */
	protected $IP = false;

	/**
	 * The IP version
	 * @var string
	 */
	protected $IP_Version = '';

	/**
	 * The IP filter status
	 * @var boolean
	 */
	protected $IP_Filter = false;

	/**
	 * The BE filter status
	 * @var boolean
	 */
	protected $BE_Filter = false;

	/**
	 * The BOT filter status
	 * @var boolean
	 */
	protected $BOT_Filter = false;

	/**
	 * Status, download logging yes or no
	 * @var boolen
	 */
	protected $DL_LOG = true;

	/**
	 * Browser language
	 * @var string
	 */
	protected $_lang  = null;

	/**
	 * Initialize the object
	 */
	public function __construct()
	{
		parent::__construct();
		$this->checkIP();
		$this->checkBE();
		$this->checkBot();
		$this->setDlLog();
		$this->dlstatsSetLang();
	}

	/**
	 * Set DL_LOG, true: logging OK (default), false not OK
	 *
	 * @return void
	 * @access protected
	 */
	public function setDlLog()
	{
		if ($this->IP_Filter === true || $this->BE_Filter === true || $this->BOT_Filter === true)
		{
			$this->DL_LOG = false;
		}

	}

	/**
	 * IP Check
	 * Set IP, detect the IP version and calls the method CheckIPv4 respectively CheckIPv6.
	 *
	 * @param string   User IP, optional for tests
	 * @return boolean true when bot found over IP
	 * @access protected
	 */
	public function checkIP($UserIP = false)
	{
	    // Check if IP present
	    if ($UserIP === false)
	    {
	        $tempIP = $this->dlstatsGetUserIP();
	        if ($tempIP !== false)
	        {
	            $this->IP = $tempIP;
	        }
	        else
	        {
	            return false; // No IP, no search.
	        }
	    }
	    else
	    {
	        $this->IP = $UserIP;
	    }
	    // IPv4 or IPv6 ?
	    switch ($this->checkIPVersion($this->IP))
	    {
	    	case "IPv4":
	    	    if ($this->checkIPv4($this->IP) === true)
	    	    {
	    	        $this->IP_Filter = true;
	    	        return $this->IP_Filter;
	    	    }
	    	    break;
	    	case "IPv6":
	    	    if ($this->checkIPv6($this->IP) === true)
	    	    {
	    	        $this->IP_Filter = true;
	    	        return $this->IP_Filter;
	    	    }
	    	    break;
	    	default:
	    	    $this->IP_Filter = false;
	    	    return $this->IP_Filter;
	    	    break;
	    }
	    $this->IP_Filter = false;
	    return $this->IP_Filter;
	}

	/**
	 * BE Login Check
	 * basiert auf Frontend.getLoginStatus
	 *
	 * @return boolean
	 * @access protected
	 */
	public function checkBE()
	{
	    $strCookie = 'BE_USER_AUTH';
	    $hash = sha1(session_id() . (!$GLOBALS['TL_CONFIG']['disableIpCheck'] ? \Environment::get('ip') : '') . $strCookie);
	    if (\Input::cookie($strCookie) == $hash)
	    {
	        $objSession = \Database::getInstance()
                	        ->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")
                	        ->limit(1)
                	        ->execute($hash, $strCookie);
	        if ($objSession->numRows &&
	            $objSession->sessionID == session_id() &&
	            //$objSession->ip == $this->Environment->ip &&
	            ($GLOBALS['TL_CONFIG']['disableIpCheck'] || $objSession->ip == \Environment::get('ip')) &&
	            ($objSession->tstamp + $GLOBALS['TL_CONFIG']['sessionTimeout']) > time())
	        {
	            $this->BE_Filter = true;
	            return $this->BE_Filter;
	        }
	    }
	    $this->BE_Filter = false;
	    return $this->BE_Filter;
	}

	/**
	 * Bot Check
	 *
	 * @return mixed    true or string if Bot found, false if not
	 * @access protected
	 */
	public function checkBot()
	{
	    if (!in_array('botdetection', \Config::getInstance()->getActiveModules() ))
	    {
	        //botdetection Modul fehlt, trotzdem zählen, Meldung kommt bereits per Hook
	        return false; //fake: no bots found
	    }
	    if ( isset($GLOBALS['TL_CONFIG']['dlstatDisableBotdetection']) &&
            (bool) $GLOBALS['TL_CONFIG']['dlstatDisableBotdetection'] === true )
	    {
	        //botdetection ist disabled for dlstats
	        return false; //fake: no bots founds
	    }
	    // Import Helperclass ModuleBotDetection
	    $this->ModuleBotDetection = new \BotDetection\ModuleBotDetection();

	    //Call BD_CheckBotAgent
	    $test01 = $this->ModuleBotDetection->BD_CheckBotAgent();
	    if ($test01 === true)
	    {
	        $this->BOT_Filter = true;
	        return $this->BOT_Filter;
	    }
	    //Call BD_CheckBotIP
	    $test02 = $this->ModuleBotDetection->BD_CheckBotIP();
	    if ($test02 === true)
	    {
	        $this->BOT_Filter = true;
	        return $this->BOT_Filter;
	    }
	    //Call BD_CheckBotAgentAdvanced
	    $test03 = $this->ModuleBotDetection->BD_CheckBotAgentAdvanced();
	    if ($test03 !== false)
	    {
	        $this->BOT_Filter = true;
	        return $test03; // Bot Name
	    }
	    // No Bots found
	    return false;
	}

	/**
	 * Set _lang over Environment::get('httpAcceptLanguage')
	 *
	 * @return boolean     true
	 */
	public function dlstatsSetLang()
	{
	    $array = \Environment::get('httpAcceptLanguage');

	    $this->_lang = str_replace('-', '_', $array[0]);

	    if(empty($this->_lang) || strlen($this->_lang) < 2)
	    {
	        $this->_lang = 'unknown';
	    }
	    return true;
	}

	/**
	 * Get _lang
	 *
	 * @return string
	 */
	public function dlstatsGetLang() { return $this->_lang; }

	/**
	 * Get IP_Version
	 *
	 * @return string
	 */
	public function dlstatsGetIpVersion() { return $this->IP_Version; }

	/**
	 * Get IP
	 *
	 * @return string
	 */
	public function dlstatsGetIp() { return $this->IP; }

	public function checkMultipleDownload($fileName)
	{
	    return $this->getBlockingStatus($this->IP, $fileName);
	}

	//////////////////////// protected functions \\\\\\\\\\\\\\\\\\\\\\\\

	/**
	 * IP =  IPv4 or IPv6 ?
	 *
	 * @param string $ip	IP Address (IPv4 or IPv6)
	 * @return mixed		false: no valid IPv4 and no valid IPv6
	 * 						"IPv4" : IPv4 Address
	 * 						"IPv6" : IPv6 Address
	 * @access protected
	 */
	protected function checkIPVersion($UserIP = false)
	{
		// Test for IPv4
		if (ip2long($UserIP) !== false)
		{
			$this->IP_Version = "IPv4";
			return $this->IP_Version;
		}

		// Test for IPv6
		if (substr_count($UserIP, ":") < 2)
		{
			$this->IP_Version = false;
			return false;
		}
		// ::1 or 2001::0db8
		if (substr_count($UserIP, "::") > 1)
		{
			$this->IP_Version = false;
			return false; // one allowed
		}
		$groups = explode(':', $UserIP);
		$num_groups = count($groups);
		if (($num_groups > 8) || ($num_groups < 3))
		{
			$this->IP_Version = false;
			return false;
		}
		$empty_groups = 0;
		foreach ($groups as $group)
		{
			$group = trim($group);
			if (! empty($group) && ! (is_numeric($group) && ($group == 0)))
			{
				if (! preg_match('#([a-fA-F0-9]{0,4})#', $group))
				{
					$this->IP_Version = false;
					return false;
				}
			}
			else
			{
				++ $empty_groups;
			}
		}
		if ($empty_groups < $num_groups)
		{
			$this->IP_Version = "IPv6";
			return $this->IP_Version;
		}
		$this->IP_Version = false;
		return false; // no (valid) IP Address
	}

	/**
	 * IP Check for IPv6
	 *
	 * @param string   User IP
	 * @return boolean true when own IP found in localconfig definitions
	 * @access protected
	 */
	protected function checkIPv6($UserIP = false)
	{
		// Check if IP present
		if ($UserIP === false)
		{
			return false; // No IP, no search.
		}
		// search for user bot IP-filter definitions in localconfig.php
		if (isset($GLOBALS['DLSTATS']['BOT_IPV6']))
		{
			foreach ($GLOBALS['DLSTATS']['BOT_IPV6'] as $lineleft)
			{
				$network = explode("/", trim($lineleft));
				if (! isset($network[1]))
				{
					$network[1] = 128;
				}
				if ($this->dlstatsIPv6InNetwork($UserIP, $network[0], $network[1]))
				{
					return true; // IP found
				}
			}
		}
		return false;
	}

	/**
	 * IP Check for IPv4
	 *
	 * @param string   User IP
	 * @return boolean true when own IP found in localconfig definitions
	 * @access protected
	 */
	protected function checkIPv4($UserIP = false)
	{
		// Check if IP present
		if ($UserIP === false)
		{
			return false; // No IP, no search.
		}
		// search for user bot IP-filter definitions in localconfig.php
		if (isset($GLOBALS['DLSTATS']['BOT_IPV4']))
		{
			foreach ($GLOBALS['DLSTATS']['BOT_IPV4'] as $lineleft)
			{
				$network = explode("/", trim($lineleft));
				if (! isset($network[1]))
				{
					$network[1] = 32;
				}
				if ($this->dlstatsIPv4InNetwork($UserIP, $network[0], $network[1]))
				{
					return true; // IP found
				}
			}
		}
		return false;
	}

	/**
	 * Helperfunction, if IPv4 in NET_ADDR/NET_MASK
	 *
	 * @param string $ip		IPv4 Address
	 * @param string $net_addr	Network, optional
	 * @param int    $net_mask	Mask, optional
	 * @return boolean
	 * @access protected
	 */
	protected function dlstatsIPv4InNetwork($ip, $net_addr = 0, $net_mask = 0)
	{
		if ($net_mask <= 0)
		{
			return false;
		}
		if (ip2long($net_addr) === false)
		{
			return false; //no IP
		}
		//php.net/ip2long : jwadhams1 at yahoo dot com
		$ip_binary_string  = sprintf("%032b", ip2long($ip));
		$net_binary_string = sprintf("%032b", ip2long($net_addr));
		return (substr_compare($ip_binary_string, $net_binary_string, 0, $net_mask) === 0);
	}

	/**
	 * Helperfunction, Replace '::' with appropriate number of ':0'
	 *
	 * @param string $Ip	IP Address
	 * @return string		IP Address expanded
	 * @access protected
	 */
	protected function dlstatsIPv6ExpandNotation($Ip)
	{
		if (strpos($Ip, '::') !== false)
			$Ip = str_replace('::', str_repeat(':0', 8 - substr_count($Ip, ':')) . ':', $Ip);
		if (strpos($Ip, ':') === 0)
			$Ip = '0' . $Ip;
		return $Ip;
	}

	/**
	 * Helperfunction, Convert IPv6 address to an integer
	 *
	 * Optionally split in to two parts.
	 *
	 * @see http://stackoverflow.com/questions/420680/
	 * @param string $Ip			IP Address
	 * @param int $DatabaseParts	1 = one part, 2 = two parts (array)
	 * @return mixed				string      / array
	 * @access protected
	 */
	protected function dlstatsIPv6ToLong($Ip, $DatabaseParts = 1)
	{
		$Ip = $this->dlstatsIPv6ExpandNotation($Ip);
		$Parts = explode(':', $Ip);
		$Ip = array('', '');
		for ($i = 0; $i < 4; $i++)
			$Ip[0] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);
		for ($i = 4; $i < 8; $i++)
			$Ip[1] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);

		if ($DatabaseParts == 2)
			return array(base_convert($Ip[0], 2, 10), base_convert($Ip[1], 2, 10));
		else
			return base_convert($Ip[0], 2, 10) + base_convert($Ip[1], 2, 10);
	}

	/**
	 * Helperfunction, if IPv6 in NET_ADDR/PREFIX
	 *
	 * @param string $UserIP        IP Address
	 * @param string $net_addr      NET_ADDR
	 * @param integer $net_mask     PREFIX
	 * @return boolean
	 * @access protected
	 */
	protected function dlstatsIPv6InNetwork($UserIP, $net_addr = 0, $net_mask = 0)
	{
		if ($net_mask <= 0)
		{
			return false;
		}
		// UserIP to bin
		$UserIP = $this->dlstatsIPv6ExpandNotation($UserIP);
		$Parts = explode(':', $UserIP);
		$Ip = array('', '');
		for ($i = 0; $i < 8; $i++)
			$Ip[0] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);

		// NetAddr to bin
		$net_addr = $this->dlstatsIPv6ExpandNotation($net_addr);
		$Parts = explode(':', $net_addr);
		for ($i = 0; $i < 8; $i++)
			$Ip[1] .= str_pad(base_convert($Parts[$i], 16, 2), 16, 0, STR_PAD_LEFT);

		// compare the IPs
		return (substr_compare($Ip[0], $Ip[1], 0, $net_mask) === 0);
	}

	/**
	 * dlstatsAnonymizeIP - Anonymize the last byte(s) of visitors IP addresses, if enabled
	 *
	 * @return mixed     string = IP Address anonymized, false for "no IP"
	 * @access protected
	 */
	protected function dlstatsAnonymizeIP()
	{
		if ($this->IP_Version === false)
		{
			return '0.0.0.0';
		}
		if (isset($GLOBALS['TL_CONFIG']['privacyAnonymizeIp']) &&
           (bool) $GLOBALS['TL_CONFIG']['privacyAnonymizeIp'] === false)
		{
			// Anonymize is disabled
			return ($this->IP === false) ? '0.0.0.0' : $this->IP;
		}
		// Anonymization is enabled, set default anonymization power
		if ( !isset($GLOBALS['TL_CONFIG']['dlstatAnonymizeIP4']) )
		{
		    $GLOBALS['TL_CONFIG']['dlstatAnonymizeIP4'] = 1;
		}
		if ( !isset($GLOBALS['TL_CONFIG']['dlstatAnonymizeIP6']) )
		{
		    $GLOBALS['TL_CONFIG']['dlstatAnonymizeIP6'] = 2;
		}
		switch ($this->IP_Version)
		{
			case "IPv4":
				$arrIP = explode('.', $this->IP); // 0..3
				$arrIP[3] = 0;
				if ($GLOBALS['TL_CONFIG']['dlstatAnonymizeIP4'] == 2)
				{
				    $arrIP[2] = 0;
				}
				return implode('.', $arrIP);
				break;
			case "IPv6":
				$arrIP = explode(':', $this->dlstatsIPv6ExpandNotation($this->IP)); // 0..7
                $arrIP[7] = 0;
				$arrIP[6] = 0;
				if ($GLOBALS['TL_CONFIG']['dlstatAnonymizeIP6'] >= 3)
				{
				    $arrIP[5] = 0;
				}
				if ($GLOBALS['TL_CONFIG']['dlstatAnonymizeIP6'] == 4)
				{
				    $arrIP[4] = 0;
				}
				return implode(':', $arrIP);
				break;
			default:
				return '0.0.0.0';
		}
	}

	/**
	 * dlstatsAnonymizeDomain - Anonymize the Domain of visitors, if enabled
	 *
	 * @return string     Domain anonymized, if DNS entry exists
	 * @access protected
	 */
	protected function dlstatsAnonymizeDomain()
	{
		if ($this->IP_Version === false || $this->IP === '0.0.0.0')
		{
			return '';
		}
		if (isset($GLOBALS['TL_CONFIG']['privacyAnonymizeIp']) &&
           (bool) $GLOBALS['TL_CONFIG']['privacyAnonymizeIp'] === false)
		{
			// Anonymize is disabled
			$domain = gethostbyaddr($this->IP);
			return ($domain == $this->IP) ? '' : $domain;
		}
		// Anonymize is enabled
		$domain = gethostbyaddr($this->IP);
		if ($domain != $this->IP) // bei Fehler/keiner Aufloesung kommt IP zurueck
		{
		    $arrURL = explode('.', $domain);
		    $tld  = array_pop($arrURL);
		    $host = array_pop($arrURL);
			return (strlen($host)) ? $host . '.' . $tld : $tld;
		}
		else
		{
			return '';
		}
	}

	/**
	 * Get User IP
	 *
	 * @return string
	 */
	protected function dlstatsGetUserIP()
	{
        $UserIP = \Environment::get('ip');
        if (strpos($UserIP, ',') !== false) //first IP
        {
            $UserIP = trim( substr($UserIP, 0, strpos($UserIP, ',') ) );
        }
        if ( true === $this->dlstatsIsPrivateIP($UserIP) &&
             false === empty($_SERVER['HTTP_X_FORWARDED_FOR'])
	       )
        {
        	//second try
            $HTTPXFF = $_SERVER['HTTP_X_FORWARDED_FOR'];
            $_SERVER['HTTP_X_FORWARDED_FOR'] = '';

            $UserIP = \Environment::get('ip');
            if (strpos($UserIP, ',') !== false) //first IP
            {
                $UserIP = trim( substr($UserIP, 0, strpos($UserIP, ',') ) );
            }
            $_SERVER['HTTP_X_FORWARDED_FOR'] = $HTTPXFF;
        }
        return $UserIP;
	}

	/**
	 * Check if an IP address is from private or reserved ranges.
	 *
	 * @param string $UserIP
	 * @return boolean         true = private/reserved
	 */
	protected function dlstatsIsPrivateIP($UserIP = false)
	{
	    return !filter_var($UserIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
	}

	protected function setBlockingIP($UserIP = false, $filename = false)
	{
	    if ($UserIP === false)
	    {
	        $UserIP = $this->IP;
	    }
	    if ($filename === false)
	    {
	    	$filename = 'no_filename';
	    }
	    $IPHash = bin2hex(sha1($UserIP,true)); // sha1 20 Zeichen, bin2hex 40 zeichen

	    // Insert
	    $arrSet = array
	    (
	        'dlstats_tstamp'   => date('Y-m-d H:i:s'),
	        'dlstats_ip'       => $IPHash,
	        'dlstats_filename' => $filename
	    );
	    \Database::getInstance()
            	    ->prepare("INSERT IGNORE INTO tl_dlstats_blocker %s")
            	    ->set($arrSet)
            	    ->executeUncached();
	}

	protected function getBlockingStatus($UserIP = false, $filename = false)
	{
	    if ($UserIP === false)
	    {
	        $UserIP = $this->IP;
	    }
	    if ($filename === false)
	    {
	        $filename = 'no_filename';
	    }

	    //Delete All Old Blocker Entries (>10s)
	    \Database::getInstance()
            	    ->prepare("DELETE FROM
                                    tl_dlstats_blocker
                                WHERE
                                    CURRENT_TIMESTAMP - INTERVAL ? SECOND > dlstats_tstamp
                                ")
                    ->executeUncached(10);

	    $IPHash = bin2hex(sha1($UserIP,true)); // sha1 20 Zeichen, bin2hex 40 zeichen
	    //Test ob Blocking gesetzt ist
	    $objBlockingIP = \Database::getInstance()
                            ->prepare("SELECT
                                            id
                                        FROM
                                            tl_dlstats_blocker
                                        WHERE
                                            dlstats_ip = ?
                                        AND
                                            dlstats_filename = ?
                                        ")
                            ->executeUncached($IPHash, $filename);
	    if ($objBlockingIP->numRows < 1)
	    {
	        return false;
	    }
	    return true;
	}
}


<?php
/**
 * Windwork
 *
 * 一个用于快速开发高并发Web应用的轻量级PHP框架
 *
 * @copyright Copyright (c) 2008-2017 Windwork Team. (http://www.windwork.org)
 * @license   http://opensource.org/licenses/MIT
 */
namespace wf\crypt\adapter;

/**
 * 基于xxtea加密算法实现
 *
 * 算法作者：
 * - David J. Wheeler
 * - Roger M. Needham
 *
 * 参考源码：
 * Ma Bingyao <mabingyao@gmail.com> (https://github.com/xxtea/xxtea-php)
 *
 * @package     wf.crypt.adapter
 * @author      cm <cmpan@qq.com>
 * @link        http://docs.windwork.org/manual/wf.crypt.html
 * @since       0.1.0
 */
class Xxtea implements \wf\crypt\CryptInterface
{
	/**
	 * (non-PHPdoc)
	 * @see \wf\crypt\CryptInterface::encrypt()
	 */
	public function encrypt($str, $key)
	{
		if ($str == '') {
			return '';
		}

		if (!$key || !is_string($key)) {
		    throw new \wf\crypt\Exception('[wf\\crypt\\Xxtea::encrypt] param 2 ($key) is required.');
		}

		$v = $this->str2long($str, true);
		$k = $this->str2long($key, false);
		if (count($k) < 4) {
			for ($i = count($k); $i < 4; $i++) {
				$k[$i] = 0;
			}
		}
		$n = count($v) - 1;

		$z = $v[$n];
		$y = $v[0];
		$delta = 0x9E3779B9;
		$q = floor(6 + 52 / ($n + 1));
		$sum = 0;
		while (0 < $q--) {
			$sum = $this->int32($sum + $delta);
			$e = $sum >> 2 & 3;
			for ($p = 0; $p < $n; $p++) {
				$y = $v[$p + 1];
				$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(
					($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
				$z = $v[$p] = $this->int32($v[$p] + $mx);
			}
			$y = $v[0];
			$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(
				($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
			$z = $v[$n] = $this->int32($v[$n] + $mx);
		}
		return $this->long2str($v, false);
	}
	/**
	 * (non-PHPdoc)
	 * @see \wf\crypt\CryptInterface::decrypt()
	 */
	public function decrypt($str, $key)
	{
		if ($str == '') {
			return '';
		}

		if (!$key || !is_string($key)) {
		    throw new \wf\crypt\Exception('[wf\\crypt\\Xxtea::decrypt] param 2 ($key) is required.');
		}
		$v = $this->str2long($str, false);
		$k = $this->str2long($key, false);
		if (count($k) < 4) {
			for ($i = count($k); $i < 4; $i++) {
				$k[$i] = 0;
			}
		}
		$n = count($v) - 1;

		$z = $v[$n];
		$y = $v[0];
		$delta = 0x9E3779B9;
		$q = floor(6 + 52 / ($n + 1));
		$sum = $this->int32($q * $delta);
		while ($sum != 0) {
			$e = $sum >> 2 & 3;
			for ($p = $n; $p > 0; $p--) {
				$z = $v[$p - 1];
				$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(
					($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
				$y = $v[$p] = $this->int32($v[$p] - $mx);
			}
			$z = $v[$n];
			$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(
				($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
			$y = $v[0] = $this->int32($v[0] - $mx);
			$sum = $this->int32($sum - $delta);
		}
		return $this->long2str($v, true);
	}

	/**
	 * 长整型转换为字符串
	 *
	 * @param long $v
	 * @param boolean $w
	 * @return string
	 */
	private function long2str($v, $w)
	{
		$len = count($v);
		$n = $len << 2;
		if ($w) {
			$m = $v[$len - 1];
			$n -= 4;
			if (($m < $n - 3) || ($m > $n)) {
				return false;
			}
			$n = $m;
		}

		$s = [];
		for ($i = 0; $i < $len; $i++) {
			$s[$i] = pack("V", $v[$i]);
		}

		if ($w) {
			return substr(join('', $s), 0, $n);
		} else {
			return join('', $s);
		}
	}

	/**
	 * 字符串转化为长整型
	 *
	 * @param string $s
	 * @param boolean $w
	 * @return Ambigous <multitype:, number>
	 */
	private function str2long($s, $w)
	{
		$v = unpack("V*", $s . str_repeat("\0", (4 - strlen($s) % 4) & 3));
		$v = array_values($v);

		if ($w) {
			$v[count($v)] = strlen($s);
		}

		return $v;
	}

	/**
	 * @param int $n
	 * @return number
	 */
	private function int32($n)
	{
		return ($n & 0xffffffff);
	}
}


<?php

namespace Bravesheep\DatabaseUrlBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class BravesheepDatabaseUrlExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $resolver = new DatabaseUrlResolver();
        foreach ($config['urls'] as $name => $url) {
            $target = $url['url'];
            $prefix = $url['prefix'];

            $params = $resolver->resolve($target);
            $container->setParameter("{$prefix}driver", $params['driver']);
            $container->setParameter("{$prefix}host", $params['host']);
            $container->setParameter("{$prefix}port", $params['port']);
            $container->setParameter("{$prefix}name", $params['name']);
            $container->setParameter("{$prefix}user", $params['user']);
            $container->setParameter("{$prefix}password", $params['password']);
            $container->setParameter("{$prefix}path", $params['path']);
            $container->setParameter("{$prefix}memory", $params['memory']);
        }
    }
}


<?php

namespace Bavix\Router;

abstract class Rule implements \Serializable, \JsonSerializable
{

    use Attachable;

    public const DEFAULT_REGEX = '[\w-]+';

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

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

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

    /**
     * @var null|Path
     */
    protected $path;

    /**
     * @var null|array
     */
    protected $methods;

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

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

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

    /**
     * Rule constructor.
     *
     * @param string $key
     * @param iterable $storage
     * @param null|self $parent
     */
    public function __construct(string $key, array $storage, ?self $parent = null)
    {
        if ($parent) {
            $this->beforePrepare($parent);
        }
        $this->prepare();
        $this->initializer($key, $storage);
        $this->pathInit();
        if ($parent) {
            $this->afterPrepare($parent);
        }
    }

    /**
     * @param self $parent
     * @return void
     */
    protected function beforePrepare(self $parent): void
    {
        $this->defaultRegex = $this->defaultRegex ?: $parent->defaultRegex;
    }

    /**
     * @return void
     */
    protected function prepare(): void
    {
        $this->_protocol = '\w+';
        $this->_host = '[^\/]+';
    }

    /**
     * if this.path === string then new Path(string, [])
     * else this.path === array then new Path(...this.path)
     */
    protected function pathInit(): void
    {
        [$path, $regExp] = $this->pathExtract();
        $this->path = null;

        if ($path) {
            $this->path = new Path($this->getDefaultRegex(), $path, $regExp);
        }
    }

    /**
     * Returns an array of two elements.
     *
     * The first parameter is path,
     *  the second is an array of regular expressions.
     *
     * @return array
     */
    protected function pathExtract(): array
    {
        $regExp = [];
        $path = $this->path;

        if (\is_array($this->path)) {
            $regExp = \array_pop($this->path);
            $path = \array_pop($this->path);
        }

        return [$path, $regExp];
    }

    /**
     * @return string
     */
    public function getDefaultRegex(): string
    {
        return $this->defaultRegex ?: self::DEFAULT_REGEX;
    }

    /**
     * @param self $parent
     * @return void
     */
    protected function afterPrepare(self $parent): void
    {
        $this->hinge($parent->path);
        $this->_protocol = $parent->protocol ?? $parent->_protocol ?? $this->_protocol;
        $this->_host = $parent->host ?? $parent->_host ?? $this->_host;
        $this->_name = $parent->_name . '.' . $this->_name;
        $this->methods = $this->methods ?? $parent->methods;
        $this->arrayMerge('defaults', $parent);
        $this->arrayMerge('extends', $parent);
    }

    /**
     * @param Path|null $path
     */
    protected function hinge(?Path $path): void
    {
        if ($this->path && $path) {
            $this->path->hinge($path);
            return;
        }

        $this->path = $path ?? $this->path;
    }

    /**
     * @param string $name
     * @param self $parent
     */
    protected function arrayMerge(string $name, self $parent): void
    {
        $this->$name = \array_merge(
            (array)$parent->$name,
            (array)$this->$name
        );
    }

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

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

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

    /**
     * @return Path
     */
    public function getPath(): Path
    {
        return $this->path;
    }

    /**
     * @return null|array
     */
    public function getMethods(): ?array
    {
        return $this->methods;
    }

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

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

    /**
     * @return array
     * @throws \ReflectionException
     */
    public function __sleep(): array
    {
        return \array_keys($this->serializeArray());
    }

    /**
     * @return array
     * @throws \ReflectionException
     */
    protected function serializeArray(): array
    {
        $properties = [];
        $reflation = new \ReflectionClass($this);
        $protected = $reflation->getProperties(\ReflectionProperty::IS_PROTECTED);
        foreach ($protected as $property) {
            $properties[] = $property->name;
        }
        return $properties;
    }

    /**
     * @inheritdoc
     * @throws \ReflectionException
     */
    public function serialize(): string
    {
        $data = [];
        foreach ($this->serializeArray() as $key => $value) {
            $data[$value] = $this->$value;
        }
        return \serialize($data);
    }

    /**
     * @inheritdoc
     */
    public function unserialize($serialized): void
    {
        /**
         * @var string $serialized
         * @var array $data
         */
        $data = \unserialize($serialized, (array)null);
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }

    /**
     * @inheritdoc
     * @throws \ReflectionException
     */
    public function jsonSerialize(): array
    {
        $data = [];
        foreach ($this->serializeArray() as $key => $value) {
            $key = \ltrim($value, '_');
            $data[$key] = $this->$value;
        }
        return $data;
    }

}


<?php
/**
 *
 * User: davidlin
 * Date: 8/11/2013
 * Time: 8:14 AM
 *
 */

namespace Dlin\Zendesk\Result;

class PaginatedResult implements \ArrayAccess, \Countable {

    /**
     * @var \Dlin\Zendesk\Client\BaseClient
     *
     */
    private $client;

    private $endPoint;

    /**
     * @var integer
     */
    private $count;

    /**
     * @var integer
     */
    private $current_page;

    /**
     * @var integer
     */
    private $per_page;

    /**
     * @var array
     */
    private $items;

    /**
     * @return $this
     */
    public function getNextResult(){
        if($this->getCount() > $this->per_page * $this->getCurrentPage()){
            return $this->client->getCollection($this->getEndPoint(), 'tickets', $this->getCurrentPage()+1, $this->getPerPage());
        }
        return null;
    }

    /**
     * Note: the web service never return next page URL, this method overrides the next_page url and resets the current pages param
     * @return $this
     */
    public function getPreviousResult(){
        if($this->getCurrentPage() > 1){
            return $this->client->getCollection($this->getEndPoint(), 'tickets', $this->getCurrentPage()-1, $this->getPerPage());
        }
        return null;
    }

    /**
     * @param \Dlin\Zendesk\Client\BaseClient $client
     */
    public function setClient($client)
    {
        $this->client = $client;
    }

    /**
     * @return \Dlin\Zendesk\Client\BaseClient
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param int $count
     */
    public function setCount($count)
    {
        $this->count = $count;
    }

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

    /**
     * @return mixed
     */
    public function getEndPoint()
    {
        return $this->endPoint;
    }

    /**
     * @param mixed $endPoint
     */
    public function setEndPoint($endPoint)
    {
        $this->endPoint = $endPoint;
    }

    /**
     * @param int $current_page
     */
    public function setCurrentPage($current_page)
    {
        $this->current_page = $current_page;
    }

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

    /**
     * @param int $per_page
     */
    public function setPerPage($per_page)
    {
        $this->per_page = $per_page;
    }

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

    /**
     * @param array $items
     */
    public function setItems(array $items)
    {
        $this->items = $items;
    }

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

//ArrayAccess Interface Implementation bellow
    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->items[] = $value;
        } else {
            $this->items[$offset] = $value;
        }
    }
    public function offsetExists($offset) {
        return isset($this->items[$offset]);
    }
    public function offsetUnset($offset) {
        unset($this->items[$offset]);
    }
    public function offsetGet($offset) {
        return isset($this->items[$offset]) ? $this->items[$offset] : null;
    }

    public function count(){
        return is_array($this->items) ? count($this->items) : 0;
    }

}


<?php
namespace Sil\PhpEnv;

use Exception;
use Sil\PhpEnv\EnvListNotAvailableException;

class Env
{
    /**
     * Throw an exception if we are not able to get the list of environment
     * variables' names.
     *
     * @throws EnvListNotAvailableException
     */
    public static function assertEnvListAvailable()
    {
        if (empty($_ENV)) {
            $variablesOrder = \ini_get('variables_order');
            if (strpos($variablesOrder, 'E') === false) {
                throw new EnvListNotAvailableException(
                    'Cannot get a list of the current environment variables. '
                    . 'Make sure the `variables_order` variable in php.ini '
                    . 'contains the letter "E".',
                    1496164061
                );
            }
        }
    }

    /**
     * Retrieve the value of the specified environment variable, translating
     * values of 'true', 'false', and 'null' (case-insensitive) to their actual
     * non-string values.
     *
     * PHP's built-in "getenv()" function returns a string (or false, if the
     * environment variable is not set). If the value is 'false', then it will
     * be returned as the string "false", which evaluates to true. This function
     * is to check for that kind of string value and return the actual value
     * that it refers to.
     *
     * NOTE:
     * - If no value is available for the specified environment variable and
     *   no default value was provided, this function returns null (rather than
     *   returning false the way getenv() does).
     * - At version 2.0.0, this method was changed to return the given default
     *   value even if the environment variable exists but has no value (or a
     *   value that only contains whitespace).
     *
     * @param string $varname The name of the desired environment variable.
     * @param mixed $default The default value to return if the environment
     *     variable is not set or its value only contains whitespace.
     * @return mixed The resulting value (if set to more than whitespace), or
     *     the given default value (if any, otherwise null).
     */
    public static function get($varname, $default = null)
    {
        $originalValue = \getenv($varname);

        if ($originalValue === false) {
            return $default;
        }

        $trimmedValue = \trim($originalValue);

        if ($trimmedValue === '') {
            return $default;
        }

        $lowercasedTrimmedValue = \strtolower($trimmedValue);

        if ($lowercasedTrimmedValue === 'false') {
            return false;
        } elseif ($lowercasedTrimmedValue === 'true') {
            return true;
        } elseif ($lowercasedTrimmedValue === 'null') {
            return null;
        }

        return $trimmedValue;
    }

    /**
     *
     * @param string $varname
     * @return string
     * @throws EnvVarNotFoundException
     */
    public static function requireEnv($varname)
    {
        $value = self::get($varname);

        if ($value === null) {
            $message = 'Required environment variable: ' . $varname . ', not found.';
            throw new EnvVarNotFoundException($message);
        }

        return $value;
    }

    /**
     *
     * @param string $varname
     * @param array $default
     * @return array
     */
    public static function getArray($varname, array $default = [])
    {
        $value = self::get($varname);

        if ($value === null) {
            return $default;
        }

        return explode(',', $value);
    }

    /**
     * Get an associative array of data, built from environment variables whose
     * names begin with the specified prefix (such as 'MY_DATA_'). If none are
     * found, an empty array will be returned.
     *
     * Note that the prefix will NOT be included in the resulting array's key
     * names. See the tests for details.
     *
     * The values 'true', 'false', and 'null' (case-insensitive) will be
     * converted to their non-string values. See Env::get().
     *
     * @param string $prefix The prefix to look for, in the list of defined
     *     environment variables' names. Must not be empty.
     * @return array
     * @throws EnvListNotAvailableException
     * @throws Exception
     */
    public static function getArrayFromPrefix($prefix)
    {
        self::assertEnvListAvailable();

        if (empty($prefix)) {
            throw new Exception(
                'You must provide a non-empty prefix to search for.',
                1496164608
            );
        }

        $results = [];

        foreach (array_keys($_ENV) as $name) {
            if (self::startsWith($name, $prefix)) {
                $nameAfterPrefix = substr($name, strlen($prefix));
                $results[$nameAfterPrefix] = self::get($name);
            }
        }

        return $results;
    }

    /**
     *
     * @param string $varname
     * @return array
     */
    public static function requireArray($varname)
    {
        self::requireEnv($varname);

        return self::getArray($varname);
    }

    /**
     * See if the given string (the haystack) starts with other given string
     * (the needle).
     *
     * Thanks to MrHus on StackOverflow for this:
     * https://stackoverflow.com/a/834355/3813891
     *
     * @param string $haystack The string to search in.
     * @param string $needle The string to search for.
     * @return bool
     */
    protected static function startsWith($haystack, $needle)
    {
         $length = strlen($needle);
         return (substr($haystack, 0, $length) === $needle);
    }
}


<?php

/**
 * Contao Open Source CMS, Copyright (C) 2005-2015 Leo Feyer
 *
 * Modul Download Statistics
 *
 * Log file downloads done by the content elements Download and Downloads,
 * and show statistics in the backend.
 *
 *
 * PHP version 5
 * @copyright  Glen Langer 2011..2015 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @author     Peter Koch (acenes) 2007-2009
 * @package    GLDLStats
 * @license    LGPL
 * @filesource
 * @see	       https://github.com/BugBuster1701/dlstats
 */

/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace BugBuster\DLStats;

/**
 * Class Dlstats
 *
 * @copyright  Glen Langer 2011..2015 <http://contao.ninja>
 * @author     Glen Langer (BugBuster)
 * @package    GLDLStats
 * @license    LGPL
 */
class Dlstats extends \DLStats\DlstatsHelper
{

	/**
	 * tl_dlstats.id
	 * @var integer
	 */
	private $_statId = 0;

	/**
	 * File name for logging
	 * @var string
	 */
	private $_filename = '';

	/**
	 * Initialize the object
	 */
	public function __construct()
	{
		parent::__construct(); // DlstatsHelper check methods
	}

	/**
	 * Log the download over $GLOBALS['TL_HOOKS']['postDownload']
	 * @param	string	$fileName	Filename, Hook Parameter
	 * @return void
	 */
	public function logDownload($fileName)
	{
		$this->_filename = $fileName;

		if (isset($GLOBALS['TL_CONFIG']['dlstats']) &&
           (bool) $GLOBALS['TL_CONFIG']['dlstats'] === true)
		{
			if (true  === $this->DL_LOG &&
			    false === $this->checkMultipleDownload($fileName)
               )
			{
				$this->logDLStats();
				$this->logDLStatDetails();
			}
		}
	}

	/**
	 * Helper function log file name
	 * @return void
	 */
	protected function logDLStats()
	{
		$q = \Database::getInstance()->prepare("SELECT id FROM `tl_dlstats` WHERE `filename`=?")
                                     ->execute($this->_filename);
		if ($q->next())
		{
			$this->_statId = $q->id;
			\Database::getInstance()->prepare("UPDATE `tl_dlstats` SET `tstamp`=?, `downloads`=`downloads`+1 WHERE `id`=?")
                                    ->execute(time(), $this->_statId);
		}
		else
		{
			$q = \Database::getInstance()->prepare("INSERT IGNORE INTO `tl_dlstats` %s")
                                         ->set(array('tstamp' => time(),
                                                     'filename' => $this->_filename,
                                                     'downloads' => 1)
                                              )
                                         ->execute();
			$this->_statId = $q->insertId;
		} // if
		$this->setBlockingIP($this->IP, $this->_filename);
	}

	/**
	 * Helper function log details
	 * @return void
	 */
	protected function logDLStatDetails()
	{
	    //Host / Page ID ermitteln
	    $pageId = $GLOBALS['objPage']->id; // ID der grad aufgerufenden Seite.
	    $pageHost = \Environment::get('host'); // Host der grad aufgerufenden Seite.

	    if (isset($GLOBALS['TL_CONFIG']['dlstatdets'])
	           && (bool) $GLOBALS['TL_CONFIG']['dlstatdets'] === true
	       )
	    {
	        //Maximum details for year & month statistic
            $username = '';
    		$strCookie = 'FE_USER_AUTH';

    		$hash = sha1(session_id() . (!$GLOBALS['TL_CONFIG']['disableIpCheck'] ? $this->IP : '') . $strCookie);
    		if (\Input::cookie($strCookie) == $hash)
    		{
    			$qs = \Database::getInstance()->prepare("SELECT pid, tstamp, sessionID, ip
                                                         FROM `tl_session` WHERE `hash`=? AND `name`=?")
                                              ->execute($hash, $strCookie);
    			if ($qs->next() &&
    				$qs->sessionID == session_id() &&
    				($GLOBALS['TL_CONFIG']['disableIpCheck'] || $qs->ip == $this->IP) &&
    				($qs->tstamp + $GLOBALS['TL_CONFIG']['sessionTimeout']) > time())
    			{
    				$qm = \Database::getInstance()->prepare("SELECT `username`
                                                             FROM `tl_member` WHERE id=?")
                                                  ->execute($qs->pid);
    				if ($qm->next())
    				{
    					$username = $qm->username;
    				}
    			} // if
    		} // if

    		\Database::getInstance()->prepare("INSERT INTO `tl_dlstatdets` %s")
            						->set(array('tstamp'    => time(),
            						            'pid'       => $this->_statId,
            						            'ip'        => $this->dlstatsAnonymizeIP(),
            						            'domain'    => $this->dlstatsAnonymizeDomain(),
            						            'username'  => $username,
            						            'page_host' => $pageHost,
            						            'page_id'   => $pageId,
            						            'browser_lang' => $this->dlstatsGetLang()
            						            )
            						        )
                                    ->execute();
	    }
	    else
	    {
	        //Minimum details for year & month statistic
	        \Database::getInstance()->prepare("INSERT INTO `tl_dlstatdets` %s")
                                    ->set(array('tstamp'    => time(),
                                                'pid'       => $this->_statId
                                               )
                                         )
                                    ->execute();
	    }
	}

} // class Dlstats


<?php

/*
 * This file is part of gpupo/search
 *
 * (c) Gilmar Pupo <contact@gpupo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gpupo\Search;

use Gpupo\Search\Result\CountableCollection;

/**
 * Comunicacao com o SphinxClient.
 */
abstract class SearchAbstract
{
    /**
     * Facade para Single query, obtendo apenas os resultados (matches).
     *
     * @param string $index
     */
    public function search($index, array $filters = null,
        array $queries = null, array $fieldWeights = null,
        $limit = 20, $offset = 0
    ) {
        $result = $this->query($index, $filters, $queries,
            $fieldWeights, $limit, $offset);

        if (!isset($result['matches'])) {
            return [];
        }

        return $result['matches'];
    }

    /**
     * Executa Queries.
     *
     * @see \Gpupo\Search\Query\FiltersAbstract::toArray()          Filter Array Sintaxe
     * @see \Gpupo\Search\Query\QueryAbstract::getQueries()         Query Array Sintaxe
     * @see \Gpupo\Search\Query\QueryAbstract::getFieldWeights()    Query Array Sintaxe
     *
     * @param array $filter       Search filter
     * @param array $queries      Search query
     * @param array $fieldWeights Field weights array
     * @param int   $limit
     * @param int   $offset
     *
     * @return array Results
     */
    public function query($index, array $filters = null,
        array $queries = null, array $fieldWeights = null,
        $limit = 20, $offset = 0
    ) {
        $sphinxClient = $this->getSphinxClient();
        $sphinxClient->SetLimits($offset, $limit);
        if (null !== $filters) {
            foreach ($filters as $filter) {
                if (!isset($filter['key'])) {
                    // Filtro existe mas sem key
                }
                if (
                    array_key_exists('min', $filter) &&
                    array_key_exists('max', $filter)
                ) {
                    $sphinxClient->SetFilterRange(
                                  $filter['key'],
                        (integer) $filter['min'],
                        (integer) $filter['max']
                    );
                } else {
                    if (!isset($filter['values']) || !is_array($filter['values'])) {
                        //Filtro existe mas sem valor;
                    }
                    $sphinxClient->SetFilter(
                        $filter['key'],
                        $filter['values']
                    );
                }
            }
        }
        if (null !== $queries) {
            foreach ($queries as $key => $queryInfo) {
                $query = $this->implodeQueryValues($queryInfo);

                if (array_key_exists('countableAttributes', $queryInfo)) {
                    $array = $queryInfo['countableAttributes'];
                    if (!is_array($array)) {
                        $array = [$array];
                    }

                    $sphinxClient->addFacetedQuery($query, $index, $array);
                } else {
                    $sphinxClient->AddQuery($query, $index);
                }
            }
        }

        if (null !== $fieldWeights) {
            $sphinxClient->SetFieldWeights($fieldWeights);
        }

        $result = $this->getResult($sphinxClient);

        return $result;
    }

    /**
     * RunQueries() + validate.
     *
     * - Single Query: Resultados da Query
     *
     * - Multi Query:  Array de Resultados das Querys
     *
     * Formato de cada Resultado:
     *
     * <code>
     * //Results
     * array(
     *     array(
     *         'id'     => 12345,
     *         'weight' => 30,
     *         'attrs'  => array(...)
     *     ),
     *     array(
     *         'id'     => 23456,
     *         'weight' => 20,
     *         'attrs'  => array(...)
     *     ),
     *     ...
     * );
     * </code>
     *
     * @param \SphinxClient $sphinxClient
     *
     * @throws \Exception
     *
     * @return array
     */
    protected function getResult(\SphinxClient $sphinxClient)
    {
        $result = $sphinxClient->RunQueries();

        if (false === $result) {
            throw new \Exception(
                $sphinxClient->getLastError()
            );
        }
        if ($sphinxClient->GetLastWarning()) {
            throw new \Exception(
                $sphinxClient->GetLastWarning()
            );
        }

        if (false === $result) {
            throw new \Exception(
                $sphinxClient->getLastError()
            );
        }
        if ($sphinxClient->GetLastWarning()) {
            throw new \Exception(
                $sphinxClient->GetLastWarning()
            );
        }

        //Suporte ao formato inicial de unica query
        if (count($result) === 1) {
            return current($result);
        }

        return $result;
    }

    /**
     * Transforma uma query array em uma string usada na
     * query do Client Sphinx Search.
     *
     * @param array $queryInfo
     *
     * @return string
     */
    protected function implodeQueryValues(array $queryInfo)
    {
        $query = "@{$queryInfo['key']} "
            .(
                '*'.implode('* *', $queryInfo['values'])
                .'*'
            ).PHP_EOL;

        return $query;
    }

    /**
     * Facade para query, obtendo resultados em objeto.
     */
    public function getCollection($index, array $filters = null,
        array $queries = null, array $fieldWeights = null,
        $limit = 20, $offset = 0, $countableAttributes = null
    ) {
        $result = $this->query($index, $filters, $queries,
            $fieldWeights, $limit, $offset);

        if (is_array($result)) {
            $i = 0;

            if ($countableAttributes) {
                foreach ($countableAttributes as $attributeName) {
                    $i++;
                    $result[0]['attributes']['countable'][$attributeName] = new CountableCollection($result[$i], $attributeName);
                }
            }

            for ($l = 1; $l <= $i; $l++) {
                unset($result[$l]);
            }

            $collection = $this->factoryCollection($result);

            return $collection;
        }
    }
}


<?php namespace Academe\SerializeParser;

/**
 * The main parser.
 */

class Parser
{
    // Protected and private opbject properties will have prefixes
    // to their names. We will strip those prefixes off by default.

    const PROTECTED_PREFIX = "\0*\0";

    /**
     * Parse a string containing a serialized data structure.
     * This is the initial entry point into the recursive parser.
     * FIXME: work out some way the string reader can be mocked.
     */
    public function parse($string)
    {
        return $this->doParse(new StringReader($string));
    }

    /**
     * This is the recursive parser.
     */
    protected function doParse(StringReader $string)
    {
        $val = null;

        // May be : or ; as a terminator, depending on what the data
        // type is.

        $type = substr($string->read(2), 0, 1);

        switch ($type) {
            case 'a':
                // Associative array: a:length:{[index][value]...}
                $count = (int)$string->readUntil(':');

                // Eat the opening "{" of the array.
                $string->read(1);

                $val= [];
                for($i=0; $i < $count; $i++) {
                    $array_key = $this->doParse($string);
                    $array_value = $this->doParse($string);

                    $val[$array_key] = $array_value;
                }

                // Eat "}" terminating the array.
                $string->read(1);

                break;

            case 'O':
                // Object: O:length:"class":length:{[property][value]...}
                $len = (int)$string->readUntil(':');

                // +2 for quotes
                $class = $string->read(2 + $len);

                // Eat the separator
                $string->read(1);

                // Do the properties.
                // Initialise with the original name of the class.
                $properties = ['__class_name' => $class];

                // Read the number of properties.
                $len = (int)$string->readUntil(':');

                // Eat "{" holding the properties.
                $string->read(1);

                for($i=0; $i < $len; $i++) {
                    $prop_key = $this->doParse($string);
                    $prop_value = $this->doParse($string);

                    // Strip the protected and private prefixes from the names.
                    // Maybe replace them with something more informative, such as "protected:" and "private:"?

                    if (substr($prop_key, 0, strlen(self::PROTECTED_PREFIX)) == self::PROTECTED_PREFIX) {
                        $prop_key = substr($prop_key, strlen(self::PROTECTED_PREFIX));
                    }

                    if (substr($prop_key, 0, 1) == "\0") {
                        list(, $private_class, $private_property_name) = explode("\0", $prop_key);

                        $prop_key = $private_property_name;
                    }

                    $properties[$prop_key] = $prop_value;
                }

                // Eat "}" terminating properties.
                $string->read(1);

                $val = (object)$properties;

                break;

            case 's':
                $len = (int)$string->readUntil(':');
                $val = $string->read($len + 2);

                // Eat the separator
                $string->read(1);
                break;

            case 'i':
                $val = (int)$string->readUntil(';');
                break;

            case 'd':
                $val = (float)$string->readUntil(';');
                break;

            case 'b':
                // Boolean is 0 or 1
                $bool = $string->read(2);
                $val = substr($bool, 0, 1) == '1';
                break;

            case 'N':
                $val = null;
                break;

            default:
                throw new \Exception(sprintf('Unable to unserialize type "%s"', $type));
        }

        return $val;
    }
}


<?php

namespace Omnipay\Klarna\Traits;

/**
 * Trait AbstractGatewayDefaultParametersGettersAndSettersTrait
 *
 * @package Omnipay\Klarna
 */
trait AbstractGatewayDefaultParametersGettersAndSettersTrait
{
    /**
     * @return string|int
     */
    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }

    /**
     * @param string|int $value
     * @return $this
     */
    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }

    /**
     * @return string
     */
    public function getSharedSecret()
    {
        return $this->getParameter('sharedSecret');
    }

    /**
     * @param string $value
     * @return $this
     */
    public function setSharedSecret($value)
    {
        return $this->setParameter('sharedSecret', $value);
    }

    /**
     * @return int|string
     */
    public function getLanguage()
    {
        return $this->getParameter('language');
    }

    /**
     * @param int|string $value
     * @return $this
     */
    public function setLanguage($value)
    {
        return $this->setParameter('language', $value);
    }

    /**
     * Get country of merchant
     * @return int|string
     */
    public function getCountry()
    {
        return $this->getParameter('country');
    }

    /**
     * Set country of merchant
     * @param int|string $value
     * @return $this
     */
    public function setCountry($value)
    {
        return $this->setParameter('country', $value);
    }

    /**
     * Sets Language, Country, and  Currency (if available)
     * @param string $value
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function setLocale($value)
    {
        $normalized = strtr($value, ['_' => '-']);
        $parts = explode('-', $normalized);
        if (empty($parts[1])) {
            throw new \InvalidArgumentException('Locale should be in the format language-country');
        }
        $language = strtolower($parts[0]);
        $country = strtoupper($parts[1]);
        $this->setLanguage($language);
        $this->setCountry($country);
        $this->setDefaultCurrency($country);
        return $this;
    }

    /**
     * Sets default currency for country according to current (May 2015) situation
     *
     * @param string $country
     * @return $this
     */
    private function setDefaultCurrency($country)
    {
        switch ($country) {
            case 'DK':
                return $this->setCurrency('DKK');
            case 'NO':
                return $this->setCurrency('NOK');
            case 'SE':
                return $this->setCurrency('SEK');
            case 'AT':
            case 'BE':
            case 'CY':
            case 'DE':
            case 'EE':
            case 'ES':
            case 'FI':
            case 'FR':
            case 'GR':
            case 'IE':
            case 'IT':
            case 'LT':
            case 'LU':
            case 'LV':
            case 'MT':
            case 'NL':
            case 'PT':
            case 'SI':
            case 'SK':
                return $this->setCurrency('EUR');
            default:
        }
        return $this->setCurrency('');
    }
}


<?php

/*
 * This file is part of gpupo/search
 *
 * (c) Gilmar Pupo <contact@gpupo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gpupo\Search\Query;

use Gpupo\Common\Entity\CollectionAbstract;
use Gpupo\Search\Paginator\PaginableInterface;
use Gpupo\Search\Paginator\PaginatorInterface;

abstract class QueryAbstract extends CollectionAbstract implements PaginableInterface
{
    public function set($key, $value)
    {
        parent::set($key, $value);

        return $this;
    }

    /**
     * @param \Gpupo\Search\Query\KeywordsInterface $keywords
     */
    public function __construct(KeywordsInterface $keywords = null)
    {
        $data = [
            'index'                 => null,
            'filters'               => null,
            'keywords'              => ['primary' => $keywords],
            'fieldWeights'          => [],
            'limit'                 => 20,
            'offset'                => null,
            'countableAttributes'   => [],
        ];

        parent::__construct($data);
    }

    /**
     * Objeto de pesquisa.
     *
     * @param \Gpupo\Search\Query\KeywordsInterface $keyword
     *
     * @return type
     */
    public function setKeyword(KeywordsInterface $keyword)
    {
        return $this->set('keywords', ['primary' => $keyword]);
    }

    public function setKeywords(array $keywordsList)
    {
        foreach ($keywordsList as $keywords) {
            if (!$keywords instanceof KeywordsInterface) {
                throw new \InvalidArgumentException('Cada item de $keywordsList deve implementar KeywordsInterface');
            }
        }

        return $this->set('keywords', $keywordsList);
    }

    /**
     * Acesso a um conjunto de KeywordsInterface.
     *
     * @todo Evoluir o uso da busca facetada para mais de uma Keyword
     */
    public function getKeywords()
    {
        $keywords =  $this->get('keywords');

        return $keywords;
    }

    public function getFilters()
    {
        if ($this->get('filters') instanceof FiltersInterface) {
            return $this->get('filters')->toArray();
        }

        return;
    }

    /**
     * SphinxSearch Queries Array.
     *
     *
     *
     * //Search single query sintaxe:
     * array(
     *     array(
     *         'key'    => 'search_key',     // The key to search on
     *         'values' => array(            // The values to match with
     *             'value_one',
     *             'value_two',
     *         ),
     *     )
     * );
     *
     * //Search Multi query sintaxe:
     * array(
     *     array(
     *         'key'    => 'search_key',     // The key to search on
     *         'values' => array(            // The values to match with
     *             'value_one',
     *             'value_two',
     *         ),
     *     ),
     *     array(
     *         'key'    => 'another_key',    // The key to search on
     *         'values' => array(            // The values to match with
     *             'some_value',
     *         ),
     *         countableAttributes => array(),  // For Faceted search
     *     ),
     *     ...
     * );
     *
     *
     */
    public function getQueries()
    {
        $array = [];
        foreach ($this->getKeywords() as $keyword) {
            $value = $keyword->getData();
            if ($this->getCountableAttributes()) {
                $value['countableAttributes'] = $this->getCountableAttributes();
            }
            $array[] = $value;
        }

        return $array;
    }

    /**
     * Field weights sintaxe:.
     *
     *
     *
     * array(
     *     'field_one' => 5,
     *     'field_two' => 3,
     *     ...
     * );
     *
     *
     * @todo Implementar Query Field weights
     */
    public function getFieldWeights()
    {
    }

    /**
     * Acesso a quantidade de itens por pagina.
     *
     * @return int
     */
    public function getLimit()
    {
        if ($this->getPaginator()) {
            return $this->getPaginator()->getItemNumberPerPage();
        } else {
            return $this->get('limit');
        }
    }

    /**
     * Offsets the result list by the number of places set by the count;.
     *
     * This would be used for pagination through results, where if you have 20
     * results per 'page', the second page would begin at offset 20, the third
     * page at offset 40, etc.
     *
     * @return int
     */
    public function getOffSet()
    {
        if ($this->getPaginator()) {
            return $this->getPaginator()->getOffset();
        } else {
            $offset = $this->get('offset');

            if (!$offset) {
                $offset = 0;
            }

            return $offset;
        }
    }

    /**
     * Mapeamento de index SphinxSearch.
     *
     * @throws \InvalidArgumentException
     *
     * @return string
     */
    public function getIndex()
    {
        $index = $this->get('index');

        if (empty($index)) {
            throw new \InvalidArgumentException('index nao informado');
        }

        return $index;
    }

    /**
     * Mapeamento de index SphinxSearch.
     *
     * @param string $index
     *
     * @throws \InvalidArgumentException
     *
     * @return bool
     */
    public function setIndex($index)
    {
        if (empty($index)) {
            throw new \InvalidArgumentException('index nao pode ser vazio');
        }

        return $this->set('index', $index);
    }

    public function setFilters(FiltersInterface $filters)
    {
        if (!$filters instanceof FiltersInterface) {
            throw new \Exception('Filtro invalido');
        }

        return $this->set('filters', $filters);
    }

    public function setFieldWeights()
    {
    }

    public function setLimit($limit)
    {
        $validator = new \Zend\Validator\Digits();
        if (!$validator->isValid($limit)) {
            throw new \InvalidArgumentException('Limit deve ser numerico');
        }

        return $this->set('limit', $limit);
    }

    public function setOffSet($offset)
    {
        $validator = new \Zend\Validator\Digits();
        if (!$validator->isValid($offset)) {
            throw new \InvalidArgumentException('Offset deve ser numerico');
        }

        return $this->set('offset', $offset);
    }

    /**
     * @return \Gpupo\Search\Paginator\PaginatorInterface|bool
     */
    public function getPaginator()
    {
        $paginator = $this->get('paginator');

        if ($paginator instanceof PaginatorInterface) {
            return $paginator;
        } else {
            return false;
        }
    }

    public function setPaginator(PaginatorInterface $paginator)
    {
        return $this->set('paginator', $paginator);
    }

    public function getCountableAttributes()
    {
        return $this->get('countableAttributes');
    }

    /**
     * Adiciona um atributo para contagem de resultados.
     *
     * Usado na busca facetada
     *
     * @param string $attribute
     *
     * @return bool
     */
    public function addCountableAttribute($attribute)
    {
        if (empty($attribute)) {
            return false;
        }

        if (in_array($attribute, $this->getCountableAttributes(), true)) {
            return false;
        }
        $this->addToArrayValue('countableAttributes', $attribute);

        return $this;
    }

    /**
     * Adiciona muitos atributos para contagem de resultados.
     *
     * @param array $attributes
     */
    public function setCountableAttributes(array $attributes)
    {
        foreach ($attributes as $attribute) {
            $this->addCountableAttribute($attribute);
        }

        return $this;
    }
}


<?php namespace Arcanesoft\Foundation;

use Arcanesoft\Core\Bases\PackageServiceProvider;

/**
 * Class     FoundationServiceProvider
 *
 * @package  Arcanesoft\Foundation
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class FoundationServiceProvider extends PackageServiceProvider
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /**
     * Package name.
     *
     * @var string
     */
    protected $package = 'foundation';

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Register the service provider.
     */
    public function register()
    {
        parent::register();

        $this->registerConfig();
        $this->registerSidebarItems();

        $this->registerProviders([
            Providers\PackagesServiceProvider::class,
            Providers\AuthorizationServiceProvider::class,
            Providers\RouteServiceProvider::class,
            Providers\ViewComposerServiceProvider::class,
        ]);
        $this->registerModuleProviders();
        $this->registerConsoleServiceProvider(Providers\CommandServiceProvider::class);

        $this->registerFoundationService();
    }

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        parent::boot();

        // Publishes
        $this->publishConfig();
        $this->publishViews();
        $this->publishTranslations();
        $this->publishSidebarItems();
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            Contracts\Foundation::class,
        ];
    }

    /* -----------------------------------------------------------------
     |  Services Functions
     | -----------------------------------------------------------------
     */

    /**
     * Register Foundation service.
     */
    private function registerFoundationService()
    {
        $this->singleton(Contracts\Foundation::class, Foundation::class);
    }

    /**
     * Register ARCANESOFT's modules (providers).
     */
    private function registerModuleProviders()
    {
        $providers = $this->config()->get('arcanesoft.foundation.modules.providers', []);

        if (count($providers) > 0)
            $this->registerProviders($providers);
    }
}


<?php namespace Arcanesoft\Foundation\Providers;

use Arcanesoft\Core\Bases\RouteServiceProvider as ServiceProvider;
use Arcanesoft\Foundation\Http\Routes;

/**
 * Class     RouteServiceProvider
 *
 * @package  Arcanesoft\Foundation\Providers
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class RouteServiceProvider extends ServiceProvider
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /**
     * The admin controller namespace for the application.
     *
     * @var string
     */
    protected $adminNamespace = 'Arcanesoft\\Foundation\\Http\\Controllers\\Admin';

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Register the route bindings.
     */
    protected function registerRouteBindings()
    {
        Routes\Admin\SystemRoutes::bindings();
    }

    /**
     * Define the routes for the application.
     */
    public function map()
    {
        $this->mapAdminRoutes();
    }

    /**
     * Map the admin routes.
     */
    private function mapAdminRoutes()
    {
        $this->adminGroup(function () {
            $this->name('foundation.')->group(function () {
                Routes\Admin\DashboardRoute::register();
                Routes\Admin\SettingsRoutes::register();
                Routes\Admin\SystemRoutes::register();
            });
        });
    }
}


<?php
/**
 *
 * User: davidlin
 * Date: 7/11/2013
 * Time: 10:47 PM
 *
 */

namespace Dlin\Zendesk\Client;

use Dlin\Zendesk\Entity\Ticket;
use Dlin\Zendesk\Entity\TicketRequester;
use Dlin\Zendesk\Search\TicketFilter;

class TicketClient extends BaseClient
{

    /**
     * Return entity class type.
     *
     * @return string
     */
    public function getType(){
        return '\Dlin\Zendesk\Entity\Ticket';
    }

    /**
     * Return a ticket by ID
     *
     * @param $id
     * @return \Dlin\Zendesk\Entity\Ticket
     */
    public function getOneById($id){
        return $this->getOne("tickets/$id.json");
    }

    /**
     * Return tickets by an array of Ids
     *
     * @param array $ids
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getByIds(array $ids, $page=1, $per_page=100){

        return $this->getCollection('tickets/show_many.json?ids='.implode(',',$ids), 'tickets',$page, $per_page);
    }

    /**
     * List tickets
     *
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getAll($page=1, $per_page=100){
        return $this->getCollection('tickets.json', 'tickets',$page, $per_page);
    }

    /**
     * List recent tickets
     *
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getRecent($page=1, $per_page=100){
        return $this->getCollection('tickets/recent.json', 'tickets',$page, $per_page);
    }

    /**
     * List tickets for the given organization
     *
     * @param $organization_id
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getOrganizationTickets($organization_id, $page=1, $per_page=100){

        return $this->getCollection("organizations/$organization_id/tickets.json", 'tickets', $page, $per_page);
    }

    /**
     * List user requested tickets
     *
     * @param $user_id
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getUserRequestedTickets($user_id, $page=1, $per_page=100){
        return $this->getCollection("users/$user_id/tickets/requested.json",'tickets', $page, $per_page);
    }

    /**
     * List user ccd tickets
     * @param $user_id
     * @param int $page
     * @param int $per_page
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function getUserCcdTickets($user_id, $page=1, $per_page=100){
        return $this->getCollection("users/$user_id/tickets/ccd.json",'tickets', $page, $per_page);
    }

    /**
     * Search tickets
     *
     * @param TicketFilter $query
     * @param int $page
     * @param int $per_page
     * @param null $sort_by
     * @param string $sort_order
     * @return \Dlin\Zendesk\Result\PaginatedResult
     */
    public function search(TicketFilter $query, $page=1, $per_page=100, $sort_by=null, $sort_order='asc'){

        $endPoint = 'search.json?query='.rawurlencode(implode(' ',$query->toArray()));

        return $this->getCollection($endPoint, 'results', $page, $per_page, $sort_by, $sort_order);
    }

    /**
     * @param Ticket $ticket
     * @param TicketRequester $requester
     * @return \Dlin\Zendesk\Result\ChangeResult|null
     */
    public function save(Ticket $ticket, TicketRequester $requester=null){

        $extraData = $requester ? array('requester'=>$requester) : null;

        return parent::saveEntity($ticket, 'tickets.json', $extraData);
    }

    /**
     *
     * Delete one given ticket
     *
     * @param Ticket $ticket
     * @return bool
     */
    public function delete(Ticket $ticket){
        return parent::deleteById($ticket->getId(), 'tickets');
    }

    /**
     * Batch delete tickets
     *
     * @param array $tickets
     * @return bool
     */
    public function deleteTickets(array $tickets){
        $ids = array();
        foreach($tickets as $ticket){
            $ids[] = $ticket->getId();
        }
        return parent::deleteByIds($ids, 'tickets/destroy_many.json');
    }

}


<?php

/*
 * This file is part of gpupo/search
 *
 * (c) Gilmar Pupo <contact@gpupo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gpupo\Search\Query;

abstract class FiltersAbstract
{
    protected $list = [];

    protected function add(array $array)
    {
        $this->list[$array['key']] = $array;

        return $this;
    }

    protected function append($key, $value)
    {
        $this->list[$key]['values'][] = $value;

        return $this;
    }

    /**
     * Acesso aos valores de um filtro.
     *
     * @param string $key
     *
     * @return array|null
     */
    public function getValues($key)
    {
        if (array_key_exists($key, $this->list)) {
            return $this->list[$key]['values'];
        }
    }

    /**
     * Adiciona um valor a ValuesFilter existente.
     *
     * @param string $key
     * @param type   $value
     *
     * @return bool
     */
    public function appendValueFilter($key, $value)
    {
        if (!empty($value)) {
            if ($this->getValues($key)) {
                return $this->append($key, $value);
            } else {
                return $this->addValuesFilter($key, [$value]);
            }
        } else {
            //do nothing
            return $this;
        }
    }

    /**
     * Filtra por Lista de valores de uma chave.
     *
     * @param string $key    The key to filter on
     * @param array  $values The values to be filtered
     */
    public function addValuesFilter($key, array $values)
    {
        $array = [
            'key'       => $key,
            'values'    => $values,
        ];

        return $this->add($array);
    }

    /**
     * Adiciona um filtro a partir de string no formato 0-10 (inicio - fim).
     *
     * @param string $key
     * @param string $string
     */
    public function addStringRangeFilter($key, $string)
    {
        $array = explode('-', trim($string));

        $min = intval($array[0]);
        if (empty($min)) {
            $min = 1;
        }

        $max = intval($array[1]);
        if (empty($max)) {
            $max = 9999;
        }

        return $this->addRangeFilter($key, $min, $max);
    }

    public function addRangeFilter($key, $min, $max)
    {
        $array = [
            'key'   => $key,
            'min'   => $min,
            'max'   => $max,
        ];

        return $this->add($array);
    }

    public function addGreaterThanFilter($key, $int)
    {
        return $this->addRangeFilter($key, $int, 99999);
    }

    /**
     * Sintaxe de retorno:
     * <code>.
     *
     * array(                                 // Filters only support integer values
     *     array(
     *         'key'    => 'some_search_key', // The key to filter on
     *         'values' => array(30,...),     // The values to be filtered
     *     ),
     *     array(                             // This is a range filter
     *         'key'    => 'some_search_key', // The key to filter on
     *         'min'    => 5,                 // Min and Max value to filter between
     *         'max'    => 105,
     *     ),
     *     ...
     * );
     * </code>
     */
    public function toArray()
    {
        return $this->list;
    }
}


<?php
namespace Peridot\Plugin\Watcher;

use Lurker\Event\FilesystemEvent;
use Lurker\ResourceWatcher;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class LurkerWatcher implements WatcherInterface
{
    /**
     * @var InputInterface
     */
    protected $input;

    /**
     * @var OutputInterface
     */
    protected $output;

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

    /**
     * {@inheritdoc}
     *
     * @param InputInterface $input
     * @return mixed|void
     */
    public function setInput(InputInterface $input)
    {
        $this->input = $input;
    }

    /**
     * {@inheritdoc}
     *
     * @param OutputInterface $output
     * @return mixed|void
     */
    public function setOutput(OutputInterface $output)
    {
        $this->output = $output;
    }

    /**
     * {@inheritdoc}
     *
     * @param array $criteria
     * @return mixed|void
     */
    public function setCriteria(array $criteria)
    {
        $this->criteria = $criteria;
    }

    /**
     * {@inheritdoc}
     *
     * @param $path
     * @param array $events
     * @param callable $listener
     * @return mixed|void
     */
    public function watch($path, array $events, callable $listener)
    {
        $fileEvents = $this->getEventMap();
        $watcher = new ResourceWatcher();
        $paths = is_array($path) ? $path : [$path];
        foreach ($paths as $path) {
            $this->trackPath($path, $events, $listener, $watcher, $fileEvents);
        }
        $watcher->start();
    }

    /**
     * Maps watcher events to FilesystemEvents
     *
     * @return array
     */
    private function getEventMap()
    {
        return [
            WatcherInterface::CREATE_EVENT => FilesystemEvent::CREATE,
            WatcherInterface::MODIFY_EVENT => FilesystemEvent::MODIFY,
            WatcherInterface::DELETE_EVENT => FilesystemEvent::DELETE,
            WatcherInterface::ALL_EVENT => FilesystemEvent::ALL
        ];
    }

    /**
     * @param $path
     * @param array $events
     * @param callable $listener
     * @param $watcher
     * @param $fileEvents
     */
    protected function trackPath($path, array $events, callable $listener, $watcher, $fileEvents)
    {
        foreach ($events as $event) {
            $trackId = "peridot.watcher.$event." . $path;
            $watcher->track($trackId, $path, $fileEvents[$event]);
            $watcher->addListener($trackId, function (FilesystemEvent $e) use ($listener) {
                if ($this->resourceMatchesCriteria($e->getResource())) {
                    $listener($this->input, $this->output);
                }
            });
        }
    }

    /**
     * @param string $resource
     * @return bool
     */
    protected function resourceMatchesCriteria($resource)
    {
        foreach ($this->criteria as $criteria) {
            if (preg_match($criteria, $resource)) {
                return true;
            }
        }
        return false;
    }
}


<?php namespace Arcanesoft\Foundation\ViewComposers;

use Arcanesoft\Sidebar\Contracts\Manager as SidebarManager;
use Illuminate\Support\Arr;
use Illuminate\View\View;

/**
 * Class     SidebarComposer
 *
 * @package  Arcanesoft\Foundation\ViewComposers
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class SidebarComposer
{
    /* -----------------------------------------------------------------
     |  Constants
     | -----------------------------------------------------------------
     */

    const VIEW = 'foundation::admin._template.sidebar-main';

    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /**
     * The Sidebar instance.
     *
     * @var \Arcanesoft\Sidebar\Contracts\Manager
     */
    protected $sidebar;

    /* -----------------------------------------------------------------
     |  Constructor
     | -----------------------------------------------------------------
     */

    /**
     * SidebarComposer constructor.
     *
     * @param  \Arcanesoft\Sidebar\Contracts\Manager  $sidebar
     */
    public function __construct(SidebarManager $sidebar)
    {
        $this->sidebar = $sidebar;
    }

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Bind data to the view.
     *
     * @param  \Illuminate\View\View  $view
     */
    public function compose(View $view)
    {
        $this->sidebar->loadItemsFromConfig('arcanesoft.foundation.sidebar.items');
        $this->sidebar->setCurrent(
            Arr::get($view->getData(), 'current_page', '')
        );
    }
}


<?php namespace Arcanesoft\Foundation\Console;

use Arcanedev\Support\Bases\Command as BaseCommand;

/**
 * Class     Command
 *
 * @package  Arcanesoft\Foundation\Console
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
abstract class Command extends BaseCommand
{
    /* -----------------------------------------------------------------
     |  Shared Methods
     | -----------------------------------------------------------------
     */

    /**
     * Display arcanesoft header.
     */
    protected function arcanesoftHeader()
    {
        $this->comment('    ___    ____  _________    _   _____________ ____  ____________');
        $this->comment('   /   |  / __ \/ ____/   |  / | / / ____/ ___// __ \/ ____/_  __/');
        $this->comment('  / /| | / /_/ / /   / /| | /  |/ / __/  \__ \/ / / / /_    / /   ');
        $this->comment(' / ___ |/ _, _/ /___/ ___ |/ /|  / /___ ___/ / /_/ / __/   / /    ');
        $this->comment('/_/  |_/_/ |_|\____/_/  |_/_/ |_/_____//____/\____/_/     /_/     ');
        $this->line('');

        // Copyright
        $this->comment('Version '.foundation()->version().' | 2015-'.date('Y').' | Created by ARCANEDEV(c)');
        $this->line('');
    }

    /**
     * Get the config repository.
     *
     * @return \Illuminate\Contracts\Config\Repository
     */
    protected function config()
    {
        return $this->laravel['config'];
    }
}


<?php
/**
 * Windwork
 *
 * 一个用于快速开发高并发Web应用的轻量级PHP框架
 *
 * @copyright Copyright (c) 2008-2017 Windwork Team. (http://www.windwork.org)
 * @license   http://opensource.org/licenses/MIT
 */
namespace wf\crypt\adapter;

/**
 * 可逆对称加密解密
 * 极高效的对称加密算法
 * 参考Discuz! Passport采用的Azerbaijan Development Group（AzDG）开发的可逆加密算法
 *
 * @package     wf.crypt.adapter
 * @author      cm <cmpan@qq.com>
 * @link        http://docs.windwork.org/manual/wf.crypt.html
 * @since       0.1.0
 */
class AzDG implements \wf\crypt\CryptInterface
{
	/**
	 * 加密
	 *
	 * @param string 等待加密的原字串
	 * @param string 私有密匙(用于解密和加密)
	 *
	 * @return string 原字串经过私有密匙加密后的结果
	 */
	public function encrypt($txt, $key)
	{
		// 使用随机数发生器产生 0~32000 的值并 MD5()
		srand((double)microtime() * 1000000);
		$encryptKey = md5(rand(0, 32000));

		// 变量初始化
		$ctr = 0;
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for($i = 0; $i < strlen($txt); $i++) {
			// 如果 $ctr = $encryptKey 的长度，则 $ctr 清零
			$ctr = $ctr == strlen($encryptKey) ? 0 : $ctr;
			// $tmp 字串在末尾增加两位，其第一位内容为 $encryptKey 的第 $ctr 位，
			// 第二位内容为 $txt 的第 $i 位与 $encryptKey 的 $ctr 位取异或。然后 $ctr = $ctr + 1
			$tmp .= $encryptKey[$ctr].($txt[$i] ^ $encryptKey[$ctr++]);
		}

		// 返回结果，结果为 self::key() 函数返回值的 base64 编码结果
		return base64_encode(self::key($tmp, $key));
	}

	/**
	 * 解密
	 *
	 * @param string 加密后的字串
	 * @param string 私有密匙(用于解密和加密)
	 *
	 * @return string 字串经过私有密匙解密后的结果
	 */
	public function decrypt($txt, $key)
	{
		// $txt 的结果为加密后的字串经过 base64 解码，然后与私有密匙一起，
		// 经过 self::key() 函数处理后的返回值
		$txt = self::key(base64_decode($txt), $key);

		// 变量初始化
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for ($i = 0; $i < strlen($txt); $i++) {
			// $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
			// 与 $txt 的第 $i + 1 位取异或。然后 $i = $i + 1
			$tmp .= $txt[$i] ^ $txt[++$i];
		}

		// 返回 $tmp 的值作为结果
		return $tmp;
	}

	/**
	 * 密匙处理
	 *
	 * @param string 待加密或待解密的字串
	 * @param string 私有密匙(用于解密和加密)
	 *
	 * @return string 处理后的密匙
	 */
	private static function key($txt, $encryptKey)
	{
		// 将 $encryptKey 赋为 $encryptKey 经 md5() 后的值
		$encryptKey = md5($encryptKey);

		// 变量初始化
		$ctr = 0;
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for($i = 0; $i < strlen($txt); $i++) {
			// 如果 $ctr = $encryptKey 的长度，则 $ctr 清零
			$ctr = $ctr == strlen($encryptKey) ? 0 : $ctr;
			// $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
			// 与 $encryptKey 的第 $ctr + 1 位取异或。然后 $ctr = $ctr + 1
			$tmp .= $txt[$i] ^ $encryptKey[$ctr++];
		}

		// 返回 $tmp 的值作为结果
		return $tmp;
	}
}


<?php namespace Arcanesoft\Foundation\Providers;

use Arcanedev\LogViewer\LogViewerServiceProvider;
use Arcanedev\RouteViewer\RouteViewerServiceProvider;
use Arcanedev\Support\ServiceProvider;

/**
 * Class     PackagesServiceProvider
 *
 * @package  Arcanesoft\Foundation\Providers
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class PackagesServiceProvider extends ServiceProvider
{
    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Register the service provider.
     */
    public function register()
    {
        parent::register();

        $this->registerLogViewerPackage();
        $this->registerRouteViewerPackage();
        $this->registerAliases();
    }

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        parent::boot();

        //
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            //
        ];
    }

    /* -----------------------------------------------------------------
     |  Register Packages
     | -----------------------------------------------------------------
     */
    /**
     * Register the LogViewer Package.
     */
    private function registerLogViewerPackage()
    {
        $this->registerProvider(LogViewerServiceProvider::class);

        $config = $this->config();

        // Setting up the LogViewer config.
        $config->set('log-viewer.route.enabled', false);
        $config->set(
            'log-viewer.menu.filter-route',
            $config->get('arcanesoft.foundation.log-viewer.filter-route')
        );
    }

    /**
     * Register the RouteViewer Package.
     */
    private function registerRouteViewerPackage()
    {
        $this->registerProvider(RouteViewerServiceProvider::class);

        // Setting up the RouteViewer config.
        $this->config()->set('route-viewer.php.route.enabled', false);
    }
}


<?php

/*
 * This file is part of gpupo/search
 *
 * (c) Gilmar Pupo <contact@gpupo.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Gpupo\Search\Result;

use Gpupo\Search\Paginator\PaginatorInterface;
use Gpupo\Common\Entity\CollectionAbstract ;

/**
 * Conjunto de Itens de resultado.
 */
abstract class AbstractCollection extends CollectionAbstract
{
    /**
     * Lista de documentos encontrados.
     */
    public function getMatches()
    {
        return $this->get('matches');
    }

    /**
     * Quantidade de documentos encontrados para a query, independente da paginação.
     */
    public function getTotal()
    {
        return intval($this->get('total'));
    }

    /**
     * @see getTotal()
     */
    public function getTotalFound()
    {
        return intval($this->get('total_found'));
    }

    /**
     * Tempo necessário para a pesquisa.
     */
    public function getTime()
    {
        return $this->get('time');
    }

    /**
     * Detalhes dos resultados para cada palavra.
     */
    public function getWords()
    {
        return $this->get('words');
    }

    /**
     * Detalhes dos resultados para cada palavra.
     */
    public function getSummary()
    {
        $string = "---\n";
        foreach ($this->getWords() as $k => $v) {
            $string .= '['.$k.']: Docs:'.$v['docs']
                .' | Hits:'.$v['hits']."\n";
        }

        return $string;
    }

    public function getPaginator()
    {
        return $this->get('paginator');
    }

    public function setPaginator(PaginatorInterface $paginator)
    {
        return $this->set('paginator', $paginator);
    }

    public function paginate($limit, $offset = 0)
    {
    }

    /**
     * @return ItemInterface
     */
    public function factoryItem(array $array)
    {
        return new Item($array);
    }

    public function __construct(array $array = null)
    {
        return $this->load($array);
    }

    /**
     * @param array $array Lista de resultados
     */
    public function load(array $array = null)
    {
        if ($array) {
            $list = [];

            if (array_key_exists('matches', $array)) {
                $matches = $array['matches'];
                unset($array['matches']);
            } elseif (array_key_exists('matches', $array[0])) {
                $matches = $array[0]['matches'];
                unset($array[0]['matches']);
                $array = $array[0];
            } else {
                parent::__construct($array);

                return $this;
            }

            foreach ($matches as $result) {
                $list[] = $this->factoryItem($result);
            }

            $array['itens'] = $list;

            parent::__construct($array);

            return $this;
        }
    }

    public function __toString()
    {
        $string = '';

        foreach ($this->toArray() as $item) {
            $string .= (string) $item;
        }

        return $string;
    }

    public function toArray()
    {
        return (array) $this->get('itens');
    }

    /**
     * First item found.
     *
     * @return Item
     */
    public function getFirst()
    {
        return current($this->toArray());
    }
}


<?php namespace Arcanesoft\Foundation\ViewComposers\System;

use Illuminate\View\View;

/**
 * Class     ServerRequirementsComposer
 *
 * @package  Arcanesoft\Foundation\ViewComposers\System
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class ServerRequirementsComposer
{
    /* -----------------------------------------------------------------
     |  Constants
     | -----------------------------------------------------------------
     */

    const VIEW = 'foundation::admin.system.information._includes.server-requirements';

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Compose the view.
     *
     * @param  \Illuminate\View\View  $view
     */
    public function compose(View $view)
    {
        $requirements['server']['ssl']     = $this->checkSslInstalled();
        $requirements['server']['modules'] = $this->getServerModules([
            'mod_rewrite',
        ]);

        $view->with('requirements', $requirements);
    }

    /* -----------------------------------------------------------------
     |  Other Methods
     | -----------------------------------------------------------------
     */

    /**
     * Check if SSL is installed.
     *
     * @return bool
     */
    private function checkSslInstalled()
    {
        return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? true : false;
    }

    /**
     * Check the APACHE requirements.
     *
     * @param  array  $requirements
     *
     * @return \Illuminate\Support\Collection
     */
    private function getServerModules(array $requirements)
    {
        if ( ! function_exists('apache_get_modules')) {
            return collect([]);
        }

        $modules      = apache_get_modules();
        $requirements = array_combine($requirements, $requirements);

        return collect($requirements)->transform(function ($requirement) use ($modules) {
            return in_array($requirement, $modules);
        });
    }
}


<?php

namespace Bavix\Router;

use Bavix\Exceptions\Runtime;

trait Attachable
{

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

    /**
     * Attachable constructor.
     *
     * @param string $key
     * @param array $storage
     */
    protected function initializer(string $key, array $storage): void
    {
        $this->_name = $key;
        $this->attached($storage);
    }

    /**
     * @param array $storage
     */
    protected function attached(array $storage): void
    {
        foreach ($this->filter($storage) as $key => $value) {
            $this->$key = $value;
        }
    }

    /**
     * @param array $storage
     * @return array
     */
    protected function filter(array $storage): array
    {
        return \array_filter($storage, function (string $key) {
            $this->checkProperty($key);
            return $key{0} !== '@'; // for xml
        }, \ARRAY_FILTER_USE_KEY);
    }

    /**
     * @param string $key
     * @throws
     */
    protected function checkProperty(string $key): void
    {
        if (!\property_exists($this, $key) || \strpos($key, '_') === 0) {
            throw new Runtime(\sprintf('The key `%s` is not registered', $key));
        }
    }

}