<?php
/**
 * This file is a part of CSCFA project.
 *
 * PHP version 5.5
 *
 * @category Provider
 * @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\provider;

use Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Cscfa\Bundle\CacheSystemBundle\Object\Element\CacheCollection;
use Symfony\Component\Serializer\Exception\MappingException;
use Cscfa\Bundle\CacheSystemBundle\Object\DirectoryException;
use Symfony\Component\HttpFoundation\File\Exception\FileException;

/**
 * FileSystemCache provider
 *
 * This provider allow to manage
 * the cache on filesystem
 *
 * @category Provider
 * @package  CscfaCacheSystemBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
class FileSystemCache implements CacheProviderInterface
{

    /**
     * Cache directory
     *
     * The filesystem directory
     * to use to manage cache
     *
     * @var string
     */
    protected $cacheDir;

    /**
     * Prefix
     *
     * The filesystem cache
     * directory prefix to
     * use to manage cache
     *
     * @var string
     */
    protected $prefix;

    /**
     * Timestamp
     *
     * The cache max
     * timestamp range
     *
     * @var integer
     */
    protected $timestamp;

    /**
     * Set kerrnel
     *
     * Set the application
     * kernel
     *
     * @param Kernel $kernel - the application kernel
     *
     * @return CacheProviderInterface
     *
     * @see \Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface::setKernel()
     */
    public function setKernel(Kernel $kernel)
    {
        $this->cacheDir = $kernel->getCacheDir() . '/';

        return $this;
    }

    /**
     * Set prefix
     *
     * Set the cache prefix
     *
     * @param string $prefix - the prefix
     *
     * @return CacheProviderInterface
     *
     * @see \Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface::setPrefix()
     */
    public function setPrefix($prefix)
    {
        $this->prefix = $prefix;

        return $this;
    }

    /**
     * Set timestamp
     *
     * Set the cache max
     * timestamp range
     *
     * @param integer $timestamp - the timestamp range
     *
     * @return CacheProviderInterface
     *
     * @see \Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface::setTimestamp()
     */
    public function setTimestamp($timestamp){
        $this->timestamp = $timestamp;

        return $this;
    }

    /**
     * Get
     *
     * Return a cache
     * element
     *
     * @param string $id - the cache element name
     *
     * @return CacheCollection - the CacheCollection element
     *
     * @see \Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface::get()
     */
    public function get($id)
    {
        if ($this->accessible($id)) {
            $collection = new CacheCollection();
            $collection->setTimestampOffset($this->timestamp);
            $collection->unserialize(file_get_contents($this->getPath($id)));

            if ($collection->getId() !== $id) {
                throw new MappingException(sprintf("The file %s does not containt the right cache element", $this->getPath($id)), 500);
            } else {
                return $collection;
            }
        } else {
            if (! $this->exist($id)) {
                return null;
            } else {

                $read = $this->readable($id);
                $write = $this->writable($id);

                if ($read && ! $write) {
                    throw new AccessDeniedException(sprintf("The file %s is on read only state", $this->getPath($id)), 403);
                } else if (! $read && ! $write) {
                    throw new AccessDeniedException(sprintf("The file %s cannot be read or write", $this->getPath($id)), 403);
                } else {
                    throw new AccessDeniedException(sprintf("The file %s cannot be read", $this->getPath($id)), 403);
                }
            }
        }
    }

    /**
     * Save
     *
     * Save a cache collection
     *
     * @param CacheCollection $collection - the cache collection to save
     *
     * @return CacheProviderInterface
     *
     * @see \Cscfa\Bundle\CacheSystemBundle\Object\provider\CacheProviderInterface::save()
     */
    public function save(CacheCollection $collection)
    {
        $directory = $this->cacheDir . $this->prefix;
        $dir = is_dir($directory);
        $read = is_readable($directory);
        $write = is_writable($directory);

        if ($dir && $read && $write) {
            if ($this->exist($collection->getId()) && ! $this->accessible($collection->getId())) {

                $read = $this->readable($collection->getId());
                $write = $this->writable($collection->getId());

                if ($read && ! $write) {
                    throw new AccessDeniedException(sprintf("The file %s is on read only state", $this->getPath($collection->getId())), 403);
                } else if (! $read && ! $write) {
                    throw new AccessDeniedException(sprintf("The file %s cannot be read or write", $this->getPath($collection->getId())), 403);
                }
            }

            $collection->setTimestampOffset($this->timestamp);
            $data = $collection->serialize();
            $result = file_put_contents($this->getPath($collection->getId()), $data);

            if ($result === false) {
                throw new FileException(sprintf("A failure occured during writing file %s", $this->getPath($collection->getId())), 500);
            } else if ($result !== strlen($data)) {
                throw new FileException(sprintf("An error occured during writing file %s. Writed %d bytes, expect %d", $this->getPath($collection->getId()), $result, strlen($data)), 500);
            }
        } else {
            if (! $dir) {

                if (! mkdir($directory, 0775, true)) {
                    throw new DirectoryException(sprintf("The %s directory does not exist", $directory), 500);
                } else {

                    if (!chmod($directory, 0775)) {
                        throw new DirectoryException(sprintf("The %s directory present permission error", $directory), 500);
                    }

                    $this->save($collection);
                }
            } else if ($read && ! $write) {
                throw new AccessDeniedException(sprintf("The directory %s is on read only state", $directory), 403);
            } else if (! $read && ! $write) {
                throw new AccessDeniedException(sprintf("The directory %s cannot be read or write", $directory), 403);
            } else {
                throw new AccessDeniedException(sprintf("The directory %s cannot be read", $directory), 403);
            }
        }
    }

    /**
     * Accessible
     *
     * Check if a cache id is
     * accessible
     *
     * @param string $id - the cache id
     *
     * @return boolean - the accessibility state
     */
    protected function accessible($id)
    {
        return $this->exist($id) && $this->readable($id) && $this->writable($id);
    }

    /**
     * Writable
     *
     * Check if a cache id is
     * writable
     *
     * @param string $id - the cache id
     *
     * @return boolean - the writable state
     */
    protected function writable($id)
    {
        return is_writable($this->getPath($id));
    }

    /**
     * Readable
     *
     * Check if a cache id is
     * readable
     *
     * @param string $id - the cache id
     *
     * @return boolean - the readable state
     */
    protected function readable($id)
    {
        return is_readable($this->getPath($id));
    }

    /**
     * Exist
     *
     * Check if a given cache
     * id exist
     *
     * @param string $id - the cache id
     *
     * @return boolean - the existance state
     */
    protected function exist($id)
    {
        return is_file($this->getPath($id));
    }

    /**
     * Get path
     *
     * Get the path to a
     * cache id
     *
     * @param string $id - the cache id
     *
     * @return string - the path
     */
    protected function getPath($id)
    {
        return $this->cacheDir . $this->prefix . '/' . $id . '.ser';
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\ObjectStore\Type;

use Ruwork\ObjectStore\Configurator\StoreConfiguratorInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class BaseStoreType implements StoreTypeInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getRequiredTypes(): iterable
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setRequired('class')
            ->setDefault('default', static function (Options $options): callable {
                $class = $options['class'];

                return static function () use ($class) {
                    return new $class();
                };
            })
            ->setAllowedTypes('class', 'string')
            ->setAllowedTypes('default', ['null', 'object', 'callable'])
            ->setNormalizer('default', static function (Options $options, $default): callable {
                if (\is_callable($default)) {
                    return $default;
                }

                return static function () use ($default) {
                    return $default;
                };
            });
    }

    /**
     * {@inheritdoc}
     */
    public function configureStore(StoreConfiguratorInterface $configurator, array $options): void
    {
        $configurator
            ->setClass($options['class'])
            ->setDefaultFactory($options['default']);
    }
}


<?php

namespace Laralum\Social\Controllers;

use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
use Laralum\Social\Models\Settings;
use Laralum\Social\Models\Social;
use Laralum\Users\Models\User;
use Laravel\Socialite\Facades\Socialite;

class SocialController extends Controller
{
    /**
     * Stores the social settings.
     *
     * @var \Laralum\Social\Models\Social
     */
    private $settings;

    /**
     * Controller constructor.
     */
    public function __construct()
    {
        $this->settings = Settings::first();
    }

    /**
     * Redirect the user to the provider authentication page.
     *
     * @return Response
     */
    public function provider($provider)
    {
        $this->checkDisabled();

        $this->checkProvider($provider);

        $this->setConfig($provider);

        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from the provider.
     *
     * @return Response
     */
    public function callback(Request $request, $provider)
    {
        $this->checkDisabled();

        $this->checkProvider($provider);

        $this->setConfig($provider);

        $user = User::find(Auth::id());

        $redirectAfter = url('/');

        if ($user) {
            $redirectAfter = !($user->hasPermission('laralum::access') || $user->superAdmin()) ?: route('laralum::social.integrations');
        }

        $user = Socialite::driver($provider)->user();

        if ($user->getEmail() && $user->getName()) {
            if (Auth::check()) {
                if (!Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first()) {
                    $this->registerSocial($provider, $user);

                    return redirect($redirectAfter)->with('success', __('laralum_social::general.provider_linked', ['provider' => $provider]));
                }

                return redirect($redirectAfter)->with('error', __('laralum_social::general.provider_already_linked', ['provider' => $provider]));
            }

            $sa = Social::where(['email' => $user->getEmail(), 'provider' => $provider])->first();

            if ($sa) {
                Auth::login($sa->user);

                return redirect($redirectAfter)->with('success', __('laralum_social::general.logged_in', ['provider' => $provider]));
            }

            abort(403, 'Registrations are not allowed using the social feature');
        }

        abort(403, 'The provider did not return a valid email or name to register the user');
    }

    public function integrations()
    {
        $providers = Social::availableProviders();

        return view('laralum_social::integrations', ['providers' => $providers]);
    }

    /**
     * Unlink the social account.
     *
     * @param string $provider
     *
     * @return Response
     */
    public function unlink($provider)
    {
        $this->checkDisabled();

        $user = User::findOrFail(Auth::id());
        $redirectAfter = $user->hasPermission('laralum::access') || $user->superAdmin() ? route('laralum::social.integrations') : url('/');

        $link = Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first();

        if (!$link) {
            return redirect($redirectAfter)->with('success', __('laralum_social::general.link_not_found', ['provider' => $provider]));
        }

        $link->delete();

        return redirect($redirectAfter)->with('success', __('laralum_social::general.unlinked', ['provider' => $provider]));
    }

    /**
     * Update the social settings.
     *
     * @return Response
     */
    public function settings(Request $request)
    {
        $this->authorize('update', Settings::class);

        $this->settings->update([
            'enabled'                 => $request->enabled ? true : false,
            'allow_register'          => $request->allow_register ? false : false, // Not enabled yet
            'facebook_client_id'      => $request->facebook_client_id ? encrypt($request->facebook_client_id) : null,
            'facebook_client_secret'  => $request->facebook_client_secret ? encrypt($request->facebook_client_secret) : null,
            'twitter_client_id'       => $request->twitter_client_id ? encrypt($request->twitter_client_id) : null,
            'twitter_client_secret'   => $request->twitter_client_secret ? encrypt($request->twitter_client_secret) : null,
            'linkedin_client_id'      => $request->linkedin_client_id ? encrypt($request->linkedin_client_id) : null,
            'linkedin_client_secret'  => $request->linkedin_client_secret ? encrypt($request->linkedin_client_secret) : null,
            'google_client_id'        => $request->google_client_id ? encrypt($request->google_client_id) : null,
            'google_client_secret'    => $request->google_client_secret ? encrypt($request->google_client_secret) : null,
            'github_client_id'        => $request->github_client_id ? encrypt($request->github_client_id) : null,
            'github_client_secret'    => $request->github_client_secret ? encrypt($request->github_client_secret) : null,
            'bitbucket_client_id'     => $request->bitbucket_client_id ? encrypt($request->bitbucket_client_id) : null,
            'bitbucket_client_secret' => $request->bitbucket_client_secret ? encrypt($request->bitbucket_client_secret) : null,
        ]);

        $this->settings->touch();

        return redirect()->route('laralum::settings.index', ['p' => 'Social'])->with('success', __('laralum_social::general.updated_settings'));
    }

    /**
     * Check if the social feature is disabled.
     */
    private function checkDisabled()
    {
        if (!$this->settings->enabled) {
            abort(404, __('laralum_social::general.social_disabled'));
        }
    }

    /**
     * Check if the provider is enabled or not.
     *
     * @param string $provider
     */
    private function checkProvider($provider)
    {
        $ci = $provider.'_client_id';
        $cs = $provider.'_client_secret';

        if (!$this->settings->$ci || !$this->settings->$cs) {
            abort(404, __('laralum_social::general.provider_not_found', ['provider' => $provider]));
        }
    }

    /**
     * Set the configuration to run socialite with a defined provider.
     *
     * @param string $provider
     */
    private function setConfig($provider)
    {
        $ci = $provider.'_client_id';
        $cs = $provider.'_client_secret';

        config(['services.'.$provider => [
            'client_id'     => decrypt($this->settings->$ci),
            'client_secret' => decrypt($this->settings->$cs),
            'redirect'      => route('laralum_public::social.callback', ['provider' => $provider]),
        ]]);
    }

    /**
     * Registers the social account.
     *
     * @param string                     $provider
     * @param mixed                      $user
     * @param \Laralum\Users\Models\User $dbuser
     *
     * @return bool
     */
    private function registerSocial($provider, $user, $dbuser = null)
    {
        return Social::create([
            'user_id'      => $dbuser ? $dbuser->id : Auth::user()->id,
            'provider'     => $provider,
            'token'        => $user->token,
            'secret_token' => isset($user->tokenSecret) ? $user->tokenSecret : null,
            'email'        => $user->getEmail(),
        ]);
    }
}


<?php

namespace Reaction\Db;

use Reaction\Base\BaseObject;
use Reaction\Helpers\StringHelper;

/**
 * ColumnSchema class describes the metadata of a column in a database table.
 */
class ColumnSchema extends BaseObject implements ColumnSchemaInterface
{
    /**
     * @var string name of this column (without quotes).
     */
    public $name;
    /**
     * @var bool whether this column can be null.
     */
    public $allowNull;
    /**
     * @var string abstract type of this column. Possible abstract types include:
     * char, string, text, boolean, smallint, integer, bigint, float, decimal, datetime,
     * timestamp, time, date, binary, and money.
     */
    public $type;
    /**
     * @var string the PHP type of this column. Possible PHP types include:
     * `string`, `boolean`, `integer`, `double`, `array`.
     */
    public $phpType;
    /**
     * @var string the DB type of this column. Possible DB types vary according to the type of DBMS.
     */
    public $dbType;
    /**
     * @var mixed default value of this column
     */
    public $defaultValue;
    /**
     * @var array enumerable values. This is set only if the column is declared to be an enumerable type.
     */
    public $enumValues;
    /**
     * @var int display size of the column.
     */
    public $size;
    /**
     * @var int precision of the column data, if it is numeric.
     */
    public $precision;
    /**
     * @var int scale of the column data, if it is numeric.
     */
    public $scale;
    /**
     * @var bool whether this column is a primary key
     */
    public $isPrimaryKey;
    /**
     * @var bool whether this column is auto-incremental
     */
    public $autoIncrement = false;
    /**
     * @var bool whether this column is unsigned. This is only meaningful
     * when [[type]] is `smallint`, `integer` or `bigint`.
     */
    public $unsigned;
    /**
     * @var string comment of this column. Not all DBMS support this.
     */
    public $comment;

    /**
     * Converts the input value according to [[phpType]] after retrieval from the database.
     * If the value is null or an [[Expression]], it will not be converted.
     * @param mixed $value input value
     * @return mixed converted value
     */
    public function phpTypecast($value)
    {
        return $this->typecast($value);
    }

    /**
     * Converts the input value according to [[type]] and [[dbType]] for use in a db query.
     * If the value is null or an [[Expression]], it will not be converted.
     * @param mixed $value input value
     * @return mixed converted value. This may also be an array containing the value as the first element
     * and the PDO type as the second element.
     */
    public function dbTypecast($value)
    {
        // the default implementation does the same as casting for PHP, but it should be possible
        // to override this with annotation of explicit PDO type.
        return $this->typecast($value);
    }

    /**
     * Converts the input value according to [[phpType]] after retrieval from the database.
     * If the value is null or an [[Expression]], it will not be converted.
     * @param mixed $value input value
     * @return mixed converted value
     */
    protected function typecast($value)
    {
        if ($value === ''
            && !in_array(
                $this->type,
                [
                    Schema::TYPE_TEXT,
                    Schema::TYPE_STRING,
                    Schema::TYPE_BINARY,
                    Schema::TYPE_CHAR
                ],
                true)
        ) {
            return null;
        }

        if ($value === null
            || gettype($value) === $this->phpType
            || $value instanceof \Reaction\Db\Expressions\ExpressionInterface
            || $value instanceof Query
        ) {
            return $value;
        }

        switch ($this->phpType) {
            case 'resource':
            case 'string':
                if (is_resource($value)) {
                    return $value;
                }
                if (is_float($value)) {
                    // ensure type cast always has . as decimal separator in all locales
                    return StringHelper::floatToString($value);
                }
                return (string) $value;
            case 'integer':
                return (int) $value;
            case 'boolean':
                return (bool) $value && $value !== "\0";
            case 'double':
                return (float) $value;
        }

        return $value;
    }
}


<?php

namespace Colorium\Orm;

use Colorium\Orm\Contract\BuilderInterface;
use Colorium\Orm\Contract\QueryInterface;
use Colorium\Orm\Contract\SourceInterface;

abstract class Hub
{

    /** @var SourceInterface */
    protected static $source;

    /**
     * Source accessor
     *
     * @param SourceInterface $source
     * @return SourceInterface
     */
    public static function source(SourceInterface $source = null)
    {
        if($source) {
            static::$source = $source;
        }
        elseif(!isset(static::$source)) {
            throw new \LogicException('No source instance stored');
        }

        return static::$source;
    }

    /**
     * MySQL source
     *
     * @param string $settings
     * @param array $classmap
     * @return MySQL
     */
    public static function MySQL($settings, array $classmap = [])
    {
        $mysql = new MySQL($settings, $classmap);
        return static::source($mysql);
    }

    /**
     * SQLite source
     *
     * @param string $filename
     * @param array $classmap
     * @return MySQL
     */
    public static function SQLite($filename, array $classmap = [])
    {
        $sqlite = new SQLite($filename, $classmap);
        return static::source($sqlite);
    }

    /**
     * Generate query
     *
     * @param string $entity
     * @return QueryInterface
     */
    public static function query($entity)
    {
        return static::source()->query($entity);
    }

    /**
     * Generate builder
     *
     * @param string $entity
     * @return BuilderInterface
     */
    public static function builder($entity)
    {
        return static::source()->builder($entity);
    }

    /**
     * Alias of query(name)
     *
     * @param string $entity
     * @param array $args
     * @return QueryInterface
     */
    public static function __callStatic($entity, array $args)
    {
        return static::query($entity);
    }

    /**
     * Execute raw query
     *
     * @param string $sql
     * @param array $params
     * @param string $class
     * @return mixed
     */
    public static function raw($sql, array $params = [], $class = null)
    {
        return static::source()->raw($sql, $params, $class);
    }

    /**
     * Fetch many result
     *
     * @param string $entity
     * @param array $where
     * @param array $sort
     * @return \object[]
     */
    public static function fetch($entity, array $where = [], array $sort = [])
    {
        $query = static::query($entity);
        foreach($where as $expression => $value) {
            $query->where($expression, $value);
        }
        foreach($sort as $field => $direction) {
            $query->sort($field, $direction);
        }

        return $query->fetch();
    }

    /**
     * Fetch one result
     *
     * @param string $entity
     * @param array $where
     * @return object
     */
    public static function one($entity, array $where = [])
    {
        $query = static::query($entity);
        foreach($where as $expression => $value) {
            $query->where($expression, $value);
        }

        return $query->one();
    }

    /**
     * Add record
     *
     * @param string $entity
     * @param mixed $values
     * @return int
     */
    public static function add($entity, $values)
    {
        return static::query($entity)->add($values);
    }

    /**
     * Edit record
     *
     * @param string $entity
     * @param mixed $values
     * @param array $where
     * @return int
     */
    public static function edit($entity, $values, array $where = [])
    {
        $query = static::query($entity);
        foreach($where as $expression => $value) {
            $query->where($expression, $value);
        }

        return $query->edit($values);
    }

    /**
     * Delete record
     *
     * @param string $entity
     * @param array $where
     * @return int
     */
    public static function drop($entity, array $where = [])
    {
        $query = static::query($entity);
        foreach($where as $expression => $value) {
            $query->where($expression, $value);
        }

        return $query->drop();
    }

}


<?php

namespace Reaction\Cache;

use React\EventLoop\Timer\TimerInterface;
use Reaction\Helpers\ArrayHelper;

/**
 * Class ExpiringCache
 * @package Reaction\Cache
 */
abstract class ExpiringCache extends ExtendedCache implements ExpiringCacheInterface
{
    /**
     * @var string Record timestamp key
     */
    public $timestampKey = '_ts';
    /**
     * @var string User data timestamp key
     */
    public $dataKey = '_data';
    /**
     * @var string Tags key in record
     */
    public $tagsKey = '_tags';
    /**
     * @var int Timer interval seconds
     */
    public $timerInterval = 3;
    /**
     * @var int Default cache lifetime
     */
    public $lifetimeDefault = 3600;
    /**
     * @var array Keys with timestamps
     */
    protected $_timestamps = [];
    /**
     * @var TimerInterface Timer for GC
     */
    protected $_timer;

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        $this->createCleanupTimer();
        parent::init();
    }

    /**
     * Cleanup callback for timer
     */
    public function cleanupTimerCallback() {
        $now = time();
        $keys = [];
        foreach ($this->_timestamps as $key => $timestamp) {
            if ($timestamp < $now) {
                $keys[] = $key;
            }
        }
        if (!empty($keys)) {
            $this->deleteMultiple($keys);
        }
    }

    /**
     * Pack record into array with needed format
     * @param mixed $record
     * @return array
     */
    protected function packRecord($record = []) {
        $tsKey = $this->timestampKey;
        $dtKey = $this->dataKey;
        $data = $record;
        $record = [];
        $record[$dtKey] = $data;
        $record[$tsKey] = time();
        return $record;
    }

    /**
     * Unpack data from record
     * @param array $record
     * @return mixed
     */
    protected function unpackRecord($record = []) {
        $tsKey = $this->timestampKey;
        $dtKey = $this->dataKey;
        if (!is_array($record) || !isset($record[$tsKey]) || !ArrayHelper::keyExists($dtKey, $record)) {
            return $record;
        }
        return $record[$dtKey];
    }

    /**
     * Create cleanup timer
     */
    protected function createCleanupTimer() {
        if (isset($this->_timer)) {
            $this->loop->cancelTimer($this->_timer);
        }
        $this->_timer = $this->loop->addPeriodicTimer($this->timerInterval, [$this, 'cleanupTimerCallback']);
    }

    /**
     * Get Event loop
     * @return \React\EventLoop\LoopInterface
     */
    protected function getLoop() {
        return \Reaction::$app->loop;
    }
}


<?php namespace Waynestate\Menuitems;

use Waynestate\Menuitems\ParserInterface;
use Waynestate\Menuitems\InvalidDisplayLevelsException;
use Waynestate\Menuitems\InvalidSkipLevelsException;

/**
 * Class ParseMenu
 * @package Waynestate
 */
class ParseMenu implements ParserInterface
{
    /**
     * @var array
     */
    protected $menu;

    /**
     * @var array
     */
    protected $path = array();

    /**
     * @var array
     */
    protected $meta = array();

    /**
     * @param array $menu
     * @param array $config
     * @throws InvalidDisplayLevelsException
     * @throws InvalidSkipLevelsException
     * @return array
     */
    public function parse(array &$menu, array $config = array())
    {
        // Set the menu locally
        $this->menu = $menu;

        // Base meta information
        $this->meta = array(
            'has_selected' => false,
            'has_submenu' => false,
            'path' => $this->path,
        );

        // Set a default levels to skip from root
        $skip = isset($config['skip_levels']) ? (int)$config['skip_levels'] : 0;

        // Set a default levels to display
        $display = isset($config['display_levels']) ? (int)$config['display_levels'] : 0;

        // If a page should be selected
        if (isset($config['page_selected'])) {
            // Find the first occurrence of the page_id
            $this->path = $this->findPath($this->menu, (int)$config['page_selected']);
        }

        // Add menu item additional information
        $this->menu = $this->setSelected($this->menu);

        if (! isset($config['full_menu']) || $config['full_menu'] == false) {
            // Trim the non-needed limbs off the menu
            $this->menu = $this->trimMenu($this->menu);
        }

        // If there is a need to skip levels from the root
        if ($skip > 0) {
            $this->menu = $this->sliceFromRoot($this->menu, $skip);

            // Trim the skip items from the path
            $this->path = array_slice($this->path, 0, -1 * abs($skip));
        }

        // If there is a specified levels to display and it is smaller than the path
        if ($display > 0 &&
             (count($this->path) == 0 || $display <= (count($this->path) - $skip))
        ) {
            $this->menu = $this->menuSlice($this->menu, $display);

            // Trim the non-display items from the path
            $this->path = array_slice($this->path, (count($this->path) - $display));
        }

        // Updated meta information
        $this->meta['path'] = array_reverse($this->path);

        // If there is a selected item
        if ($this->meta['has_selected']) {
            // Check to see if there are any active submenu items
            $this->meta['has_submenu'] = $this->hasSubMenu(current($this->meta['path']));
        }

        // The menu now has been modified with $config
        return array(
            'meta' => $this->meta,
            'menu' => $this->menu,
        );
    }

    /**
     * @param $breadcrumbs
     * @param $menu_item
     * @return mixed
     */
    public function prependBreadCrumb($breadcrumbs, $menu_item)
    {
        // add menu_item to the breadcrumbs array and return it
        array_unshift($breadcrumbs, $menu_item);

        return $breadcrumbs;
    }

    /**
     * @param $menu
     * @return mixed
     */
    public function getBreadCrumbs($menu)
    {
        $breadcrumbs = array();
        $array_path = array();

        // Loop through the path array and pull out each of the menu_item_ids from within the $menu['menu'] array
        foreach ((array)$menu['meta']['path'] as $menu_item_id) {
            $array_path[] = $menu_item_id;
            $crumb = self::array_get($menu['menu'], implode('.submenu.', $array_path));
            $crumb['submenu'] = array();
            $breadcrumbs[] = $crumb;
        }

        return $breadcrumbs;
    }

    /**
     * @param array $menu
     * @param $page_id
     * @return array
     */
    protected function findPath(array $menu, $page_id)
    {
        // Start with no path
        $path = array();

        // Loop through each menu
        foreach ($menu as $item) {
            // If there is a submenu for this item
            if (! empty($item['submenu'])) {
                // Try to look for the page within the submenu
                $sub_found = $this->findPath($item['submenu'], $page_id);

                // Append the path to get the trail
                $path = array_merge($path, $sub_found);

                // If there was something found build the path
                if ($sub_found) {
                    $path[] = $item['menu_item_id'];
                }
            }

            // If this individual item matches the page, keep track of it
            if ($item['page_id'] == $page_id && !in_array($item['menu_item_id'], $path)) {
                $path[] = $item['menu_item_id'];
            }
        }

        // Return an array of menu_item_id's to show a trail to the page_id
        return $path;
    }

    /**
     * @param array $menu
     * @return array
     */
    protected function trimMenu(array $menu)
    {
        // Start with the blank new menu
        $path_menu = array();

        // Loop through each menu item
        foreach ($menu as $item) {

            // If this menu item is found in the path
            if (in_array($item['menu_item_id'], $this->path)) {

                // If there is a submenu trim it too
                if (! empty($item['submenu'])) {
                    $item['submenu'] = $this->trimMenu($item['submenu']);
                }
            } else {
                // If this menu item is not in the path, ignore any submenus
                $item['submenu'] = array();
            }

            // Add this item to the newly trimmed menu
            $path_menu[$item['menu_item_id']] = $item;
        }

        // Return the trimmed menu
        return $path_menu;
    }

    /**
     * @param array $menu
     * @param $start
     * @param int $level
     * @throws InvalidSkipLevelsException
     * @return array
     */
    protected function sliceFromRoot(array $menu, $start, $level = 0)
    {
        // Require the skip to be less than the selected path
        if ($start > 0 && $start >= count($this->path)) {
            throw new InvalidSkipLevelsException('Selected path must be deeper than the levels to skip.');
        }

        // If we have reached our start level
        if ($level >= $start) {
            // Return the rest of the menu
            return $menu;
        }

        // Loop through each menu item
        foreach ($menu as $item) {
            // If there are sub menu items
            if (! empty($item['submenu'])) {
                // Dig deeper into the next level
                return $this->sliceFromRoot($item['submenu'], $start, ++ $level);
            }
        }

        // If the menu does not have 'submenu' array (invalid $menu array format)
        return array();
    }

    /**
     * @param array $menu
     * @param $end
     * @param int $level
     * @throws InvalidDisplayLevelsException
     * @return array
     */
    protected function menuSlice(array $menu, $end, $level = 1)
    {
        // Require a path selection to display more than one level of the menu
        if ($end > 1 && count($this->path) < 1) {
            throw new InvalidDisplayLevelsException('Page must be selected to display more than one level.');
        }

        // Start with a blank sliced array
        $slice_menu = array();

        // If we have reached the final level to display
        if ($level > $end) {
            // Chop off any submenus and return
            return array();
        } else {
            // Loop through each item in the menu
            foreach ($menu as $item) {
                // If there is a submenu
                if (! empty($item)) {
                    // Dig deeper into the next level of the menu
                    $item['submenu'] = $this->menuSlice($menu, $end, ++ $level);
                }

                // If in bounds, add the item to the new menu
                $slice_menu[$item['menu_item_id']] = $item;
            }
        }

        // Should never get to this point
        return $slice_menu;
    }

    /**
     * Determine if the top level of a selected path has a submenu to display
     *
     * @param $menu_item_id
     * @return bool
     */
    protected function hasSubMenu($menu_item_id)
    {
        // Submenu always available with a path > 1
        if (count($this->meta['path']) > 1)
            return true;

        // Decide if the first level menu has any visible submenu items
        foreach ($this->menu as $item) {
            // Find the desired menu item in the first level
            if ($item['menu_item_id'] == $menu_item_id) {
                // Loop through each submenu item
                foreach ($item['submenu'] as $sub_item) {
                    // If there is at least one active item
                    if ($sub_item['is_active'] == true) {
                        // There is a submenu to display
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * @param array $menu
     * @return array
     */
    private function setSelected(array $menu)
    {
        // Start with the blank new menu
        $full_menu = array();

        // Loop through each menu item
        foreach ($menu as $item) {
            // Default each menu item to not-selected
            $item['is_selected'] = false;

            // If this menu item is found in the path
            if (in_array($item['menu_item_id'], $this->path)) {
                // This item should be in the selected path
                $item['is_selected'] = true;

                // Set the meta information
                $this->meta['has_selected'] = true;
            }

            // If there is a sub menu, setSelected state on those items
            if (!empty($item['submenu'])) {
                $item['submenu'] = $this->setSelected($item['submenu']);
            }

            // Add this item into the menu being formed
            $full_menu[$item['menu_item_id']] = $item;
        }

        return $full_menu;
    }

    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  string $key
     * @param  mixed $default
     * @return mixed
     */
    private static function array_get($array, $key, $default = null)
    {
        if (!is_array($array)) {
            return value($default);
        }
        if (is_null($key)) {
            return $array;
        }
        if (array_key_exists($key, $array)) {
            return $array[$key];
        }
        foreach (explode('.', $key) as $segment) {
            if (is_array($array) && array_key_exists($segment, $array)) {
                $array = $array[$segment];
            } else {
                return value($default);
            }
        }
        return $array;
    }
}


<?php
/*
 * This file is part of the Skeetr package.
 *
 * (c) Máximo Cuadros <mcuadros@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Skeetr\Client\RPC\Method;

use Skeetr\Client\RPC\Method;
use Skeetr\Client\RPC\Request;
use Skeetr\Client\HTTP;
use Skeetr\Client\Handler\Error;
use Skeetr\Runtime\Manager;
use http\Message\Body;

class Process extends Method
{
    private $callback;
    private $runtime = true;

    /**
     * Constructor
     *
     * @param callback $callback
     */
    public function __construct(Callable $callback)
    {
        $this->callback = $callback;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(Request $request)
    {
        $start = microtime(true);

        $httpRequest = new HTTP\Request();

        $body = new Body();
        $httpResponse = new HTTP\Response;
        $httpResponse->setBody($body);

        try {
            $result = $this->runCallback($httpRequest, $httpResponse);
            $body->append($result);
        } catch (\Exception $e) {
            $httpResponse->setResponseCode(500);

            //TODO: Maybe implement something more complex, with better error reporting?
            Error::printException($e, false);
            $body->append(sprintf('Error: %s', $e->getMessage()));
        }

        $this->prepareResponse($httpResponse);

        return $httpResponse->toArray();
    }

    private function runCallback(HTTP\Request $request, HTTP\Response $response)
    {
        $cb = $this->callback;

        return $cb($request, $response);
    }

    /**
     * Set the headers and the response code to a given $response, class is reset after.
     *
     * @param  HTTP\Response $response
     * @return boolean
     */
    private function prepareResponse(HTTP\Response $response)
    {
        if ( !Manager::loaded() ) return false;
        session_write_close();

        $values = Manager::values();
        if ( isset($values['header']) ) {
            if ( isset($values['header']['code']) && $values['header']['code'] ) {
                $response->setResponseCode($values['header']['code']);
            }

            if ( isset($values['header']['list']) ) {
                foreach ($values['header']['list'] as $headers) {
                    foreach ($headers as $header) {
                        $response->addHeader($header, false);
                    }
                }
            }
        }

        Manager::reset();
    }
}


<?php
/**
 * OpenWebPresence Support Library - openwebpresence.com
 *
 * @copyright 2001 - 2017, Brian Tafoya.
 * @package   OwpSupportMethods
 * @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 various helper methods which can be used in any php development projects.
 */
class OwpSupportMethods
{

    /**
     * uuid
     *
     * @method uuid()
     * @access public
     * @return string
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static public function uuid()
    {
        return md5(uniqid((rand() + MicroTime()), 1));

    }//end uuid()

    /**
     * randomPasswordAlphaNum
     *
     * @method randomPasswordAlphaNum()
     * @access public
     * @return string
     * @param  int $length Random password length.
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static public function randomPasswordAlphaNum($length)
    {
        $alphabets       = range('A', 'Z');
        $alphabets_lower = range('a', 'z');
        $numbers         = range('0', '9');
        $final_array     = array_merge($alphabets, $numbers, $alphabets_lower);

        $password = '';

        while($length--) {
            $key       = array_rand($final_array);
            $password .= $final_array[$key];
        }

        return (string) $password;

    }//end randomPasswordAlphaNum()

    /**
     * GetUserIP
     *
     * @method GetUserIP()
     * @access public
     * @return string
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static public function GetUserIP()
    {
        if(isset($_SERVER) && isset($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        } else {
            return "127.0.0.1";
        }

    }//end GetUserIP()

    /**
     * includeIfExists
     *
     * @method includeIfExists($file) Includes file if it exists.
     * @access public
     * @param  string $file File to include.
     * @return mixed
     *
     * @author  Brian Tafoya
     * @version 1.0
     */
    static function includeIfExists($file)
    {
        if (file_exists($file)) {
            return include $file;
        }

    }//end includeIfExists()

    /**
     * filterAction
     *
     * @method filterAction($action) Includes file if it exists.
     * @access public
     * @param  $action
     * @return string
     */
    static function filterAction($action)
    {
        return (string) preg_replace("/[^A-Za-z0-9_-]/", "", $action);

    }//end filterAction()

    /**
     * file_get_php_classes
     *
     * @method file_get_php_classes($filepath) Get classes from a file.
     * @param  $filepath
     * @return array
     */
    static function file_get_php_classes($filepath)
    {
        $php_code = file_get_contents($filepath);
        $classes  = OwpSupportMethods::get_php_classes($php_code);
        return $classes;

    }//end file_get_php_classes()

    /**
     * get_php_classes
     *
     * @method get_php_classes($php_code) Get classes froma string.
     * @param  $php_code
     * @return array
     */
    static function get_php_classes($php_code)
    {
        $classes = array();
        $tokens  = token_get_all($php_code);
        $count   = count($tokens);
        for ($i = 2; $i < $count; $i++) {
            if ($tokens[($i - 2)][0] === T_CLASS
                && $tokens[($i - 1)][0] === T_WHITESPACE
                && $tokens[$i][0] === T_STRING
            ) {
                $class_name = $tokens[$i][1];
                $classes[]  = $class_name;
            }
        }

        return $classes;

    }//end get_php_classes()

    /**
     * OwpPCdebug
     *
     * @method OwpPCdebug($object, $tag) Debug method.
     * @param  mixed  $object Object to debug
     * @param  string $tag    Object tag
     * @return mixed
     */
    static function OwpPCdebug($object, $tag)
    {
        PC::debug($object, $tag);
        return $object;
    }//end OwpPCdebug()
}//end class


<?php namespace Ordercloud\Support\ExceptionGenerators;

use Ordercloud\Requests\Exceptions\OrdercloudRequestException;
use Ordercloud\Requests\OrdercloudRequest;
use Ordercloud\Support\Http\OrdercloudHttpException;

abstract class ExceptionGenerator
{
    /**
     * @var ExceptionGenerator
     */
    protected $successor;

    /**
     * Attempt to generate the exception. If the exception can't be generated
     * here, then pass the exception to the next generator.
     *
     * @param OrdercloudRequest       $request
     * @param OrdercloudHttpException $exception
     *
     * @return OrdercloudRequestException
     */
    abstract public function generateException(OrdercloudRequest $request, OrdercloudHttpException $exception);

    /**
     * Set the ExceptionGenerator that should be executed next
     * if this generator can't handle the exception.
     *
     * @param ExceptionGenerator $generator
     */
    public function succeedWith(ExceptionGenerator $generator)
    {
        $this->successor = $generator;
    }

    /**
     * Pass the exception to be handled by the successor.
     *
     * @param OrdercloudRequest       $request
     * @param OrdercloudHttpException $exception
     *
     * @return OrdercloudRequestException
     */
    public function next(OrdercloudRequest $request, OrdercloudHttpException $exception)
    {
        return $this->successor->generateException($request, $exception);
    }
}


<?php

namespace KsUtils\StrFilter;

/**
 * Filter for stripping html tags from string
 */
class StripTags implements \KsUtils\StrFilter
{
    /**
     * Clears html tags from source string
     * @param  string|array $str Source string
     * @return string       Filtered string
     */
    public function filter($str)
    {
        if (is_array($str)) {
            foreach ($str as $k => $v) {
                $str[$k] = strip_tags($v);
            }

            return $str;
        }

        return strip_tags($str);
    }
}


<?php

namespace Reaction\Db\Expressions;

/**
 * Class ExpressionBuilder builds objects of [[yii\db\Expression]] class.
 */
class ExpressionBuilder implements ExpressionBuilderInterface
{
    use ExpressionBuilderTrait;

    /**
     * {@inheritdoc}
     * @param Expression $expression the expression to be built
     */
    public function build($expression, array &$params = [])
    {
        $params = array_merge($params, $expression->params);
        return method_exists($expression, '__toString') ? $expression->__toString() : '';
    }
}


<?php
/**
 * PEAR_Installer_Role
 *
 * PHP versions 4 and 5
 *
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: Role.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/package/PEAR
 * @since      File available since Release 1.4.0a1
 */

/**
 * base class for installer roles
 */
require_once 'PEAR/Installer/Role/Common.php';
require_once 'PEAR/XMLParser.php';
/**
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 1.4.0a1
 */
class PEAR_Installer_Role
{
    /**
     * Set up any additional configuration variables that file roles require
     *
     * Never call this directly, it is called by the PEAR_Config constructor
     * @param PEAR_Config
     * @access private
     * @static
     */
    function initializeConfig(&$config)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $class => $info) {
            if (!$info['config_vars']) {
                continue;
            }

            $config->_addConfigVars($class, $info['config_vars']);
        }
    }

    /**
     * @param PEAR_PackageFile_v2
     * @param string role name
     * @param PEAR_Config
     * @return PEAR_Installer_Role_Common
     * @static
     */
    function &factory($pkg, $role, &$config)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        if (!in_array($role, PEAR_Installer_Role::getValidRoles($pkg->getPackageType()))) {
            $a = false;
            return $a;
        }

        $a = 'PEAR_Installer_Role_' . ucfirst($role);
        if (!class_exists($a)) {
            require_once str_replace('_', '/', $a) . '.php';
        }

        $b = new $a($config);
        return $b;
    }

    /**
     * Get a list of file roles that are valid for the particular release type.
     *
     * For instance, src files serve no purpose in regular php releases.
     * @param string
     * @param bool clear cache
     * @return array
     * @static
     */
    function getValidRoles($release, $clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret = array();
        if ($clear) {
            $ret = array();
        }

        if (isset($ret[$release])) {
            return $ret[$release];
        }

        $ret[$release] = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if (in_array($release, $okreleases['releasetypes'])) {
                $ret[$release][] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret[$release];
    }

    /**
     * Get a list of roles that require their files to be installed
     *
     * Most roles must be installed, but src and package roles, for instance
     * are pseudo-roles.  src files are compiled into a new extension.  Package
     * roles are actually fully bundled releases of a package
     * @param bool clear cache
     * @return array
     * @static
     */
    function getInstallableRoles($clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret;
        if ($clear) {
            unset($ret);
        }

        if (isset($ret)) {
            return $ret;
        }

        $ret = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if ($okreleases['installable']) {
                $ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret;
    }

    /**
     * Return an array of roles that are affected by the baseinstalldir attribute
     *
     * Most roles ignore this attribute, and instead install directly into:
     * PackageName/filepath
     * so a tests file tests/file.phpt is installed into PackageName/tests/filepath.php
     * @param bool clear cache
     * @return array
     * @static
     */
    function getBaseinstallRoles($clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret;
        if ($clear) {
            unset($ret);
        }

        if (isset($ret)) {
            return $ret;
        }

        $ret = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if ($okreleases['honorsbaseinstall']) {
                $ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret;
    }

    /**
     * Return an array of file roles that should be analyzed for PHP content at package time,
     * like the "php" role.
     * @param bool clear cache
     * @return array
     * @static
     */
    function getPhpRoles($clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret;
        if ($clear) {
            unset($ret);
        }

        if (isset($ret)) {
            return $ret;
        }

        $ret = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if ($okreleases['phpfile']) {
                $ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret;
    }

    /**
     * Scan through the Command directory looking for classes
     * and see what commands they implement.
     * @param string which directory to look for classes, defaults to
     *               the Installer/Roles subdirectory of
     *               the directory from where this file (__FILE__) is
     *               included.
     *
     * @return bool TRUE on success, a PEAR error on failure
     * @access public
     * @static
     */
    function registerRoles($dir = null)
    {
        $GLOBALS['_PEAR_INSTALLER_ROLES'] = array();
        $parser = new PEAR_XMLParser;
        if ($dir === null) {
            $dir = dirname(__FILE__) . '/Role';
        }

        if (!file_exists($dir) || !is_dir($dir)) {
            return PEAR::raiseError("registerRoles: opendir($dir) failed: does not exist/is not directory");
        }

        $dp = @opendir($dir);
        if (empty($dp)) {
            return PEAR::raiseError("registerRoles: opendir($dir) failed: $php_errmsg");
        }

        while ($entry = readdir($dp)) {
            if ($entry{0} == '.' || substr($entry, -4) != '.xml') {
                continue;
            }

            $class = "PEAR_Installer_Role_".substr($entry, 0, -4);
            // List of roles
            if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'][$class])) {
                $file = "$dir/$entry";
                $parser->parse(file_get_contents($file));
                $data = $parser->getData();
                if (!is_array($data['releasetypes'])) {
                    $data['releasetypes'] = array($data['releasetypes']);
                }

                $GLOBALS['_PEAR_INSTALLER_ROLES'][$class] = $data;
            }
        }

        closedir($dp);
        ksort($GLOBALS['_PEAR_INSTALLER_ROLES']);
        PEAR_Installer_Role::getBaseinstallRoles(true);
        PEAR_Installer_Role::getInstallableRoles(true);
        PEAR_Installer_Role::getPhpRoles(true);
        PEAR_Installer_Role::getValidRoles('****', true);
        return true;
    }
}


<?php
namespace Core\Toolbox\Strings;

/**
 * Shorten.php
 *
 * @author Michael "Tekkla" Zorn <tekkla@tekkla.de>
 * @copyright 2016
 * @license MIT
 */
class Shorten extends AbstractStrings
{

    /**
     *
     * @var int
     */
    private $length;

    /**
     *
     * @var string
     */
    private $endstring = '. ';

    /**
     *
     * @var string
     */
    private $addition = '[...]';

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

    /**
     * Returns the lenght of string before it gets shortened
     *
     * @return int
     */
    public function getLength(): int
    {
        return $this->length;
    }

    /**
     * Returns the lenght of string before it gets shortened
     *
     * @param int $length
     *            The length
     */
    public function setLength(int $length)
    {
        $this->length = $length;
    }

    /**
     * Returns the string that is used as mark after that the string gets shortened
     *
     * @return string
     */
    public function getEndstring(): string
    {
        return $this->endstring;
    }

    /**
     * Sets the string that is used as mark after that the string gets shortened
     *
     * @param string $endstring
     */
    public function setEndstring(string $endstring)
    {
        $this->endstring = $endstring;
    }

    /**
     * Returns the addition that will be prepended the shortened string
     *
     * @return string
     */
    public function getAddition(): string
    {
        return $this->addition;
    }

    /**
     * Sets the addition that will be prepended the shortened string
     *
     * @param string $addition
     */
    public function setAddition(string $addition)
    {
        $this->addition = $addition;
    }

    /**
     * Returns the url that is used to wrap the additional string
     *
     * @return string
     */
    public function getWrapUrl(): string
    {
        return $this->wrap_url;
    }

    /**
     * Sets the url that is used to wrap the additional string
     *
     * @param string $wrap_url
     */
    public function setWrapUrl(string $wrap_url)
    {
        $this->wrap_url = $wrap_url;
    }

    /**
     * Shortens a string to the given length and appends the additional string that can be wrapped by a link when a
     * wrap url is set.
     *
     * @return string
     */
    public function shorten(): string
    {
        // Shorten only what is longer than the length
        if (strlen($this->string) < $this->length) {
            return $this->string;
        }

        // Shorten string by length
        $this->result = substr($this->string, 0, $this->length);

        // Shorten further until last occurence of a ' '
        $string = substr($this->result, 0, strrpos($this->result, $this->endstring));

        if (!empty($this->wrap_url)) {
            $addition = 'wrap_url . '">' . $this->addition . '';
        }

        // Add addition
        $this->result .= $addition;

        // Done.
        return $this->result;
    }
}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Bz2.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Compress_CompressAbstract
 */

/**
 * Compression adapter for Bz2
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Compress_Bz2 extends Zend_Filter_Compress_CompressAbstract
{
    /**
     * Compression Options
     * array(
     *     'blocksize' => Blocksize to use from 0-9
     *     'archive'   => Archive to use
     * )
     *
     * @var array
     */
    protected $_options = array(
        'blocksize' => 4,
        'archive'   => null,
    );

    /**
     * Class constructor
     *
     * @param array|Zend_Config $options (Optional) Options to set
     */
    public function __construct($options = null)
    {
        if (!extension_loaded('bz2')) {

            throw new Zend_Filter_Exception('This filter needs the bz2 extension');
        }
        parent::__construct($options);
    }

    /**
     * Returns the set blocksize
     *
     * @return integer
     */
    public function getBlocksize()
    {
        return $this->_options['blocksize'];
    }

    /**
     * Sets a new blocksize
     *
     * @param integer $level
     * @return Zend_Filter_Compress_Bz2
     */
    public function setBlocksize($blocksize)
    {
        if (($blocksize < 0) || ($blocksize > 9)) {

            throw new Zend_Filter_Exception('Blocksize must be between 0 and 9');
        }

        $this->_options['blocksize'] = (int) $blocksize;
        return $this;
    }

    /**
     * Returns the set archive
     *
     * @return string
     */
    public function getArchive()
    {
        return $this->_options['archive'];
    }

    /**
     * Sets the archive to use for de-/compression
     *
     * @param string $archive Archive to use
     * @return Zend_Filter_Compress_Bz2
     */
    public function setArchive($archive)
    {
        $this->_options['archive'] = (string) $archive;
        return $this;
    }

    /**
     * Compresses the given content
     *
     * @param  string $content
     * @return string
     */
    public function compress($content)
    {
        $archive = $this->getArchive();
        if (!empty($archive)) {
            $file = bzopen($archive, 'w');
            if (!$file) {

                throw new Zend_Filter_Exception("Error opening the archive '" . $archive . "'");
            }

            bzwrite($file, $content);
            bzclose($file);
            $compressed = true;
        } else {
            $compressed = bzcompress($content, $this->getBlocksize());
        }

        if (is_int($compressed)) {

            throw new Zend_Filter_Exception('Error during compression');
        }

        return $compressed;
    }

    /**
     * Decompresses the given content
     *
     * @param  string $content
     * @return string
     */
    public function decompress($content)
    {
        $archive = $this->getArchive();
        if (file_exists($content)) {
            $archive = $content;
        }

        if (file_exists($archive)) {
            $file = bzopen($archive, 'r');
            if (!$file) {

                throw new Zend_Filter_Exception("Error opening the archive '" . $content . "'");
            }

            $compressed = bzread($file);
            bzclose($file);
        } else {
            $compressed = bzdecompress($content);
        }

        if (is_int($compressed)) {

            throw new Zend_Filter_Exception('Error during decompression');
        }

        return $compressed;
    }

    /**
     * Returns the adapter name
     *
     * @return string
     */
    public function toString()
    {
        return 'Bz2';
    }
}


<?php

namespace Reaction\Base;

use Reaction\Helpers\ArrayHelper;
use Reaction\Helpers\IgnoreArrayValue;
use Reaction\Helpers\ReplaceArrayValue;
use Reaction\Helpers\UnsetArrayValue;
use Reaction\StaticApplicationInterface;

/**
 * Class ConfigReader. Reads content of file configs and merges those into one array
 * @package Reaction\Base
 */
class ConfigReader extends BaseObject
{
    /** @var string Config files dir path */
    public $path;
    /** @var string Application type (web|console) */
    public $appType = StaticApplicationInterface::APP_TYPE_WEB;
    /** @var array Config files extensions */
    public $extensions = ['php'];
    /** @var array Config files possible names */
    public $names;
    /** @var array Config array */
    public $data = [];
    /**
     * @var string Default configs path (relative to re-action/src dir)
     */
    public $configPathDefault = 'Config';

    /**
     * @inheritdoc
     */
    public function init() {
        if (isset($this->path)) {
            $this->data = $this->readData();
        }
    }

    /**
     * Get config data by its key
     * @param string $key
     * @param mixed  $defaultValue
     * @return mixed
     */
    public function get($key, $defaultValue = null) {
        return ArrayHelper::getValue($this->data, $key, $defaultValue);
    }

    /**
     * Set config data for a key
     * @param string $key
     * @param mixed  $value
     */
    public function set($key, $value) {
        ArrayHelper::setValue($this->data, $key, $value);
    }

    /**
     * Generate config files names
     * @return array
     */
    protected function generateNames() {
        $env = getenv('APP_ENV');
        $env = strtolower((!empty($env) ? $env : \Reaction::APP_ENV_PROD));
        $suffixes = ['', $env, 'local'];
        $templates = ['main', $this->appType];
        $configFiles = [];
        foreach ($templates as $tpl) {
            foreach ($suffixes as $sfx) {
                $tplSuffix = $sfx ? '.' . $sfx : '';
                foreach ($this->extensions as $ext) {
                    $configFiles[] = $tpl . $tplSuffix . '.' . $ext;
                }
            }
        }
        return $configFiles;
    }

    /**
     * Merge config data with given one
     * @param array       $data
     * @param string|null $key
     */
    public function merge($data = [], $key = null) {
        if (!isset($key)) {
            $this->data = ArrayHelper::merge($this->data, $data);
        } else {
            if (!isset($this->data[$key])) {
                $this->data[$key] = $data;
            } else {
                if (is_array($this->data[$key])) {
                    $this->data[$key] = ArrayHelper::merge($this->data[$key], $data);
                } else {
                    $this->data[$key] = $data;
                }
            }
        }
    }

    /**
     * Read configs and merge
     * @return array
     */
    public function readData() {
        if (empty($this->names)) {
            $this->names = $this->generateNames();
        }
        //Add default configs
        $defaultPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . $this->configPathDefault;
        $paths = [$defaultPath, $this->path];
        $confData = [];
        foreach ($paths as $basePath) {
            foreach ($this->names as $_name_) {
                $_fileName_ = $this->normalizeConfigPath($_name_, $basePath);
                if (($fileConfig = $this->readFileData($_fileName_)) !== null) {
                    $confData[] = $fileConfig;
                }
            }
        }
        if (empty($confData)) {
            return [];
        } elseif (count($confData) === 1) {
            return reset($confData);
        }
        return static::mergeConfigs(...$confData);
    }

    /**
     * Read particular config file
     * @param string $_fileName_
     * @return array|null
     */
    protected function readFileData($_fileName_ = null) {
        if (!file_exists($_fileName_)) {
            return null;
        }
        /** @noinspection PhpIncludeInspection */
        $_conf_data_ = include $_fileName_;
        return is_array($_conf_data_) ? $_conf_data_ : [];
    }

    /**
     * Normalize config file path
     * @param string $filePath
     * @param string|null $basePath
     * @return string
     */
    protected function normalizeConfigPath($filePath, $basePath = null) {
        if (null === $basePath) {
            $basePath = $this->path;
        }
        $fullPath = strpos($filePath, '/') === 0 ? $filePath : $basePath . DIRECTORY_SEPARATOR . $filePath;
        return $fullPath;
    }

    /**
     * Merge config arrays.
     * Same as ArrayHelper::merge() but without adding new elements to indexed array if already exists.
     * @param array $a
     * @param array $b
     * @return array
     */
    protected static function mergeConfigs($a, $b) {
        $args = func_get_args();
        $res = array_shift($args);
        while (!empty($args)) {
            foreach (array_shift($args) as $k => $v) {
                if ($v instanceof UnsetArrayValue) {
                    unset($res[$k]);
                } elseif ($v instanceof ReplaceArrayValue) {
                    $res[$k] = $v->value;
                } elseif ($v instanceof IgnoreArrayValue) {
                    if (!array_key_exists($k, $res)) {
                        $res[$k] = $v->value;
                    }
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
                    $res[$k] = self::mergeConfigs($res[$k], $v);
                } else {
                    $res[$k] = $v;
                }
            }
        }

        return ArrayHelper::cleanupMergedValues($res);
    }
}


<?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\Model;

use \CarteBlanche\Model\AbstractModel;

/**
 * The default CRUD model abstract class
 *
 * Any CRUD model must extend this abstract class
 *
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
abstract class AbstractCrud extends AbstractModel
{

    /**
     * The table name for the model
     *
     * This must be re-defined in the model (__unless it will send an error as the "_Crud_Model"
     * table doesn't exist__).
     */
    var $_table_name='_crud_model';

    /**
     * The table structure
     *
     * It is redefined just to precise that it must be an array.
     */
    var $_table_structure=array();

    /**
     * The object relations
     *
     * It is redefined just to precise that it must be an array.
     */
    var $_object_relations=array();

    /**
     * A flag to know if the object is loaded
     */
    private $__loaded=false;

    /**
     * A flag to know if one or every object relation(s) are loaded
     */
    private $__relations_loaded=false;

    /**
     * Returns TRUE if the object primary ID is set
     */
    public function exists()
    {
        return $this->id;
    }

// ------------------------------------------
// Setters / Getters
// ------------------------------------------

    /**
     * Sets the object primary ID
     *
     * @param int $id The primary ID of the object
     */
    public function setId($id = null)
    {
        if (!empty($id)) $this->id = $id;
    }

    /**
     * Gets the object primary ID
     *
     * @return int The object primary ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Sets the object data
     *
     * @param array $data An array of the object contents
     */
    public function setData($data = null)
    {
        if (!empty($data)) {
            foreach ($this->_table_structure as $_field=>$field_structure) {
                if (isset($data[$_field]))
                    $this->data[$_field] = $data[$_field];
                elseif (empty($this->data[$_field]))
                    $this->data[$_field] = null;
            }
        }
    }

    /**
     * Gets the object data
     *
     * @return array The object data
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Sets the object data
     *
     * @return array Empty object's data
     */
    public function createEmpty()
    {
        foreach ($this->_table_structure as $_field=>$field_structure) {
            $this->data[$_field] =
                isset($field_structure['default']) ? $field_structure['default'] : null;
        }
        return $this->getData();
    }

    /**
     * Sets one of the object related object
     *
     * @param string $model The name of the related model
     * @param array $data An array of the contents of the related object
     * @param int $id The related object primary ID in case of multi-relations
     */
    public function setRelated($model = null, $data = null, $id = null)
    {
        if (!empty($model) && !empty($data)) {
            if (!empty($id)) {
                if (!isset($this->data[$model]))
                    $this->data[$model] = array();
                if (!is_array($this->data[$model]))
                    $this->data[$model] = array_filter( array( $this->data[$model] ) );
                $this->data[$model][$id] = $data;
            } else
                $this->data[$model] = $data;
        }
    }

    /**
     * Gets one of the object related object
     *
     * @param string $model The name of the related model
     * @return mixed The recorded related object if so
     */
    public function getRelated($model = null)
    {
        return $this->data[$model];
    }

// ------------------------------------------
// CRUD Methods
// ------------------------------------------

    /**
     * @return array Must return the counting of all model objects
     */
    abstract function count();

    /**
     * @return array Must return the list of all model objects
     */
    abstract function dump();

    /**
     * @param int $id The primary ID of the object
     * @return object Must return the content of the object
     */
    abstract function read($id = null);

    /**
     * Create a new object
     *
     * @param array $data An array of the object contents
     * @return bool Must return a boolean indicating if the creation has succeeded
     */
    abstract function create($data = null);

    /**
     * Update an existing object
     *
     * @param int $id The primary ID of the object
     * @param array $data An array of the object contents
     * @return bool Must return a boolean indicating if the update has succeeded
     */
    abstract function update($id = null, $data = null);

    /**
     * Delete an object
     *
     * @param int $id The primary ID of the object
     * @return bool Must return a boolean indicating if the deletion has succeeded
     */
    abstract function delete($id = null);

}

// Endfile


<?php

namespace Zax\Application\UI;

use Nette;
use Zax\Latte\AjaxMacro;

trait TControlAjax {

	use TControlForward;

	/** @var bool */
	protected $ajaxEnabled = FALSE;

	/** @var bool */
	protected $autoAjax = FALSE;

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

	/**
	 * Enables AJAX for this component and all sub-components (if they implement IAjaxAware)
	 *
	 * @param bool $autoAjax Should call redrawControl() as soon as the component gets attached to presenter?
	 * @param array $exclude array of subcomponent names which should be excluded from AJAXification
	 * @return $this
	 */
	public function enableAjax($autoAjax = TRUE, array $exclude = NULL) {
		$this->ajaxEnabled = TRUE;
		$this->autoAjax = $autoAjax;
		if(is_array($exclude)) {
			$this->disableAjaxFor($exclude);
		}
		return $this;
	}

	/**
	 * Forces AJAX off on specified subcomponents (has higher priority than enableAjax())
	 *
	 * @param array $subcomponents array of subcomponent names which should be excluded from AJAXification
	 * @return $this
	 */
	public function disableAjaxFor(array $subcomponents = []) {
		$this->ajaxDisabledFor = $subcomponents;
		return $this;
	}

	/**
	 * Disables AJAX for this component.
	 * Do not call in factory, it won't work, use disableAjaxFor in parent component instead
	 *
	 * @return $this
	 */
	public function disableAjax() {
		$this->ajaxEnabled = FALSE;
		$this->autoAjax = FALSE;
		return $this;
	}

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

	/**
	 * Automatic snippet invalidation
	 * Do not call manually
	 */
	public function attached($presenter) {
		parent::attached($presenter);

		if($this->ajaxEnabled && $this->autoAjax && $presenter instanceof Nette\Application\UI\Presenter && $presenter->isAjax()) {
			$this->redrawControl();
		}
	}

	/**
	 * Useful for cases where you don't want automatic AJAX to kick in.
	 */
	protected function redrawNothing() {
		foreach($this->getPresenter()->getComponents(TRUE, 'Nette\Application\UI\IRenderable') as $component) {
			$component->redrawControl(NULL, FALSE);
		}
	}

	/**
	 * @param string $name
	 * @return Nette\ComponentModel\IComponent
	 */
	protected function createComponent($name) {
		$control = parent::createComponent($name);
		if($this->ajaxEnabled && !in_array($name, $this->ajaxDisabledFor) && ($control instanceof IAjaxAware)) {
			$control->enableAjax();
		}
		return $control;
	}

	/**
	 * If AJAX, then forward, else redirect.
	 *
	 * @param string $destination
	 * @param array $args
	 * @param array $snippets Not needed if we only have one unnamed snippet
	 * @param bool $presenterForward Prefer $presenter->forward() over $this->forward()
	 */
	final public function go($destination, $args = [], $snippets = [], $presenterForward = FALSE) {
		if($this->ajaxEnabled && $this->presenter->isAjax()) {
			foreach($snippets as $snippet) {
				$this->redrawControl($snippet);
			}

			if($presenterForward) {
				$this->presenterForward($destination, $args);
			} else {
				$this->forward($destination, $args);
			}
		} else {
			$this->redirect($destination, $args);
		}
	}

}


<?php

namespace Yami\SheetFight\Model;

use InvalidArgumentException;
use RangeException;

/**
 * Provides accurate frame data for a move.
 *
 * @author Kevin GITTENS <kgittens973@gmail.com>
 * @author Ludovic FLEURY <ludo.fleury@gmail.com>
 */
class FrameData implements FrameDataInterface
{
    /**
     * @var int Positive integer
     */
    private $startup;

    /**
     * @var int Positive integer
     */
    private $active;

    /**
     * @var int Positive integer
     */
    private $recovery;

    /**
     * @var int integer
     */
    private $guardAdvantage;

    /**
     * @var int integer
     */
    private $hitAdvantage;

    public function __construct($startup, $active, $recovery, $guardAdvantage, $hitAdvantage)
    {
        if (!is_int($startup)) {
            throw new InvalidArgumentException('The startup frames should be integer');
        }

        if ($startup < 0) {
            throw new RangeException('The startup frames should not be negative');
        }

        if (!is_int($active)) {
            throw new InvalidArgumentException('The active frames should be integer');
        }

        if ($active < 0) {
            throw new RangeException('The active frames should not be negative');
        }

        if (!is_int($recovery)) {
            throw new InvalidArgumentException('The recovery frames should be integer');
        }

        if ($recovery < 0) {
            throw new RangeException('The recovery frames should not be negative');
        }

        if (!is_int($guardAdvantage)) {
            throw new InvalidArgumentException('The guard advantage should be integer');
        }

        if (!is_int($hitAdvantage)) {
            throw new InvalidArgumentException('The hit advantage should be integer');
        }

        $this->startup = $startup;
        $this->active = $active;
        $this->recovery = $recovery;
        $this->guardAdvantage = $guardAdvantage;
        $this->hitAdvantage = $hitAdvantage;
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    public function getStartup()
    {
        return $this->startup;
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    public function getRecovery()
    {
        return $this->recovery;
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    public function getGuardAdvantage()
    {
        return $this->guardAdvantage;
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    public function getHitAdvantage()
    {
        return $this->hitAdvantage;
    }

    /**
     * {@inheritdoc}
     *
     * @param FrameDataInterface $otherFrameData
     *
     * @return bool
     */
    public function equals(FrameDataInterface $otherFrameData)
    {
        return
            $this->startup === $otherFrameData->getStartup() &&
            $this->active === $otherFrameData->getActive() &&
            $this->recovery === $otherFrameData->getRecovery() &&
            $this->guardAdvantage === $otherFrameData->getGuardAdvantage() &&
            $this->hitAdvantage === $otherFrameData->getHitAdvantage()
        ;
    }
}


<?php

namespace Philip\Plugin;

use Philip\AbstractPlugin as BasePlugin;
use Philip\IRC\Response;
use Philip\IRC\Event;

/**
 * Adds basic administrative functionality to the Philip IRC bot.
 *
 * @author Bill Israel <bill.israel@gmail.com>
 */
class AdminPlugin extends BasePlugin
{
    /**
     * Adds !quit, !join, and !leave commands to the bot:
     *
     * !quit <quit message> -- Tells the bot to quit the IRC server
     * Example usage:
     *      !quit ...aaand boom goes the dynamite.
     *
     * !join <channels>
     * Example usage:
     *      !join #example-room
     *      !join #example-room1 #example-room2
     *
     * !leave <channels> -- Tells the bot to leave channels
     * Example usage:
     *      !leave #example-room
     *      !leave #example-room1 #example-room2
     *
     * !say <channel> <msg> -- Tells the bot to send a message to the given channel
     * Example usage:
     *      !say #example-room Look I can talk.
     *
     * These commands only work via private message and only if the issuer
     * is in the ops array in the bot's configuration.
     */
    public function init()
    {
        $bot = $this->bot;
        $config = $bot->getConfig();

        // Allow the bot to join rooms
        $this->bot->onPrivateMessage("/^!join(.*)/", function(Event $event) use ($config, $bot) {
            $matches = $event->getMatches();
            $user = $event->getRequest()->getSendingUser();
            $rooms = explode(' ', $matches[0]);

            if ($bot->isAdmin($user)) {
                $event->addResponse(Response::join(implode(',', $rooms)));
            } else {
                $event->addResponse(Response::msg($user, "You're not the boss of me."));
            }
        });

        // Allow the bot to leave rooms
        $this->bot->onPrivateMessage("/^!leave(.*)/", function(Event $event) use ($config, $bot) {
            $matches = $event->getMatches();
            $user = $event->getRequest()->getSendingUser();
            $rooms = explode(' ', $matches[0]);

            if ($bot->isAdmin($user)) {
                $event->addResponse(Response::leave(implode(',', $rooms)));
            } else {
                $event->addResponse(Response::msg($user, "You're not the boss of me."));
            }
        });

        // Echo things into channels
        $this->bot->onPrivateMessage("/^!say ([#&][^\x07\x2C\s]{0,200}) (.+)/", function(Event $event) use ($config, $bot) {
            $matches = $event->getMatches();
            $user = $event->getRequest()->getSendingUser();

            if ($bot->isAdmin($user)) {
                $event->addResponse(Response::msg($matches[0], $matches[1]));
            } else {
                $event->addResponse(Response::msg($user, "You're not the boss of me."));
            }
        });

        // Quit gracefully
        $this->bot->onPrivateMessage("/^!quit(.*)/", function(Event $event) use ($config, $bot) {
            $matches = $event->getMatches();
            $user = $event->getRequest()->getSendingUser();
            $msg = $matches[0] ? trim($matches[0]) : 'Later, kids.';

            if ($bot->isAdmin($user)) {
                $event->addResponse(Response::quit($msg));
            } else {
                $event->addResponse(Response::msg($user, "You're not the boss of me."));
            }
        });
    }

    /**
     * Help messages!
     */
    public function displayHelp(Event $event)
    {
        return array(
            "!join <rooms> - join the specified rooms (admin req'd)",
            "!leave <rooms> - leave the specified rooms (admin req'd)",
            "!say <room> <msg> - say the message to the specified room (admin req'd)",
            "!quit <room> - quit the specified room (admin req'd)"
        );
    }

    /**
     * @see \Philip\AbstractPlugin#getName()
     */
    public function getName()
    {
        return 'AdminPlugin';
    }
}


<?php

/**
* This class inherits all functionality from Twig Template Engine and implements TemplatingInterface interface
* The class can be easy replaced with other class implementing same interface and this allows to
* change your templating engine easy without PHP changes in your app.
*
* LICENSE: MIT
*
* @category   Templating
* @package    Gelembjuk/Templating
* @copyright  Copyright (c) 2015 Roman Gelembjuk. (http://gelembjuk.com)
* @version    1.0
* @link       https://github.com/Gelembjuk/templating
*/

namespace Gelembjuk\Templating;

class TwigTemplating  extends \Twig_Environment implements TemplatingInterface {
	use TemplatingTrait;

	/**
	 * Check if there are all settings ready to do oprtation with templates saved in filesystem
	 * This is standard set of checks. We expect many engines can use only this
	 *
	 * @return boolean True on success and raises exception if there are problems
	 */
	protected function checkFileSystemTemplatingConfigured() {
		if (trim($this->template_dir_orig) == '') {
			throw new \Exception('Templates directory is not set');
		}
		if (!is_dir($this->template_dir_orig)) {
			throw new \Exception(sprintf('Templates directory %s not found',$this->template_dir_orig));
		}
		// compile dir is not needed
		if ($this->caching) {
			// if cache is On the cache path must be present
			if (!is_dir($this->cache_dir)) {
				throw new \Exception(sprintf('Templates cache directory %s not found',$this->cache_dir));
			}
			if (!is_writable($this->cache_dir)) {
				throw new \Exception(sprintf('Templates cache directory %s is not writable',$this->cache_dir));
			}
		}
		return true;
	}
	/**
	 * Init plugins and extra plugins on the engine
	 *
	 * @param string|array Path(s) to plugins sirectory
	 */
	protected function initPlugins($plugins = '') {
		if (is_dir(dirname(__FILE__).'/TwigPlugins')) {
			$this->loadPluginsFromDirectory(dirname(__FILE__).'/TwigPlugins');
		}

		if (isset($plugins)) {
			if (is_array($plugins)) {
				foreach ($plugins as $path) {
					$this->loadPluginsFromDirectory($path);
				}
			} elseif ($plugins != '') {
				$this->loadPluginsFromDirectory($plugins);
			}
		}
	}
	/**
	 * Returns a path to a directory with plugins. Can be used for cases
	 * when plugins should be used with an external application
	 *
	 * @return string Path to a directory with native plugins
	 */
	public function getNativePluginsDir() {
		if (is_dir(dirname(__FILE__).'/TwigPlugins')) {
			return dirname(__FILE__).'/TwigPlugins';
		}
	}
	/**
	 * Empty all previously set template variables
	 */
	public function cleanVars() {
		$this->template_vars = array();
	}
	/**
	 * Set new template variable
	 *
	 * @paral string $name Variable name
	 * @paral mixed $val Variable value. Can be different type, depends on supported types of engine
	 */
	public function setVar($name,$val) {
		$this->template_vars[$name] = $val;
	}
	/**
	 * Set many variables
	 *
	 * @paral array $list List of key/value pairs to set as variables
	 */
	public function setVars($list) {
		foreach ($list as $k=>$v) {
			$this->setVar($k,$v);
		}
	}
	/**
	 * Get previously set variable
	 *
	 * @paral string $name Variable name
	 *
	 * @return mixed Variable value
	 */
	public function getVar($name) {
		return $this->template_vars[$name];
	}
	/**
	 * Fetch prepared file template and return complete html document
	 *
	 * @return string HTML document with all data included
	 */
	protected function fetchFromFile() {
		// TODO
		// we don't check if there was loader already set. but it would be useful like optimization
		$loader = new \Twig_Loader_Filesystem($this->template_dir_orig);
		$this->setLoader($loader);

		if ($this->caching) {
			$this->setCache($this->cache_dir);
		}
		return $this->render($this->template.'.'.$this->templates_extension, $this->template_vars);
	}

	/**
	 * Fetch prepared string template and return complete html document
	 *
	 * @return string HTML document with all data included
	 */
	protected function fetchFromString() {
		// loader is created each time as value of index can be changed
		// maybe there is way to do this without creating new loader each time
		$loader = new \Twig_Loader_Array(array('index' => $this->template_data));
		$this->setLoader($loader);

		return $this->render('index', $this->template_vars);
	}
	/**
	 * Load plugins from a directory
	 */
	protected function loadPluginsFromDirectory($dirpath) {
		if (!is_dir($dirpath)) {
			return false;
		}

		$contents = @scandir($dirpath);

		if (is_array($contents)) {
			foreach ($contents as $file) {
				if (substr($file,-4) == '.php') {
					$class = '\\' . substr($file,0,-4);

					if($class != '') {
						// is this secure enough?
						// we don't use autoloader as we don't know how taht plugins are stored
						require_once($dirpath.'/'.$file);

						try {
							$twig_object = new $class();

							if ($twig_object instanceof \Twig_Extension) {
								$this->addExtension($twig_object);
							}
						} catch (\Extension $e) {
						}
					}
				}
			}
		}
	}
}


<?php namespace Ordercloud\Entities\Settings;

use JsonSerializable;
use Ordercloud\Entities\Organisations\OrganisationShort;

class Setting implements JsonSerializable
{
    /** @var integer */
    private $id;
    /** @var string */
    private $value;
    /** @var SettingKeyShort */
    private $key;
    /** @var string */
    private $startDate;
    /** @var string */
    private $endDate;
    /** @var OrganisationShort */
    private $organisation;

    public function __construct($id, $value, SettingKeyShort $key, $startDate, $endDate, OrganisationShort $organisation)
    {
        $this->id = $id;
        $this->value = $value;
        $this->key = $key;
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->organisation = $organisation;
    }

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

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @return SettingKeyShort
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @return string
     */
    public function getStartDate()
    {
        return $this->startDate;
    }

    /**
     * @return string
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * @return OrganisationShort
     */
    public function getOrganisation()
    {
        return $this->organisation;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        return [
            'id' => $this->getId(),
            'value' => $this->getValue(),
            'key' => $this->getKey(),
            'startDate' => $this->getStartDate(),
            'endDate' => $this->getEndDate(),
            'organisation' => $this->getOrganisation(),
        ];
    }
}


<?php
/**
 * Менеджер ORM
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Менеджер ORM
 *
 * @package ORM
 */
class ORM_Manager
{
    /**
     * Драйвер СУБД
     * @var ORM_Driver_SQL
     * @since 3.00
     */
    private $driver = null;

    /**
     * Реестр таблиц
     *
     * @var ORM_Table[]
     * @since 1.00
     */
    private $tables = array();

    /**
     * Типы полей
     *
     * @var array
     * @since 1.00
     */
    private $filedTypes = array(
        'bindings' => 'ORM_Field_Bindings',
        'boolean' => 'ORM_Field_Boolean',
        'date' => 'ORM_Field_Date',
        'datetime' => 'ORM_Field_Datetime',
        'entity' => 'ORM_Field_Entity',
        'entities' => 'ORM_Field_Entities',
        'float' => 'ORM_Field_Float',
        'integer' => 'ORM_Field_Integer',
        'string' => 'ORM_Field_String',
        'timestamp' => 'ORM_Field_Timestamp'
    );

    /**
     * Задаёт используемый драйвер СУБД
     *
     * Внимание! Этот метод можно вызывать только до первого обращения к {@link getDriver()}.
     *
     * @param ORM_Driver_SQL $driver
     *
     * @throws LogicException
     *
     * @since 3.00
     */
    public function setDriver(ORM_Driver_SQL $driver)
    {
        if (null !== $this->driver)
        {
            throw new LogicException('ORM Driver is already set');
        }
        $this->driver = $driver;
    }

    /**
     * Возвращает используемый драйвер СУБД
     *
     * @return ORM_Driver_SQL
     *
     * @since 3.00
     */
    public function getDriver()
    {
        if (null === $this->driver)
        {
            $this->driver = new ORM_Driver_MySQL($this);
        }
        return $this->driver;
    }

    /**
     * Возвращает объект таблицы для указанной сущности указанного плагина
     *
     * @param Eresus_Plugin $plugin      плагин, которому принадлежит сущность
     * @param string        $entityName  имя сущности (без имени плагина и слова «Entity»)
     *
     * @return ORM_Table
     *
     * @throws InvalidArgumentException
     *
     * @since 1.00
     */
    public function getTable($plugin, $entityName)
    {
        if (!($plugin instanceof Eresus_Plugin))
        {
            throw new InvalidArgumentException(
                sprintf('Argument 1 passed to %s must be an instance of Eresus_Plugin, %s given',
                    __METHOD__, is_object($plugin) ? get_class($plugin) : gettype($plugin)));
        }
        $className = get_class($plugin);
        $className .= '_Entity_Table_' . $entityName;
        if (!array_key_exists($className, $this->tables))
        {
            $this->tables[$className] = new $className($plugin, $this->getDriver());
        }
        return $this->tables[$className];
    }

    /**
     * Возвращает возможные типы полей
     *
     * @return ORM_Field_Abstract[]
     *
     * @since 3.00
     */
    public function getFieldTypes()
    {
        return $this->filedTypes;
    }

    /**
     * Регистрирует тип поля
     *
     * $typeClass должен быть потомком ORM_Field_Abstract и содержать в имени строку «_Field_».
     * Также должен существовать класс унаследованный от X, имя которого совпадает с $typeClass,
     * но строка «_Field_» заменена на «_Driver_SQL_»
     *
     * @param string $typeName   имя типа (латинские буквы в нижнем регистре и цифры)
     * @param string $typeClass  имя класса типа
     *
     * @since 3.00
     */
    public function registerField($typeName, $typeClass)
    {
        $this->filedTypes[$typeName] = $typeClass;
    }

    /**
     * Возвращает таблицу по имени класса сущности
     *
     * @param string $entityClass
     *
     * @throws InvalidArgumentException
     *
     * @return ORM_Table|null
     *
     * @since 3.00
     */
    public function getTableByEntityClass($entityClass)
    {
        if ('' === strval($entityClass))
        {
            throw new InvalidArgumentException(sprintf(
                'Argument 1 passed to %s can not be blank', __METHOD__));
        }
        $entityPluginName = substr($entityClass, 0, strpos($entityClass, '_'));
        $entityPluginName = strtolower($entityPluginName);
        $plugin = Eresus_Plugin_Registry::getInstance()->load($entityPluginName);
        if (!$plugin)
        {
            return null;
        }
        $entityName = substr($entityClass, strrpos($entityClass, '_') + 1);
        $table = self::getTable($plugin, $entityName);
        return $table;
    }
}