<?php

namespace kitten\component\container;

use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class Container implements ExpandContainerInterface
{
    private $entries = [];
    /** @var ServiceProviderInterface[] */
    private $providers=[];

    /**
     * Finds an entry of the container by its identifier and returns it.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @throws NotFoundExceptionInterface  No entry was found for **this** identifier.
     * @throws ContainerExceptionInterface Error while retrieving the entry.
     *
     * @return mixed Entry.
     */
    public function get($id)
    {
        if (!array_key_exists($id, $this->entries)) {
            throw new NotFoundException(sprintf('The entry for %s was not found.', $id));
        }
        // Pass in the container as the only argument to the closure when we invoke it.
        return $this->entries[$id]($this);
    }

    /**
     * Returns true if the container can return an entry for the given identifier.
     * Returns false otherwise.
     *
     * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
     * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
     *
     * @param string $id Identifier of the entry to look for.
     *
     * @return bool
     */
    public function has($id):bool
    {
        return isset($this->entries[$id]);
    }

    /**
     * Adds an entry to the container.
     * @param string $id Identifier of the entry.
     * @param \Closure $value The closure to invoke when this entry is resolved.
     */
    function set(string $id, \Closure $value)
    {
        $this->entries[$id] = $value;
    }

    /**
     * Adds a shared (singleton) entry to the container.
     * @param string $id Identifier of the entry.
     * @param \Closure $value The closure to invoke when this entry is resolved.
     */
    function share(string $id, \Closure $value)
    {
        $this->entries[$id] = function ($container) use ($value) {
            static $resolvedValue;
            if (is_null($resolvedValue)) {
                $resolvedValue = $value($container);
            }
            return $resolvedValue;
        };
    }

    function addServiceProvider(ServiceProviderInterface $provider)
    {
        $provider->register($this);
        $this->providers[]=$provider;
    }

    function boot()
    {
        foreach ($this->providers as $provider) {
            if ($provider instanceof BootServiceProviderInterface){
                $provider->boot($this);
            }
        }
    }
}


<?php
/**
 * OpenWebPresence Support Library - openwebpresence.com
 *
 * @copyright 2001 - 2017, Brian Tafoya.
 * @package   OwpMessaging
 * @author    Brian Tafoya <btafoya@briantafoya.com>
 * @version   1.0
 * @license   MIT
 * @license   https://opensource.org/licenses/MIT The MIT License
 * @category  OpenWebPresence_Support_Library
 * @link      http://openwebpresence.com OpenWebPresence
 *
 * Copyright (c) 2017, Brian Tafoya
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * This class provides messaging for the owpFramework library utilizing PHPMailer.
 */
class OwpMessaging
{

    /**
     * @var array $errors Error array
     */
    public $errors = array();

    /**
     * @var string $root_path The root file path.
     */
    private $root_path = null;

    /**
     * Constructor.
     */
    function __construct()
    {
        $this->root_path = ROOT_PATH;

    }//end __construct()

    /**
     * sendEmailDirect
     *
     * @method boolean sendEmailDirect($data_array) Send email directly to the recipient's mail server using the PHPMailer library.
     * @access public
     * @return boolean
     * @param  array $data_array Mailer data array.
     *
     * @throws InvalidArgumentException Missing required argument
     * @throws Exception Meage send failure.
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    public function sendEmailDirect($data_array)
    {
        try {
            $email_to_clean     = filter_var($data_array["email_to"], FILTER_SANITIZE_EMAIL);
            list($to_addy_info) = imap_rfc822_parse_adrlist($email_to_clean, "");
            $dns_get_mx         = dns_get_record($to_addy_info->host, DNS_MX);
            $ip           = gethostbyname($dns_get_mx[0]["target"]);
            $message_sent = $this->sendCore($data_array, (string) $ip);
        } catch (InvalidArgumentException $e) {
            throw new InvalidArgumentException("OwpMessaging->sendEmailDirect(): Caught InvalidArgumentException: ".$e->getMessage());
        } catch (Exception $e) {
            throw new Exception("OwpMessaging->sendEmailDirect(): Caught Exception: ".$e->getMessage());
        }

        return $message_sent;

    }//end sendEmailDirect()

    /**
     * sendEmailViaSMTP()
     *
     * @method boolean sendEmailViaSMTP($data_array) Send email via mail server using the PHPMailer library.
     * @access public
     * @return boolean
     * @param  array $data_array Mailer data array.
     *
     * @throws InvalidArgumentException Missing required argument
     * @throws Exception Meage send failure.
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    public function sendEmailViaSMTP($data_array)
    {

        try {
            $message_sent = $this->sendCore($data_array, (string) getenv("smtp_hostname"));
        } catch (InvalidArgumentException $e) {
            throw new InvalidArgumentException("OwpMessaging->sendEmailViaSMTP(): Caught InvalidArgumentException: ".$e->getMessage());
        } catch (Exception $e) {
            throw new Exception("OwpMessaging->sendEmailViaSMTP(): Caught Exception: ".$e->getMessage());
        }

        return $message_sent;

    }//end sendEmailViaSMTP()

    /**
     * sendCore()
     *
     * @method boolean sendCore($data_array, $smtp_hostname) Core PHPMailer library.
     * @access private
     * @return boolean
     * @param  array  $data_array    Mailer data array.
     * @param  String $smtp_hostname hostname to send to.
     * @throws Exception Mail end failure.
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    private function sendCore($data_array, $smtp_hostname)
    {

        try {
            $this->validateData($data_array);
        } catch (InvalidArgumentException $e) {
            throw new InvalidArgumentException("OwpMessaging->sendCore(): Caught InvalidArgumentException: ".$e->getMessage());
        }

        $email_to_clean = filter_var($data_array["email_to"], FILTER_SANITIZE_EMAIL);

        $mail = new PHPMailer;

        $mail->isSMTP();
        $mail->Host = $smtp_hostname;

        if(in_array(getenv("smtp_auth"), array("yes", "true", 1))) {
            $mail->SMTPAuth = true;
            $mail->Username = (string) getenv("smtp_username");
            $mail->Password = (string) getenv("smtp_password");
        }

        if(in_array(getenv("smtp_secure"), array("ssl", "tls"))) {
            $mail->SMTPSecure  = (string) getenv("smtp_secure");
            $mail->SMTPOptions = array(
                                  'ssl' => array(
                                            'verify_peer'       => false,
                                            'allow_self_signed' => true,
                                            'verify_peer_name'  => false,
                                            'cafile'            => '/etc/ssl/ca_cert.pem',
                                           ),
                                 );
        }

        $mail->Port = (string) getenv("smtp_port");

        $mail->XMailer  = "OpenWebPresence-1.0";
        $mail->Helo     = gethostname();
        $mail->Hostname = gethostname();

        $mail->From     = $data_array["email_from"];
        $mail->FromName = $data_array["email_from_name"];
        $mail->AddAddress($email_to_clean, $data_array["email_to_name"]);
        // $mail->AddReplyTo(filter_var($data_array["reply_to"], FILTER_SANITIZE_EMAIL));
        if(in_array(getenv("DKIM_active"), array("yes", "true", 1))) {
            $mail->DKIM_domain     = getenv("DKIM_domain");
            $mail->DKIM_private    = $this->root_path.'PHPMailer_DKIM/'.getenv("DKIM_private").'.htkeyprivate';
            $mail->DKIM_selector   = getenv("DKIM_selector");
            $mail->DKIM_passphrase = getenv("DKIM_passphrase");
            $mail->DKIM_identity   = getenv("DKIM_identity");
        }

        $mail->WordWrap = 50;
        $mail->IsHTML(true);

        $mail->Subject = $data_array["subject"];
        $mail->Body    = $data_array["message_body"];

        $mail->addCustomHeader("X-AntiAbuse", "This is a solicited email for ".$data_array["sender_domain"].".");
        $mail->addCustomHeader("X-AntiAbuse", $data_array["email_from"]);

        if(!$mail->send()) {
            throw new Exception($mail->ErrorInfo);
        } else {
            return true;
        }

    }//end sendCore()

    /**
     * validateData
     *
     * @method validateData() Validate the arguments used to send a message.
     * @access private
     * @param  array $data_array Mail data to be validated.
     * @return boolean
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    private function validateData($data_array)
    {
        $required_variables = array(
                               "sender_domain",
                               "subject",
                               "message_body",
                               "email_to",
                               "email_to_name",
                               "email_from",
                               "email_from_name",
                               "reply_to",
                              );

        $missing_columns = array_diff($required_variables, array_keys($data_array));

        if($missing_columns) {
            throw new InvalidArgumentException("OwpMessaging->validateData() : The following columns are missing: ".implode(", ", $missing_columns));
        }

        return true;

    }//end validateData()

}//end class


<?php
    /**
     * Bu Dosya AnonymFramework'e ait bir dosyadır.
     *
     * @author vahitserifsaglam <vahit.serif119@gmail.com>
     * @see http://gemframework.com
     *
     */

    namespace Anonym\Components\Crypt;

    /**
     * Class SecurityKeyGenerator
     * @package Anonym\Components\Crypt
     */
    class SecurityKeyGenerator implements SecurityKeyGeneratorInterface
    {

        /**
         * Özel güvenlik anahtarını oluşturur
         *
         * @return string
         */
        public function create()
        {
            $ip = $_SERVER['REMOTE_ADDR'];
            $len = strlen($ip);
            $letters = [];
            for ($i = 'a', $j = 1; $j <= 26; $i++, $j++) {
                $letters[$j] = $i;
            }
            $bas = substr($ip, 0, 2);
            $con = $letters[$len];
            $son = substr($ip, $len - 1, 1);
            $int = strval($len).$son;
            $con2 = $letters[$int];
            $serverIP = $_SERVER['SERVER_ADDR'];
            $message = $son . $serverIP . $con . $con2 . $ip . $bas;
            return md5($message);
        }

        /**
         * create a random string
         *
         * @param string $prefix
         * @return string
         */
        public function random($prefix = ''){
            $key = $prefix.$this->create().strval(rand(strlen($_SERVER['REMOTE_ADDR']), rand(111,2222)));
            $uniqid = uniqid($key);
            return md5($uniqid);
        }
    }


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\ORM;

use Valkyrja\Model\Model;
use Valkyrja\ORM\Enums\PropertyType;

/**
 * Class Entity.
 *
 * @author Melech Mizrachi
 */
abstract class Entity extends Model
{
    /**
     * The table name.
     *
     * @var string
     */
    protected static $table = self::class;

    /**
     * The id field.
     *
     * @var string
     */
    protected static $idField = 'id';

    /**
     * Valid types allowed to be mass set.
     *
     * @var array
     */
    protected static $properties = [];

    /**
     * Required properties.
     *
     * @var array
     */
    protected static $required = [];

    /**
     * Types for attributes that differs from what they were saved into the database as.
     *
     *
     *      [
     *          // An array to be json_encoded/decoded to/from the db
     *          'property_name' => 'array',
     *          // An object to be serialized and unserialized to/from the db
     *          'property_name' => 'object',
     *          // A related entity
     *          'property_name' => Entity::class,
     *          // An array of related entities
     *          'property_name' => [Entity::class],
     *      ]
     *
     *
     * @var array
     */
    protected static $propertyTypes = [];

    /**
     * The ORM repository to use.
     *
     * @var string|null
     */
    protected static $repository;

    /**
     * Get the table.
     *
     * @return string
     */
    public static function getTable(): string
    {
        return static::$table;
    }

    /**
     * Get the id field.
     *
     * @return string
     */
    public static function getIdField(): string
    {
        return self::$idField;
    }

    /**
     * Get the properties.
     *
     * @return array
     */
    public static function getProperties(): array
    {
        return static::$properties;
    }

    /**
     * Get the property types.
     *
     * @return array
     */
    public static function getPropertyTypes(): array
    {
        return static::$propertyTypes;
    }

    /**
     * Get the ORM repository.
     *
     * @return null|string
     */
    public static function getRepository(): ? string
    {
        return static::$repository;
    }

    /**
     * Get required properties.
     *
     * @return array
     */
    public static function getRequiredProperties(): array
    {
        return static::$required;
    }

    /**
     * A mapper of property types to properties for generating a full entity with relations.
     * NOTE: Used in conjunction with Entity::$propertyTypes. If a property type is defined
     * but a property mapper is not, then the property type is NOT automatically filled in
     * via the EntityManager and Repository. If a mapper is specified and a type is not
     * then nothing happens.
     *
     *
     *      [
     *          'property_name' => [
     *              'field'         => 'fieldNameOfThisEntity',
     *              'relationField' => 'fieldNameOfTheRelationEntityToMapTo',
     *          ]
     *      ]
     *
     *
     * @return array
     */
    public function getPropertyMapper(): array
    {
        return [];
    }

    /**
     * Set properties from an array of properties.
     *
     * @param array $properties
     *
     * @return void
     */
    public function fromArray(array $properties): void
    {
        // Iterate through the properties
        foreach ($properties as $property => $value) {
            // If the value is null or the property doesn't exist in this model
            if (null === $value || ! property_exists($this, $property)) {
                // Continue to the next property
                continue;
            }

            // Check if a type was set for this attribute
            $type = static::$propertyTypes[$property] ?? null;

            switch ($type) {
                // If the type is object and the property isn't already an object
                case PropertyType::OBJECT:
                    if (! \is_object($value)) {
                        $value = unserialize($value, true);
                    }

                    break;
                // If the type is array and the property isn't already an array
                case PropertyType::ARRAY:
                    if (! \is_array($value)) {
                        $value = json_decode($value, true);
                    }

                    break;
                default:
                    // Otherwise if a type was set and type is an array and the value is an array
                    // Then this should be an array of entities
                    if ($type !== null && \is_array($type) && \is_array($value)) {
                        // Iterate through the items
                        foreach ($value as &$item) {
                            // Create a new entity for each item
                            $item = new $type[0]($item);
                        }

                        // Unset the reference loop item
                        unset($item);
                    } // Otherwise if a type was set and the value isn't already of that type
                    elseif ($type !== null && ! ($value instanceof $type)) {
                        $value = new $type($value);
                    }
            }

            // Set the property
            $this->__set($property, $value);
        }
    }

    /**
     * Get entity as an array.
     *
     * @return array
     */
    public function asArray(): array
    {
        return $this->jsonSerialize();
    }

    /**
     * Get the entity as an array for saving to the data store.
     *
     * @return array
     */
    public function forDataStore(): array
    {
        $properties = [];

        // Otherwise iterate through the properties array
        foreach (static::$properties as $property) {
            $value = $this->{$property};
            // Check if a type was set for this attribute
            $type = static::$propertyTypes[$property] ?? null;

            // If the type is object and the property isn't already an object
            if ($type === PropertyType::OBJECT && \is_object($value)) {
                // Unserialize the object
                $value = serialize($value);
            } // If the type is array and the property isn't already an array
            elseif ($type === PropertyType::ARRAY && \is_array($value)) {
                $value = \json_encode($value);
            }

            // And set each property to its value
            $properties[$property] = $value;
        }

        return $properties;
    }
}


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium>
 *
 * For the full copyright and license information, please view the LICENSE.md
 * file that was distributed with this source code.
 */

namespace jarrus90\User\controllers;

use jarrus90\User\models\Assignment;
use Yii;
use yii\web\Controller;

/**
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class AssignmentController extends Controller {

    /**
     * Show form with auth items for user.
     *
     * @param int $id
     */
    public function actionAssign($id) {
        $model = Yii::createObject([
                    'class' => Assignment::className(),
                    'user_id' => $id,
        ]);

        if ($model->load(\Yii::$app->request->post()) && $model->updateAssignments()) {

        }

        return \jarrus90\User\widgets\Assignments::widget([
                    'model' => $model,
        ]);
    }

}


<?php

/*
 * This file is part of the Pondtunes package.
 *
 * (c) Marcus Stöhr <dafish@soundtrack-board.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pond\Tunes;

use Pond\Tunes\Tunes;

class Search extends Tunes
{
    /**
     * URI for search service
     *
     * @var string
     */
    private $serviceUri = 'https://itunes.apple.com/search?';

    /**
     * @var array
     */
    private $searchTerms = array();

    /**
     * {@inheritDoc}
     */
    public function getRawRequestUrl()
    {
        if ('' == $this->rawRequestUrl) {
            $this->buildSpecificRequestUri();
        }

        return $this->rawRequestUrl;
    }

    /**
     * Return search term
     *
     * @return array
     */
    public function getTerms()
    {
        return $this->searchTerms;
    }

    /**
     * Add search terms. New terms are appended unless $reset is set to `false`.
     *
     * @param array|string $terms Terms to be searched on.
     * @param boolean      $reset Set to `true` if previously set terms should be reset.
     *
     * @return Search
     */
    public function setTerms($terms, $reset = false)
    {
        if ($reset) {
            $this->searchTerms = array();
        }

        $searchTerms = array();
        if (!is_array($terms)) {
            $terms = explode(' ', $terms);
        }

        foreach ($terms as $term) {
            $words = explode(' ', $term);

            $searchTerms = array_merge($searchTerms, $words);
        }

        $this->searchTerms = array_merge($this->searchTerms, $searchTerms);

        return $this;
    }

    /**
     * Request information for countries. If no parameter is passed the complete
     * list of countries will be searched.
     *
     * @param array $countries
     *
     * @return array
     */
    public function requestForCountries($countries = array())
    {
        if (empty($countries)) {
            $countries = self::$countryList;
        }

        $results = array();
        foreach ($countries as $country) {
            $this->setCountry($country);

            $results[$country] = $this->request();
        }

        return $results;
    }

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

    /**
     * {@inheritDoc}
     */
    protected function buildSpecificRequestUri()
    {
        $requestParameters = array();

        $uri = parent::buildRequestUri();
        if (!empty($uri)) {
            $requestParameters[] = $uri;
        }

        if (empty($this->searchTerms)) {
            throw new \LogicException('Cannot query search service if no terms are set!');
        }

        // add terms
        $requestParameters[] = 'term=' . implode('+', array_map('urlencode', $this->searchTerms));

        $this->rawRequestUrl = $this->getUri() . implode('&', $requestParameters);
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Utils;

/**
 * Boite à outils pour les chaînes de caractères
 */
class StringTools
{

  /**
   * Retourne la longueur de la chaîne de caractères
   *
   * @param  string  $string  Chaîne de caractères
   * @return integer          Longueur de la chaîne
   */
  public static function len($string)
  {
    return strlen($string);
  }

  /**
   * Permet de reconstituer une chaîne de caractère à partir d'un tableau de chaînes
   *
   * @param  array   $pieces  Tableau de chaînes de caractères
   * @param  string  $glue    (optional) Caractère de séparation des éléments reconstitués (Chaîne vide par défaut)
   * @return array
   */
  public static function implode($pieces, $glue = '')
  {
    return implode($glue, $pieces);
  }

  /**
   * Teste si la chaine contient une sous-chaîne spécifiée
   *
   * @param  string  $string  Chaîne de caractères
   * @param  string  $search  Chaîne recherchée
   * @param  boolean $noCase  (optional) Ne pas prendre en compte la casse (FALSE par défaut)
   * @return boolean          TRUE si la chaîne contient la sous-chaîne
   */
  public static function contains($string, $search, $noCase = false)
  {
    return static::firstIndexOf($string, $search, $noCase) != -1;
  }

  /**
   * Teste si la chaîne débute par le préfixe indiqué
   *
   * @param  string  $string  Chaîne de caractères
   * @param  string  $prefix  Préfixe à tester
   * @param  boolean $noCase  (optional) Ne pas prendre en compte la casse (FALSE par défaut)
   * @return boolean          TRUE si la chaîne débute par le préfixe indiqué
   */
  public static function startsWith($string, $prefix, $noCase = false)
  {
    if ($noCase) {
      return strtolower(substr($string, 0, strlen($prefix))) == strtolower($prefix);
    } else {
      return substr($string, 0, strlen($prefix)) == $prefix;
    }
  }

  /**
   * Teste si la chaîne finit par le suffixe indiqué
   *
   * @param  string  $string  Chaîne de caractères
   * @param  string  $suffix  Suffixe à tester
   * @param  boolean $noCase  (optional) Ne pas prendre en compte la casse (FALSE par défaut)
   * @return boolean          TRUE si la chaîne finit par le suffixe indiqué
   */
  public static function endsWith($string, $suffix, $noCase = false)
  {
    $length = strlen($suffix);
    if ($noCase) {
      return strtolower(substr($string, strlen($string) - $length, $length)) == strtolower($suffix);
    } else {
      return substr($string, strlen($string) - $length, $length) == $suffix;
    }
  }

  /**
   * Cherche la première occurence d'une sous-chaîne dans la chaîne en commençant à l'index spécifié. Retourne -1 si aucune occurence n'est trouvée
   *
   * @param  string  $string      Chaîne de caractères
   * @param  string  $search      Chaîne à rechercher
   * @param  boolean $noCase      (optional) Ne pas prendre en compte la casse (FALSE par défaut)
   * @param  integer $startIndex  (optional) Index à partir duquel commencer la recherche (0 par défaut)
   * @return integer              Position de la chaîne recherchée, -1 si aucune occurence n'est trouvée
   */
  public static function firstIndexOf($string, $search, $noCase = false, $startIndex = 0)
  {
    if ($noCase) {
      $index = stripos($string, $search, $startIndex);
    } else {
      $index = strpos($string, $search, $startIndex);
    }
    return ($index === false) ? -1 : $index;
  }

  /**
   * Cherche la dernière occurence d'une sous-chaîne dans la chaîne en limitant la recherche à l'index spécifié.
   * Retourne -1 si aucune occurence n'est trouvée
   *
   * @param  string  $string    Chaîne de caractères
   * @param  string  $search    Chaîne à rechercher
   * @param  boolean $noCase    (optional) Ne pas prendre en compte la casse (FALSE par défaut)
   * @param  integer $endIndex  (optional) Index limitant la recherche (Par défaut la recherche débute à la fin de la chaîne)
   * @return integer            Position de la chaîne recherchée, -1 si aucune occurence n'est trouvée
   */
  public static function lastIndexOf($string, $search, $noCase = false, $endIndex = 0)
  {
    if ($noCase) {
      $index = strripos($string, $search, $endIndex);
    } else {
      $index = strrpos($string, $search, $endIndex);
    }
    return ($index === false) ? -1 : $index;
  }

  /**
   * Analyse la chaîne pour trouver lex expressions qui correspondent à l'expression régulière fournie
   *
   * @param  string  $string      Chaîne de caractères
   * @param  string  $regex       Expression régulière
   * @param  integer $startIndex  (optional) Index où débuter la recherche (0 par défaut)
   * @return array                Tableau multidimensionnel
   */
  public static function getMatches($string, $regex, $startIndex = 0)
  {
    $matches = array();
    preg_match_all($regex, $string, $matches, PREG_OFFSET_CAPTURE, $startIndex);
    return $matches[0];
  }

  /**
   * Retourne le caractère à l'index spécifié
   *
   * @param  string  $string   Chaîne de caractères
   * @param  integer $index    Index
   * @return string            Caractère trouvé à l'index spécifié
   */
  public static function charAt($string, $index)
  {
    return substr($string, $index, 1);
  }

  /**
   * Retourne une portion de chaîne
   *
   * @param  string  $string  Chaîne de caractères
   * @param  integer $index   Index à partir duquel prélever la sous-chaîne
   * @param  integer $length  (optional) Longueur de la chaîne à prélever. (Par défaut correspondra à toute la fin de la chaîne)
   * @return string          Portion de chaîne
   */
  public static function substring($string, $index, $length = 0)
  {
    return substr($string, $index, $length);
  }

  /**
   * Retourne la sous-chaîne de caractères au début de la chaîne
   *
   * @param  string  $string  Chaîne de caractère
   * @param  integer $length  Nombre de caractères à retourner
   * @return string           Sous chaîne de caractères
   */
  public static function left($string, $length)
  {
    return substr($string, 0, $length);
  }

  /**
   * Retourne la sous-chaîne de caractères à la fin de la chaîne
   *
   * @param  string  $string  Chaîne de caractère
   * @param  integer $length  Nombre de caractères à retourner
   * @return string           Sous chaîne de caractères
   */
  public static function right($string, $length)
  {
    return substr($string, strlen($string) - $length, $length);
  }

  /**
   * Coupe la chaîne en un tableau
   *
   * @param  string  $string     Chaîne de caractères
   * @param  string  $delimiter  (optional) Caractère ou chaîne utilisée pour découper le tableau. (Si la chaîne est vide ou non fournie la chaîne sera découpée pour chaque caractère)
   * @return array               Tableau de chaînes de caractères
   */
  public static function explode($string, $delimiter = '')
  {
    if ($delimiter == '') {
      return str_split($string);
    } else {
      return explode($delimiter, $string);
    }
  }

  /**
   * Remplace les occurences de la sous-chaîne dans la chaîne
   *
   * @param  string  $string       Chaîne de caractères
   * @param  string  $search       Chaine à rechercher
   * @param  string  $replacement  Chaine de remplacement
   * @param  boolean $noCase       (optional) Ne pas tenir compte de la casse (FALSE par défaut)
   * @return string                Chaîne de caractère modifiée
   */
  public static function replaceAll($string, $search, $replacement, $noCase = false)
  {
    if ($noCase) {
      return str_replace($search, $replacement, $string);
    } else {
      return str_ireplace($search, $replacement, $string);
    }
  }

  /**
   * Remplace la première occurence de la sous-chaîne dans la chaîne
   *
   * @param  string  $string       Chaîne de caractères
   * @param  string  $search       Chaine à rechercher
   * @param  string  $replacement  Chaine de remplacement
   * @param  boolean $noCase       (optional) Ne pas tenir compte de la casse (FALSE par défaut)
   * @return string                Chaîne de caractère modifiée
   */
  public static function replaceFirst($string, $search, $replacement, $noCase = false)
  {
    $search = static::replaceAll($search, '/', '\/');
    if ($noCase) {
      return preg_replace('/' . $search . '/i', $replacement, $string, 1);
    } else {
      return preg_replace('/' . $search . '/', $replacement, $string, 1);
    }
  }

  /**
   * Remplace la dernière occurence de la sous-chaîne dans la chaîne
   *
   * @param  string  $string       Chaîne de caractères
   * @param  string  $search       Chaine à rechercher
   * @param  string  $replacement  Chaine de remplacement
   * @param  boolean $noCase       (optional) Ne pas tenir compte de la casse (FALSE par défaut)
   * @return string                Chaîne de caractère modifiée
   */
  public static function replaceLast($string, $search, $replacement, $noCase = false)
  {
    if ($noCase) {
      $position = strripos($string, $search);
    } else {
      $position = strrpos($string, $search);
    }
    if ($position !== false) {
      return substr_replace($string, $replacement, $position, strlen($search));
    }
    return $string;
  }

  /**
   * Analyse la chaîne et remplace toutes les expressions qui correspondent à l'expression régulière fournie
   *
   * @param  string  $string       Chaîne de caractères
   * @param  string  $regex        Expression régulière
   * @param  string  $replacement  Chaîne de remplacement
   * @return string                Chaîne de caractère modifiée
   */
  public static function replaceAllMatches($string, $regex, $replacement)
  {
    return preg_replace($regex, $replacement, $string);
  }

  /**
   * Analyse la chaîne et remplace toutes lla première expressions qui correspond à l'expression régulière fournie
   *
   * @param  string  $string       Chaîne de caractères
   * @param  string  $regex        Expression régulière
   * @param  string  $replacement  Chaîne de remplacement
   * @return string                Chaîne de caractère modifiée
   */
  public static function replaceFirstMatch($string, $regex, $replacement)
  {
    return preg_replace($regex, $replacement, $string, 1);
  }

  /**
   * Met la chaîne en minuscules
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne en minuscules
   */
  public static function toLowerCase($string)
  {
    return strtolower($string);
  }

  /**
   * Met la chaîne en majuscules
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne en majuscules
   */
  public static function toUpperCase($string)
  {
    return strtoupper($string);
  }

  /**
   * Met le premier caractère de la chaîne en majuscule
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne avec le premier caractère en majuscule
   */
  public static function firstCarToUpperCase($string)
  {
    return ucfirst($string);
  }

  /**
   * Formate une chaîne en lui passant un tableau de correspondances.
   * Les mots clés sont à insérer sous la forme %cle%.
   * Le système va recherche les clés dans le tableau fourni correspondants aux mots clés détectés.
   *
   * @param  string  $string        Chaîne de caractères
   * @param  array   $replacements  Clés à remplacer (Tableau associatif obligatoirement)
   * @return string                 Chaîne formatée
   */
  public static function format($string, $replacements)
  {
    foreach ($replacements as $key => $value) {
      $string = str_replace('%'. $key .'%', $value, $string);
    }
    return $string;
  }

  /**
   * Effectue une césure d'une chaîne en respectant les mots
   *
   * @param  string  $string   Chaîne de caractères
   * @param  integer $length   Longueur de la ligne en nombre de caractères
   * @param  string  $cresure  (optional) Chaîne utilisée pour effectuer le retour à la ligne (balise BR par défaut)
   * @param  integer $height   (optional) Nombre maximal de lignes (-1 par défaut, c'est à dire pas de maximum)
   * @param  string  $suffix   (optional) Suffixe à afficher si le texte dépasse le nombre de lignes maximal.
   * @return string            Chaîne formatée
   */
  public static function wordWrap($string, $length, $cresure = '
', $height = -1, $suffix = '')
  {
    $string = static::removeHtmlTags($string);
    $string = wordwrap($string, $length, $cresure);
    $elements = static::explode($string, $cresure);
    if (count($elements) + 1 > $height && $height != -1) {
      $string = '';
      for ($i = 0; $i <= $height; $i++) {
        $string .= $elements[$i];
        if ($i < ($height)) {
          $string .= $cresure;
        } elseif ($i == ($height)) {
          $string .= $suffix;
        }
      }
    }
    return $string;
  }

  /**
   * Supprime les espaces blancs en début et fin de chaîne
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractère modifiée
   */
  public static function deleteWhiteSpaces($string)
  {
    return trim($string);
  }

  /**
   * Encode au format uuencode
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères encodée
   */
  public static function uuEncode($string)
  {
    return convert_uuencode($string);
  }

  /**
   * Décode du format uuencode
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères décodée
   */
  public static function uuDecode($string)
  {
    return convert_uudecode($string);
  }

  /**
   * Encode au format HTML
   *
   * @param  string  $string        Chaîne de caractères
   * @param  boolean $specialChars  (optional) Si TRUE, encode également les caractères spéciaux &"'<> (TRUE par défaut)
   * @return string                 Chaîne encodée
   */
  public static function htmlEncode($string, $specialChars = true)
  {
    if ($specialChars) {
      $string = htmlspecialchars($string);
    }
    return htmlentities($string);
  }

  /**
   * Décode une chaîne au format HTML
   *
   * @param  string  $string        Chaîne de caractères
   * @param  boolean $specialChars  (optional) Si TRUE, décode également les caractères spéciaux &"'<> (TRUE par défaut)
   * @return string                 Chaîne décodée
   */
  public static function htmlDecode($string, $specialChars = true)
  {
    if ($specialChars) {
      $string = htmlspecialchars_decode($string);
    }
    return html_entity_decode($string);
  }

  /**
   * Génère une valeur de hashage
   *
   * @param  string  $string     Chaîne de caractères
   * @param  string  $algorithm  (optional) Algorithme à utiliser (md5 par défaut)
   * @return string              Valeur de hashage
   */
  public static function hashCode($string, $algorithm = 'md5')
  {
    return hash($algorithm, $string);
  }

  /**
   * Génère une valeur de hashage avec une clé utilisée pour générer la variance HMAC de l'empreinte numérique.
   *
   * @param  string $string     Chaîne de caractères à hasher
   * @param  string $key        Clé de variance
   * @param  string $algorithm  (optional) Algorithme à utiliser (md5 par défaut)
   * @return string
   */
  public static function hmac($string, $key, $algorithm = 'md5')
  {
    return hash_hmac($algorithm, $string, $key);
  }

  /**
   * Supprime toutes les balises HTML
   *
   * @param  string  $string  Chaîne de caractère
   * @return string           Chaîne de caractère nettoyée
   */
  public static function removeHtmlTags($string)
  {
    return strip_tags($string);
  }

  /**
   * Nettoie un nom de fichier de tous les caractères spéciaux
   *
   * @param  string  $fileName  Chaîne de caractère
   * @return string             Chaîne de caractère nettoyée
   */
  public static function cleanFileName($fileName)
  {
    $fileNameParts = explode('.', $fileName);
    $extension = array_pop($fileNameParts);
    $fileName = implode($fileNameParts);
    return static::clean($fileName) .'.'. $extension;
  }

  /**
   * Nettoie la chaîne de caractère de tous les caractères spéciaux
   *
   * @param  string  $string  Chaîne de caractère
   * @return string           Chaîne de caractère nettoyée
   */
  public static function clean($string)
  {
    $string = static::removeHtmlTags($string);
    setlocale(LC_CTYPE, 'fr_FR.UTF-8');
    $string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
    $string = str_replace(' ', '-', $string);
    $string = strtolower($string);
    $string = trim($string, '-');
    $string = preg_replace('/[^\w-]/', '', $string);
    $string = preg_replace('/-+/', '-', $string);
    return $string;
  }

  /**
   * Encode la chaîne au format URL
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères encodée
   */
  public static function urlEncode($string)
  {
    return urlencode($string);
  }

  /**
   * Décode une chaîne au format Url
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractère décodée
   */
  public static function urlDecode($string)
  {
    return urldecode($string);
  }

  /**
   * Encode une chaîne ISO8859-1 au format utf8
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères encodée
   */
  public static function utf8Encode($string)
  {
    return utf8_encode($string);
  }

  /**
   * Encode une chaîne utf8 au format ISO8859-1
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères décodée
   */
  public static function utf8Decode($string)
  {
    return utf8_decode($string);
  }

  /**
   * Encode une chaîne en MIME base64
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères encodée
   */
  public static function base64Encode($string)
  {
    return base64_encode($string);
  }

  /**
   * Décode une chaîne en MIME base64
   *
   * @param  string  $string  Chaîne de caractères
   * @return string           Chaîne de caractères décodée
   */
  public static function base64Decode($string)
  {
    return base64_decode($string);
  }

  /**
   * Génère un lien mailto protégé
   *
   * @param  string $email  Adresse mail
   * @param  string $name   (optional) Nom du contact lié à l'adresse mail
   * @param  string $text   (optional) Texte à utiliser pour le lien
   * @return string
   */
  public static function protectEmailLink($email, $name = null, $text = null)
  {
    $email = preg_replace("/\"/", "\\\"", $email);
    if ($name == null) {
      $name = $email;
    }
    if ($text == null) {
      $text = $name;
    }
    $clear = sprintf('document.write(\'%s\')', $email, $text);
    $encrypted = '';
    for ($i = 0; $i < strlen($clear); $i++) {
      $encrypted .= '%'. bin2hex(substr($clear, $i, 1));
    }
    return sprintf('', $encrypted);
  }
}


<?php
/**
 * Class representing a HTTP response
 *
 * PHP version 5
 *
 * LICENSE
 *
 * This source file is subject to BSD 3-Clause License that is bundled
 * with this package in the file LICENSE and available at the URL
 * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
 *
 * @category  HTTP
 * @package   HTTP_Request2
 * @author    Alexey Borzov <avb@php.net>
 * @copyright 2008-2014 Alexey Borzov <avb@php.net>
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
 * @link      http://pear.php.net/package/HTTP_Request2
 */

/**
 * Exception class for HTTP_Request2 package
 */
require_once 'HTTP/Request2/Exception.php';

/**
 * Class representing a HTTP response
 *
 * The class is designed to be used in "streaming" scenario, building the
 * response as it is being received:
 * <code>
 * $statusLine = read_status_line();
 * $response = new HTTP_Request2_Response($statusLine);
 * do {
 *     $headerLine = read_header_line();
 *     $response->parseHeaderLine($headerLine);
 * } while ($headerLine != '');
 *
 * while ($chunk = read_body()) {
 *     $response->appendBody($chunk);
 * }
 *
 * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());
 * </code>
 *
 * @category HTTP
 * @package  HTTP_Request2
 * @author   Alexey Borzov <avb@php.net>
 * @license  http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
 * @version  Release: 2.2.1
 * @link     http://pear.php.net/package/HTTP_Request2
 * @link     http://tools.ietf.org/html/rfc2616#section-6
 */
class HTTP_Request2_Response
{
    /**
     * HTTP protocol version (e.g. 1.0, 1.1)
     * @var  string
     */
    protected $version;

    /**
     * Status code
     * @var  integer
     * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
     */
    protected $code;

    /**
     * Reason phrase
     * @var  string
     * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
     */
    protected $reasonPhrase;

    /**
     * Effective URL (may be different from original request URL in case of redirects)
     * @var  string
     */
    protected $effectiveUrl;

    /**
     * Associative array of response headers
     * @var  array
     */
    protected $headers = array();

    /**
     * Cookies set in the response
     * @var  array
     */
    protected $cookies = array();

    /**
     * Name of last header processed by parseHederLine()
     *
     * Used to handle the headers that span multiple lines
     *
     * @var  string
     */
    protected $lastHeader = null;

    /**
     * Response body
     * @var  string
     */
    protected $body = '';

    /**
     * Whether the body is still encoded by Content-Encoding
     *
     * cURL provides the decoded body to the callback; if we are reading from
     * socket the body is still gzipped / deflated
     *
     * @var  bool
     */
    protected $bodyEncoded;

    /**
     * Associative array of HTTP status code / reason phrase.
     *
     * @var  array
     * @link http://tools.ietf.org/html/rfc2616#section-10
     */
    protected static $phrases = array(

        // 1xx: Informational - Request received, continuing process
        100 => 'Continue',
        101 => 'Switching Protocols',

        // 2xx: Success - The action was successfully received, understood and
        // accepted
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // 3xx: Redirection - Further action must be taken in order to complete
        // the request
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',  // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',

        // 4xx: Client Error - The request contains bad syntax or cannot be
        // fulfilled
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',

        // 5xx: Server Error - The server failed to fulfill an apparently
        // valid request
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded',

    );

    /**
     * Returns the default reason phrase for the given code or all reason phrases
     *
     * @param int $code Response code
     *
     * @return string|array|null Default reason phrase for $code if $code is given
     *                           (null if no phrase is available), array of all
     *                           reason phrases if $code is null
     * @link   http://pear.php.net/bugs/18716
     */
    public static function getDefaultReasonPhrase($code = null)
    {
        if (null === $code) {
            return self::$phrases;
        } else {
            return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;
        }
    }

    /**
     * Constructor, parses the response status line
     *
     * @param string $statusLine   Response status line (e.g. "HTTP/1.1 200 OK")
     * @param bool   $bodyEncoded  Whether body is still encoded by Content-Encoding
     * @param string $effectiveUrl Effective URL of the response
     *
     * @throws   HTTP_Request2_MessageException if status line is invalid according to spec
     */
    public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)
    {
        if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
            throw new HTTP_Request2_MessageException(
                "Malformed response: {$statusLine}",
                HTTP_Request2_Exception::MALFORMED_RESPONSE
            );
        }
        $this->version      = $m[1];
        $this->code         = intval($m[2]);
        $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
        $this->bodyEncoded  = (bool)$bodyEncoded;
        $this->effectiveUrl = (string)$effectiveUrl;
    }

    /**
     * Parses the line from HTTP response filling $headers array
     *
     * The method should be called after reading the line from socket or receiving
     * it into cURL callback. Passing an empty string here indicates the end of
     * response headers and triggers additional processing, so be sure to pass an
     * empty string in the end.
     *
     * @param string $headerLine Line from HTTP response
     */
    public function parseHeaderLine($headerLine)
    {
        $headerLine = trim($headerLine, "\r\n");

        if ('' == $headerLine) {
            // empty string signals the end of headers, process the received ones
            if (!empty($this->headers['set-cookie'])) {
                $cookies = is_array($this->headers['set-cookie'])?
                           $this->headers['set-cookie']:
                           array($this->headers['set-cookie']);
                foreach ($cookies as $cookieString) {
                    $this->parseCookie($cookieString);
                }
                unset($this->headers['set-cookie']);
            }
            foreach (array_keys($this->headers) as $k) {
                if (is_array($this->headers[$k])) {
                    $this->headers[$k] = implode(', ', $this->headers[$k]);
                }
            }

        } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
            // string of the form header-name: header value
            $name  = strtolower($m[1]);
            $value = trim($m[2]);
            if (empty($this->headers[$name])) {
                $this->headers[$name] = $value;
            } else {
                if (!is_array($this->headers[$name])) {
                    $this->headers[$name] = array($this->headers[$name]);
                }
                $this->headers[$name][] = $value;
            }
            $this->lastHeader = $name;

        } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
            // continuation of a previous header
            if (!is_array($this->headers[$this->lastHeader])) {
                $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
            } else {
                $key = count($this->headers[$this->lastHeader]) - 1;
                $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
            }
        }
    }

    /**
     * Parses a Set-Cookie header to fill $cookies array
     *
     * @param string $cookieString value of Set-Cookie header
     *
     * @link     http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
     */
    protected function parseCookie($cookieString)
    {
        $cookie = array(
            'expires' => null,
            'domain'  => null,
            'path'    => null,
            'secure'  => false
        );

        if (!strpos($cookieString, ';')) {
            // Only a name=value pair
            $pos = strpos($cookieString, '=');
            $cookie['name']  = trim(substr($cookieString, 0, $pos));
            $cookie['value'] = trim(substr($cookieString, $pos + 1));

        } else {
            // Some optional parameters are supplied
            $elements = explode(';', $cookieString);
            $pos = strpos($elements[0], '=');
            $cookie['name']  = trim(substr($elements[0], 0, $pos));
            $cookie['value'] = trim(substr($elements[0], $pos + 1));

            for ($i = 1; $i < count($elements); $i++) {
                if (false === strpos($elements[$i], '=')) {
                    $elName  = trim($elements[$i]);
                    $elValue = null;
                } else {
                    list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
                }
                $elName = strtolower($elName);
                if ('secure' == $elName) {
                    $cookie['secure'] = true;
                } elseif ('expires' == $elName) {
                    $cookie['expires'] = str_replace('"', '', $elValue);
                } elseif ('path' == $elName || 'domain' == $elName) {
                    $cookie[$elName] = urldecode($elValue);
                } else {
                    $cookie[$elName] = $elValue;
                }
            }
        }
        $this->cookies[] = $cookie;
    }

    /**
     * Appends a string to the response body
     *
     * @param string $bodyChunk part of response body
     */
    public function appendBody($bodyChunk)
    {
        $this->body .= $bodyChunk;
    }

    /**
     * Returns the effective URL of the response
     *
     * This may be different from the request URL if redirects were followed.
     *
     * @return string
     * @link   http://pear.php.net/bugs/bug.php?id=18412
     */
    public function getEffectiveUrl()
    {
        return $this->effectiveUrl;
    }

    /**
     * Returns the status code
     *
     * @return   integer
     */
    public function getStatus()
    {
        return $this->code;
    }

    /**
     * Returns the reason phrase
     *
     * @return   string
     */
    public function getReasonPhrase()
    {
        return $this->reasonPhrase;
    }

    /**
     * Whether response is a redirect that can be automatically handled by HTTP_Request2
     *
     * @return   bool
     */
    public function isRedirect()
    {
        return in_array($this->code, array(300, 301, 302, 303, 307))
               && isset($this->headers['location']);
    }

    /**
     * Returns either the named header or all response headers
     *
     * @param string $headerName Name of header to return
     *
     * @return   string|array    Value of $headerName header (null if header is
     *                           not present), array of all response headers if
     *                           $headerName is null
     */
    public function getHeader($headerName = null)
    {
        if (null === $headerName) {
            return $this->headers;
        } else {
            $headerName = strtolower($headerName);
            return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
        }
    }

    /**
     * Returns cookies set in response
     *
     * @return   array
     */
    public function getCookies()
    {
        return $this->cookies;
    }

    /**
     * Returns the body of the response
     *
     * @return   string
     * @throws   HTTP_Request2_Exception if body cannot be decoded
     */
    public function getBody()
    {
        if (0 == strlen($this->body) || !$this->bodyEncoded
            || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
        ) {
            return $this->body;

        } else {
            if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
                $oldEncoding = mb_internal_encoding();
                mb_internal_encoding('8bit');
            }

            try {
                switch (strtolower($this->getHeader('content-encoding'))) {
                case 'gzip':
                    $decoded = self::decodeGzip($this->body);
                    break;
                case 'deflate':
                    $decoded = self::decodeDeflate($this->body);
                }
            } catch (Exception $e) {
            }

            if (!empty($oldEncoding)) {
                mb_internal_encoding($oldEncoding);
            }
            if (!empty($e)) {
                throw $e;
            }
            return $decoded;
        }
    }

    /**
     * Get the HTTP version of the response
     *
     * @return   string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Decodes the message-body encoded by gzip
     *
     * The real decoding work is done by gzinflate() built-in function, this
     * method only parses the header and checks data for compliance with
     * RFC 1952
     *
     * @param string $data gzip-encoded data
     *
     * @return   string  decoded data
     * @throws   HTTP_Request2_LogicException
     * @throws   HTTP_Request2_MessageException
     * @link     http://tools.ietf.org/html/rfc1952
     */
    public static function decodeGzip($data)
    {
        $length = strlen($data);
        // If it doesn't look like gzip-encoded data, don't bother
        if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
            return $data;
        }
        if (!function_exists('gzinflate')) {
            throw new HTTP_Request2_LogicException(
                'Unable to decode body: gzip extension not available',
                HTTP_Request2_Exception::MISCONFIGURATION
            );
        }
        $method = ord(substr($data, 2, 1));
        if (8 != $method) {
            throw new HTTP_Request2_MessageException(
                'Error parsing gzip header: unknown compression method',
                HTTP_Request2_Exception::DECODE_ERROR
            );
        }
        $flags = ord(substr($data, 3, 1));
        if ($flags & 224) {
            throw new HTTP_Request2_MessageException(
                'Error parsing gzip header: reserved bits are set',
                HTTP_Request2_Exception::DECODE_ERROR
            );
        }

        // header is 10 bytes minimum. may be longer, though.
        $headerLength = 10;
        // extra fields, need to skip 'em
        if ($flags & 4) {
            if ($length - $headerLength - 2 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $extraLength = unpack('v', substr($data, 10, 2));
            if ($length - $headerLength - 2 - $extraLength[1] < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $headerLength += $extraLength[1] + 2;
        }
        // file name, need to skip that
        if ($flags & 8) {
            if ($length - $headerLength - 1 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $filenameLength = strpos(substr($data, $headerLength), chr(0));
            if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $headerLength += $filenameLength + 1;
        }
        // comment, need to skip that also
        if ($flags & 16) {
            if ($length - $headerLength - 1 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $commentLength = strpos(substr($data, $headerLength), chr(0));
            if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $headerLength += $commentLength + 1;
        }
        // have a CRC for header. let's check
        if ($flags & 2) {
            if ($length - $headerLength - 2 < 8) {
                throw new HTTP_Request2_MessageException(
                    'Error parsing gzip header: data too short',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $crcReal   = 0xffff & crc32(substr($data, 0, $headerLength));
            $crcStored = unpack('v', substr($data, $headerLength, 2));
            if ($crcReal != $crcStored[1]) {
                throw new HTTP_Request2_MessageException(
                    'Header CRC check failed',
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            }
            $headerLength += 2;
        }
        // unpacked data CRC and size at the end of encoded data
        $tmp = unpack('V2', substr($data, -8));
        $dataCrc  = $tmp[1];
        $dataSize = $tmp[2];

        // finally, call the gzinflate() function
        // don't pass $dataSize to gzinflate, see bugs #13135, #14370
        $unpacked = gzinflate(substr($data, $headerLength, -8));
        if (false === $unpacked) {
            throw new HTTP_Request2_MessageException(
                'gzinflate() call failed',
                HTTP_Request2_Exception::DECODE_ERROR
            );
        } elseif ($dataSize != strlen($unpacked)) {
            throw new HTTP_Request2_MessageException(
                'Data size check failed',
                HTTP_Request2_Exception::DECODE_ERROR
            );
        } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
            throw new HTTP_Request2_Exception(
                'Data CRC check failed',
                HTTP_Request2_Exception::DECODE_ERROR
            );
        }
        return $unpacked;
    }

    /**
     * Decodes the message-body encoded by deflate
     *
     * @param string $data deflate-encoded data
     *
     * @return   string  decoded data
     * @throws   HTTP_Request2_LogicException
     */
    public static function decodeDeflate($data)
    {
        if (!function_exists('gzuncompress')) {
            throw new HTTP_Request2_LogicException(
                'Unable to decode body: gzip extension not available',
                HTTP_Request2_Exception::MISCONFIGURATION
            );
        }
        // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
        // while many applications send raw deflate stream from RFC 1951.
        // We should check for presence of zlib header and use gzuncompress() or
        // gzinflate() as needed. See bug #15305
        $header = unpack('n', substr($data, 0, 2));
        return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
    }
}
?>


<?php
/**
 * This file is a part of CSCFA project.
 *
 * PHP version 5.5
 *
 * @category Object
 * @package  CscfaCacheSystemBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
namespace Cscfa\Bundle\CacheSystemBundle\Object;

use Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface;
use Symfony\Component\HttpKernel\Kernel;

/**
 * Cache object
 *
 * This object manage the cache
 * system
 *
 * @category Object
 * @package  CscfaCacheSystemBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
class Cache
{
    /**
     * Provider
     *
     * The cache provider
     *
     * @var CacheProviderInterface
     */
    protected $provider;

    /**
     * Set arguments
     *
     * Initialyze the cache object
     *
     * @param string $providerClass - the provider class
     */
    public function setArguments(Kernel $kernel, $config){

        $provider = $config['provider'];
        $prefix = $config['prefix'];
        $timestamp = $config['timestamp'];

        $this->setProvider(new $provider());
        $this->provider->setKernel($kernel);
        $this->provider->setPrefix($prefix);
        $this->provider->setTimestamp($timestamp);
    }

    /**
     * Get provider
     *
     * Return the cache provider
     *
     * @return CacheProviderInterface - the cache provider
     */
    public function getProvider()
    {
        return $this->provider;
    }

    /**
     * Set provider
     *
     * Set the cache provider
     *
     * @param CacheProviderInterface $provider - the cache provider
     *
     * @return Cache - the current instance
     */
    protected function setProvider(CacheProviderInterface $provider)
    {
        $this->provider = $provider;
        return $this;
    }
}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Caster
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\CollectionHelper\Manager;

// @codingStandardsIgnoreStart
use CSDT\CollectionsBundle\CollectionHelper\HelperInterface\ArrayCasterManagerInterface;
use CSDT\CollectionsBundle\Collections\ValueSet;
use CSDT\CollectionsBundle\CollectionHelper\HelperInterface\ArrayCasterInterface;
// @codingStandardsIgnoreEnd

/**
 * Array caster manager
 *
 * This class is used to process a cast from
 * array to any collection that registered a
 * caster.
 *
 * @category Caster
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
class ArrayCasterManager implements ArrayCasterManagerInterface
{

    /**
     * Casters
     *
     * This property store the registered casters.
     *
     * @var ValueSet
     */
    protected $casters;

    /**
     * Construct
     *
     * The default ArrayCasterManager
     * constructor
     *
     * @return void
     */
    public function __construct()
    {
        $this->casters = new ValueSet();
    }

    /**
     * Process
     *
     * This method search the caster able to
     * process the given array. It thrown an
     * exception if no one is stored.
     *
     * @param array  $array          The array to process
     * @param string $collectionName The collection class result
     *
     * @throws \ParseError if no one caster is able to parse the array
     * @return CollectionInterface
     */
    public function process(array $array, $collectionName)
    {
        foreach ($this->casters as $caster) {
            if ($caster instanceof ArrayCasterInterface) {
                if ($caster->support($collectionName)) {
                    return $caster->toCollection($array, $collectionName);
                }
            }
        }

        throw new \ParseError(
            sprintf("No caster found for %s type", $collectionName)
        );
    }

    /**
     * Add caster
     *
     * This method allow to store an ArrayCaster
     * instance into the manager.
     *
     * @param ArrayCasterInterface $caster The ArrayCaster to store
     *
     * @return ArrayCasterManagerInterface
     */
    public function addCaster(ArrayCasterInterface $caster)
    {
        $this->casters->add($caster);

        return $this;
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\ObjectStore\Type;

use Ruwork\ObjectStore\Configurator\StoreConfiguratorInterface;
use Ruwork\ObjectStore\Normalizer\SymfonyNormalizer;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class SymfonyNormalizerStoreType implements StoreTypeInterface
{
    private $normalizer;
    private $denormalizer;

    public function __construct(NormalizerInterface $normalizer, DenormalizerInterface $denormalizer)
    {
        $this->normalizer = $normalizer;
        $this->denormalizer = $denormalizer;
    }

    /**
     * {@inheritdoc}
     */
    public static function getRequiredTypes(): iterable
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'normalizer_format' => null,
                'normalization_context' => [],
                'denormalization_context' => [],
            ])
            ->setAllowedTypes('normalizer_format', ['null', 'string'])
            ->setAllowedTypes('normalization_context', 'array')
            ->setAllowedTypes('denormalization_context', 'array');
    }

    /**
     * {@inheritdoc}
     */
    public function configureStore(StoreConfiguratorInterface $configurator, array $options): void
    {
        $configurator->setNormalizer(new SymfonyNormalizer(
            $this->normalizer,
            $this->denormalizer,
            $options['normalization_context'],
            $options['denormalization_context'],
            $options['normalizer_format']
        ));
    }
}


<?php

namespace Colorium\Orm\Mapper;

use Colorium\Orm\Contract\BuilderInterface;
use Colorium\Orm\SafePDO;
use Colorium\Orm\SQL;

class Builder extends SafePDO implements BuilderInterface
{

    /** @var Entity */
    protected $entity;

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

    /**
     * Query constructor
     *
     * @param Entity $entity
     * @param \PDO $pdo
     */
    public function __construct(Entity $entity, \PDO $pdo)
    {
        parent::__construct($pdo);
        $this->entity = $entity;
    }

    /**
     * Check if entity exists in source
     *
     * @return bool
     */
    public function exists()
    {
        try {
            $sql = SQL::tableExists($this->entity->name);
            return $this->execute($sql);
        }
        catch(\PDOException $e) {
            return false;
        }
    }

    /**
     * Create entity
     *
     * @return bool
     */
    public function create()
    {
        $opts = [];
        foreach($this->entity->fields as $field) {
            $opts[$field->name] = get_object_vars($field);
        }

        $sql = SQL::createTable($this->entity->name, $opts);
        return $this->execute($sql);
    }

    /**
     * Wipe entitys
     *
     * @return bool
     */
    public function wipe()
    {
        $sql = SQL::dropTable($this->entity->name);
        return $this->execute($sql);
    }

    /**
     * Clear entity data
     *
     * @return bool
     */
    public function clear()
    {
        $sql = SQL::truncateTable($this->entity->name);
        return $this->execute($sql);
    }

}


<?php
/**
 * Connections
 * User: moyo
 * Date: 09/08/2017
 * Time: 6:00 PM
 */

namespace Carno\Pool;

use function Carno\Coroutine\go;
use function Carno\Coroutine\race;
use function Carno\Coroutine\timeout;
use Carno\Pool\Chips\CCPolicy;
use Carno\Pool\Exception\SelectWaitOverflowException;
use Carno\Pool\Exception\SelectWaitTimeoutException;
use Carno\Pool\Features\IdleRecycling;
use Carno\Promise\Promise;
use Carno\Promise\Promised;
use SplQueue;
use SplStack;
use Throwable;

class Connections
{
    use CCPolicy;

    /**
     * @var Pool
     */
    private $pool = null;

    /**
     * @var Options
     */
    private $options = null;

    /**
     * @var Connector
     */
    private $connector = null;

    /**
     * @var IdleRecycling
     */
    private $recycling = null;

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

    /**
     * @var SplStack
     */
    private $staIdling = null;

    /**
     * @var Poolable[]
     */
    private $staBusying = [];

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

    /**
     * @var SplQueue
     */
    private $getWaitQ = null;

    /**
     * @var Promised[]
     */
    private $liveGetQ = [];

    /**
     * @var bool
     */
    private $exiting = false;

    /**
     * Connections constructor.
     * @param Pool $pool
     * @param Options $options
     * @param Connector $connector
     */
    public function __construct(
        Pool $pool,
        Options $options,
        Connector $connector
    ) {
        $this->pool = $pool;
        $this->options = $options;
        $this->connector = $connector;

        $this->staIdling = new SplStack;
        $this->getWaitQ = new SplQueue;

        $this->resizing($this->options->initial, 'initialize');
    }

    /**
     */
    public function cleanup() : void
    {
        $this->pool = null;
        $this->options = null;

        $this->getWaitQ = null;

        $this->connector->cleanup();
    }

    /**
     * @param IdleRecycling $recycling
     */
    public function setIRecycling(IdleRecycling $recycling) : void
    {
        $this->recycling = $recycling;
    }

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

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

    /**
     * @return int
     */
    public function cWaitCount() : int
    {
        return $this->getWaitQ ? $this->getWaitQ->count() : 0;
    }

    /**
     * @deprecated
     * @return Promised|Poolable
     */
    public function getLived()
    {
        if (!$this->staIdling->isEmpty()) {
            return $this->staIdling->current();
        } elseif ($this->staBusying) {
            return current($this->staBusying);
        } else {
            return $this->liveGetQ[] = Promise::deferred();
        }
    }

    /**
     * @return SplStack|Poolable[]
     */
    public function getIdles() : SplStack
    {
        return $this->staIdling;
    }

    /**
     * @param bool $wait
     * @param bool $work
     * @return Promised|Poolable
     */
    public function getIdled(bool $wait = true, bool $work = true)
    {
        if ($this->staIdling->isEmpty()) {
            if ($wait) {
                if ($this->getWaitQ->count() > $this->options->getWaitQMax) {
                    throw new SelectWaitOverflowException($this->connector->identify());
                }

                $this->getWaitQ->enqueue($waiting = Promise::deferred());

                $this->ccDecision(
                    $this->options,
                    $this->connector->identify(),
                    $this->cIdleCount(),
                    $this->cBusyCount(),
                    $this->cWaitCount()
                );

                return race(
                    $waiting,
                    timeout(
                        $this->options->getWaitTimeout,
                        SelectWaitTimeoutException::class,
                        $this->connector->identify()
                    )
                );
            }

            return null;
        }

        return $this->setBusying(null, $work);
    }

    /**
     * @param Poolable $conn
     */
    public function putIdled(Poolable $conn) : void
    {
        /**
         * @var Promised $wait
         */

        // checking in liveGetQ
        while ($this->liveGetQ && null !== $wait = array_pop($this->liveGetQ)) {
            $wait->pended() && $wait->resolve($conn);
        }

        // checking in getWaitQ
        while (($this->getWaitQ ?! $this->getWaitQ->isEmpty() : false) && $wait = $this->getWaitQ->dequeue()) {
            if ($wait->pended()) {
                $wait->resolve($this->setBusying($conn));
                return;
            }
        }

        // finally set idle
        $this->setIdling($conn);

        // check exiting
        $this->exiting && $conn->destroy();
    }

    /**
     * @param Poolable $conn
     */
    public function released(Poolable $conn) : void
    {
        $hit = false;

        $cid = $conn->cid();

        // searching in "busying" stack
        if (isset($this->staBusying[$cid])) {
            unset($this->staBusying[$cid]);
            $this->setClosing($conn);
            $hit = true;
        }

        // searching in "idling" stack
        $hit || $this->removeIdling($conn);

        // finally checking conn state
        $this->checking();
    }

    /**
     * @param bool $forced
     * @param string $reason
     */
    public function exit(bool $forced = true, string $reason = 'exiting') : void
    {
        $this->exiting = true;
        $this->resizing(0, $reason, $forced);
        $this->checking();
    }

    /**
     * conn sta checking
     */
    private function checking() : void
    {
        $cleared = ! ($this->cIdleCount() + $this->cBusyCount());

        if ($this->exiting) {
            if ($this->pool && ($closed = $this->pool->closed())->pended() && $cleared) {
                $closed->resolve();
            }
            return;
        }

        $cleared && $this->resizing(
            max(
                1,
                $this->options->initial,
                min($this->getWaitQ->count(), $this->options->maxIdle)
            ),
            'minimum-scaling'
        );
    }

    /**
     * @param int $target
     * @param string $reason
     * @param bool $forced
     * @return int
     */
    public function resizing(int $target, string $reason = 'none', bool $forced = false) : int
    {
        $busySize = $this->cBusyCount();
        $idleSize = $this->cIdleCount();

        if ($busySize + $idleSize < $target && !$this->rsExpanding) {
            logger('pool')->debug(
                'Expanding',
                [
                    'id' => $this->connector->identify(),
                    'idle' => $idleSize,
                    'busy' => $busySize,
                    'target' => $target,
                    'reason' => $reason,
                ]
            );
            $this->rsExpanding = $expandSize = $target - $busySize - $idleSize;
            while ($expandSize -- > 0) {
                go(function () {
                    try {
                        /**
                         * @var Poolable $poolable
                         */
                        $poolable = yield $this->connector->created();
                        yield $poolable->connect();
                        $poolable->cid(sprintf('c-%d', ++ $this->connIDA));
                        $this->putIdled($poolable);
                    } catch (Throwable $e) {
                        logger('pool')->warning(
                            'Connecting failed',
                            [
                                'id' => $this->connector->identify(),
                                'error' => sprintf('#%d->%s::%s', $e->getCode(), get_class($e), $e->getMessage()),
                            ]
                        );
                    }
                    $this->rsExpanding --;
                });
            }
            return $expandSize;
        } elseif ($busySize + $idleSize > $target) {
            logger('pool')->debug(
                'Shrinking',
                [
                    'id' => $this->connector->identify(),
                    'idle' => $idleSize,
                    'busy' => $busySize,
                    'target' => $target,
                    'reason' => $reason,
                ]
            );
            $shrinkSize = ($busySize + $idleSize) - $target;
            while ($shrinkSize -- > 0) {
                if ($this->staIdling->count() > 0) {
                    if ($this->removeIdling(null, function ($_, Poolable $found) use ($forced) {
                        if (($this->recycling && $this->recycling->idling($found->cid())) || $forced) {
                            return true;
                        }
                        return false;
                    })) {
                        // removed ... checking next
                        continue;
                    } else {
                        // give up shrinking if all idles conn not accord
                        logger('pool')->debug('Idles conn not according', ['id' => $this->connector->identify()]);
                        break;
                    }
                }
                ($closer = Promise::deferred())->then(function (Poolable $conn) {
                    $this->setClosing($conn);
                });
                ($got = array_shift($this->staBusying)) && $got->schedule(Poolable::RELEASED, $closer);
            }
            return - $shrinkSize;
        }

        return 0;
    }

    /**
     * @param Poolable $conn
     * @param bool $work
     * @return Poolable
     */
    private function setBusying(Poolable $conn = null, bool $work = true) : Poolable
    {
        is_null($conn) && $conn = $this->staIdling->shift();

        $cid = $conn->cid();

        if ($this->recycling && $work) {
            $this->recycling->busying($cid);
        }

        return $this->staBusying[$cid] = $conn;
    }

    /**
     * @param Poolable $conn
     */
    private function setIdling(Poolable $conn) : void
    {
        $cid = $conn->cid();

        if (isset($this->staBusying[$cid])) {
            unset($this->staBusying[$cid]);
        }

        $this->staIdling->unshift($conn);
    }

    /**
     * @param Poolable $conn
     */
    private function setClosing(Poolable $conn) : void
    {
        $conn->closed()->pended() && $conn->close();
    }

    /**
     * @param Poolable $any
     * @param callable $matcher
     * @param bool $close
     * @return bool
     */
    private function removeIdling(Poolable $any = null, callable $matcher = null, bool $close = true) : bool
    {
        if ($this->staIdling->isEmpty()) {
            return false;
        }

        if (is_null($matcher)) {
            $matcher = static function (Poolable $present, Poolable $found) {
                return $present->cid() === $found->cid();
            };
        }

        $searched = 0;
        $connections = $this->staIdling->count();

        while ($searched ++ < $connections) {
            $conn = $this->staIdling->pop();
            if ($matcher($any, $conn)) {
                $close && $this->setClosing($conn);
                return true;
            } else {
                $this->staIdling->unshift($conn);
            }
        }

        return false;
    }
}


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Http;

use Valkyrja\Support\Collection;

/**
 * Class Server.
 *
 * @author Melech Mizrachi
 */
class Server extends Collection
{
    /**
     * Special HTTP headers that do not have the "HTTP_" prefix.
     *
     * @var array
     */
    public const SPECIAL_HEADERS = [
        'CONTENT_TYPE',
        'CONTENT_LENGTH',
        'PHP_AUTH_USER',
        'PHP_AUTH_PW',
        'PHP_AUTH_DIGEST',
        'AUTH_TYPE',
    ];

    /**
     * Get all headers from server.
     *
     * @return array
     */
    public function getHeaders(): array
    {
        $headers        = [];
        $specialHeaders = self::SPECIAL_HEADERS;

        foreach ($this->collection as $key => $value) {
            if (
                \in_array($key, $specialHeaders, true)
                || 0 === strpos($key, 'HTTP_')
            ) {
                $headers[$this->getHeaderName($key)] = $value;
            }
        }

        return $headers;
    }

    /**
     * Get the correct HTTP header name.
     *
     * @param string $header
     *
     * @return string
     */
    protected function getHeaderName($header): string
    {
        if (0 === strpos($header, 'HTTP_')) {
            $header = substr($header, 5);
        }

        $header =
            str_replace(
                ' ',
                '-',
                ucwords(str_replace('_', ' ', strtolower($header)))
            );

        return $header;
    }
}


<?php
/**
 * OpenWebPresence Support Library - openwebpresence.com
 *
 * @copyright 2001 - 2017, Brian Tafoya.
 * @package   OwpBaseFramework
 * @author    Brian Tafoya <btafoya@briantafoya.com>
 * @version   1.0
 * @license   MIT
 * @license   https://opensource.org/licenses/MIT The MIT License
 * @category  OpenWebPresence_Support_Library
 * @link      http://openwebpresence.com OpenWebPresence
 *
 * Copyright (c) 2017, Brian Tafoya
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * This class is the glue that binds all of the Open Web Presence functionality together.
 * It acts as the controller, logic, and view handler without extreme complexity of an entire MVC framework.
 */
class OwpBaseFramework
{
    /**
     * @var object $actionsConfig Theme specific actions configuration
     */
    public $actionsConfig;

    /**
     * @var string $actualAction Action finally processed after permissions are verified
     */
    public $actualAction;

    /**
     * @var string $current_web_root The current web root
     */
    public $current_web_root;

    /**
     * @var object $ezSqlDB Database object
     */
    public $ezSqlDB;

    /**
     * @var object $frameworkObject Framework object
     */
    public $frameworkObject;

    /**
     * @var array $LoadedClasses Object holder for dynamically loaded classes
     */
    public $LoadedClasses = array();

    /**
     * @var object $PhpConsole Phpconsole object
     */
    public $PhpConsole;

    /**
     * @var string $requested_action The user action requested
     */
    public $requested_action;

    /**
     * @var string $root_path The app root path
     */
    public $root_path;

    /**
     * @var string $THEME The app theme
     */
    public $THEME;

    /**
     * @var object $userClass The user object
     */
    public $userClass;

    /**
     * @var string $uuid The request's uuid
     */
    public $uuid;

    /**
     * Constructor
     *
     * @method void __construct()
     * @access public
     * @param  object $frameworkObject Data and method oject created by the OwpFramework.
     * @global string $root_path        The app root file path.
     * @global string $current_web_root The current web root.
     * @global object $PhpConsole       PhpConsole debugger object.
     * @uses   OwpFramework
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __construct()
    {
        $actionsConfig = null;

        $frameworkObject = OwpFramework::$frameworkObject;

        $this->frameworkObject = $frameworkObject;
        $this->ezSqlDB = (object)$frameworkObject["ezSqlDB"];
        $this->current_web_root = (string)CURRENT_WEB_ROOT;
        $this->root_path = (string)ROOT_PATH;
        $this->requested_action = (string)$frameworkObject["frameworkVariables"]["requested_action"];
        $this->uuid = (string)$frameworkObject["frameworkVariables"]["uuid"];
        $this->userClass = (object)$frameworkObject["userClass"];
        $this->THEME = (string)$frameworkObject["frameworkVariables"]["theme"];
        $this->actionsConfig = (array)$frameworkObject["actionsConfig"];
        $this->actualAction = $this->requested_action;
    }

    /**
     * action() Triggers the framework logic.
     *
     * @method void action()
     * @access public
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function action()
    {
        switch($this->requested_action) {
        default:
            $hasPermission = $this->checkActionPermissions($this->requested_action);
            $this->actualAction = ($hasPermission?$this->requested_action:$this->frameworkObject["frameworkVariables"]["default_action"]);

            $this->processAction($this->actualAction);
            break;
        case "ajaxDefault":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes","default","lib","OwpAjaxUdf.inc.php"));
            break;
        case "jsAssetsDefault":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes","default","lib","OwpjsAssets.inc.php"));
            break;
        case "cssAssetsDefault":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes","default","lib","OwpcssAssets.inc.php"));
            break;
        case "ajax":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes",$this->THEME,"lib","OwpAjaxUdf.inc.php"));
            $OwpAjaxUdf = new OwpAjaxUdf();
            $OwpAjaxUdf->processAction($this->frameworkObject);
            break;
        case "jsAssets":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes",$this->THEME,"lib","OwpjsAssets.inc.php"));
            break;
        case "cssAssets":
            include $this->root_path.join(DIRECTORY_SEPARATOR, array("app","themes",$this->THEME,"lib","OwpcssAssets.inc.php"));
            break;
        }
    }

    /**
     * checkActionPermissions()
     *
     * @method checkActionPermissions() Returns action data
     * @param  $action
     * @return boolean
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    private function checkActionPermissions($action)
    {
        $getActionData = $this->getActionData($action);

        if(!(int)$getActionData["permissions"]["isAdmin"] && !(int)$getActionData["permissions"]["isUser"]) {
            return true;
        }

        if((boolean)$this->userClass->isLoggedIn()) {
            if((boolean)$this->userClass->isAdmin() && (int)$getActionData["permissions"]["isAdmin"]) {
                return true;
            } else {
                return ((int)$getActionData["permissions"]["isUser"]?true:false);
            }
        } else {
            return false;
        }
    }

    /**
     * getActionData()
     *
     * @method getActionData() Returns action data
     * @param  $action
     * @return mixed
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    private function getActionData($action)
    {
        return (isset($this->actionsConfig[$action])?$this->actionsConfig[$action]:false);
    }

    /**
     * processAction()
     *
     * @method void processAction() Process the framework action.
     * @access public
     * @param  string $action
     * @throws Exception Include does not exist.
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function processAction($action)
    {
        $actionData = $this->getActionData($action);

        if(!$actionData) {
            $actionData = $this->getActionData("404");
        }

        $mod_includes = array();
        $mod_includes[] = $this->root_path . join(DIRECTORY_SEPARATOR, array('app', 'themes', $_ENV["THEME"], 'lib', "OwpFunctions.inc.php"));

        if($actionData && $actionData["mod"]) {
            $mod_includes = array_merge($mod_includes, $actionData["mod"]);
        }

        if($mod_includes) {
            foreach($mod_includes as $mi) {
                if(file_exists($mi)) {
                    $classes = OwpSupportMethods::file_get_php_classes($mi);
                    include $mi;
                    foreach($classes as $class_name) {
                        $this->LoadedClasses[$class_name] = new $class_name($this->frameworkObject);
                    }
                } else {
                    throw new Exception("Mod include " . $mi . " not found!", 911);
                }
            }
        }

        $view_includes = array();
        if($actionData && $actionData["view"]) {
            $view_includes = array_merge($view_includes, $actionData["view"]);
        }

        if($view_includes) { foreach($view_includes as $vi) {
                if(file_exists($vi)) {
                    include $vi;
                } else {
                    throw new Exception("View include " . $vi . " not found!", 911);
                }
        }
        }
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Library\StorageEngine\DatabaseDriver;

/**
 * Any database driver must extend this abstract class
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
abstract class AbstractDatabaseDriver
{

// ------------------------
// Statics
// ------------------------

    public static $DBADAPTER_ASSOC = null;

    public static $DBADAPTER_NUM = null;

    public static $DBADAPTER_BOTH = null;

// ------------------------
// Constants build
// ------------------------

    /**
     * Constants constructor
     *
     * @param array $statics_map An array defineding every class'statics value
     */
    protected function _buildStatics(array $statics_map)
    {
        // assoc
        if (isset($statics_map['assoc'])) {
            self::$DBADAPTER_ASSOC = $statics_map['assoc'];
        } else {
            throw new \InvalidArgumentException('You must defined the "assoc" constant value (as a static property) for a database adapter!');
        }

        // num
        if (isset($statics_map['num'])) {
            self::$DBADAPTER_NUM = $statics_map['num'];
        } else {
            throw new \InvalidArgumentException('You must defined the "num" constant value (as a static property) for a database adapter!');
        }

        // both
        if (isset($statics_map['both'])) {
            self::$DBADAPTER_BOTH = $statics_map['both'];
        } else {
            throw new \InvalidArgumentException('You must defined the "both" constant value (as a static property) for a database adapter!');
        }
    }

    /**
     * Force the adapter classes to build a "_loadStatics()" method to execute the "_buildStatics()" method above
     */
    abstract protected function _loadStatics();

}

// Endfile


<?php

/*
 * This file is part of the Valkyrja framework.
 *
 * (c) Melech Mizrachi
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Valkyrja\Console\Output;

use Valkyrja\Application;
use Valkyrja\Console\Enums\OutputStyle;
use Valkyrja\Support\Providers\Provides;

/**
 * Class NativeOutput.
 *
 * @author Melech Mizrachi
 */
class NativeOutput implements Output
{
    use Provides;

    /**
     * The formatter.
     *
     * @var \Valkyrja\Console\Output\OutputFormatter
     */
    protected $formatter;

    /**
     * Output constructor.
     *
     * @param OutputFormatter $formatter The output formatter
     */
    public function __construct(OutputFormatter $formatter)
    {
        $this->formatter = $formatter;
    }

    /**
     * Get the formatter.
     *
     * @return \Valkyrja\Console\Output\OutputFormatter
     */
    public function formatter(): OutputFormatter
    {
        return $this->formatter;
    }

    /**
     * Set the formatter.
     *
     * @param OutputFormatter $formatter
     *
     * @return void
     */
    public function setFormatter(OutputFormatter $formatter): void
    {
        $this->formatter = $formatter;
    }

    /**
     * Write messages to the console.
     *
     * @param array       $messages    The messages
     * @param bool        $newLine     [optional] Whether to use new lines
     *                                 between each message
     * @param OutputStyle $outputStyle [optional] The output style to use
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    public function write(array $messages, bool $newLine = null, OutputStyle $outputStyle = null): void
    {
        foreach ($messages as $message) {
            $this->writeMessage($message, $newLine, $outputStyle);
        }
    }

    /**
     * Write a message to the console.
     *
     * @param string      $message     The message
     * @param bool        $newLine     [optional] Whether to use new lines
     *                                 between each message
     * @param OutputStyle $outputStyle [optional] The output style to use
     *
     * @throws \InvalidArgumentException
     *
     * @return void
     */
    public function writeMessage(string $message, bool $newLine = null, OutputStyle $outputStyle = null): void
    {
        $newLine         = $newLine ?? false;
        $outputStyleType =
            $outputStyle ? $outputStyle->getValue() : OutputStyle::NORMAL;

        switch ($outputStyleType) {
            case OutputStyle::NORMAL:
                $message = $this->formatter->format($message);
                break;
            case OutputStyle::RAW:
                break;
            case OutputStyle::PLAIN:
                $message = strip_tags($this->formatter->format($message));
                break;
        }

        $this->writeOut($message, $newLine);
    }

    /**
     * Write a message out to the console.
     *
     * @param string $message
     * @param bool   $newLine
     *
     * @return void
     */
    protected function writeOut(string $message, bool $newLine): void
    {
        if (config()['console']['quiet'] || input()->hasOption('--quiet')) {
            return;
        }

        echo $message;

        if ($newLine) {
            echo PHP_EOL;
        }
    }

    /**
     * The items provided by this provider.
     *
     * @return array
     */
    public static function provides(): array
    {
        return [
            Output::class,
        ];
    }

    /**
     * Publish the provider.
     *
     * @param Application $app The application
     *
     * @return void
     */
    public static function publish(Application $app): void
    {
        $app->container()->singleton(
            Output::class,
            new static(
                $app->container()->getSingleton(OutputFormatter::class)
            )
        );
    }
}