<?php

namespace Gaufrette\Core\Operator;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\File;

final class ChecksumOperator extends AbstractOperator implements CanLoad
{
    /**
     * {@inheritdoc}
     */
    public function supports(File $file, Adapter $adapter)
    {
        return $this->adapterHasBehavior($adapter, 'Gaufrette\Core\Adapter\KnowsChecksum');
    }

    /**
     * {@inheritdoc}
     */
    public function load(File $file, Adapter $adapter)
    {
        $file->setChecksum($adapter->readChecksum($file->getName()));
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\ModelInterface\Model\NodeInterface;

/**
 * Class HomeDataGenerator
 */
class HomeDataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
        $routePattern = "/";
        $language = "fr";

        return $this->generateNodeGlobal($language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeEn()
    {
        $routePattern = "/";
        $language = "en";

        return $this->generateNodeGlobal($language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeDe()
    {
        $routePattern = "/";
        $language = "de";

        return $this->generateNodeGlobal($language, $routePattern);
    }

    /**
     * @param string $language
     * @param string $routePattern
     *
     * @return Node
     */
    protected function generateNodeGlobal($language, $routePattern)
    {
        $nodeHome = $this->createBaseNode();
        $nodeHome->setLanguage($language);
        $nodeHome->setNodeId(NodeInterface::ROOT_NODE_ID);
        $nodeHome->setName('Homepage');
        $nodeHome->setVersionName($this->getVersionName($nodeHome));
        $nodeHome->setCreatedBy('fake_admin');
        $nodeHome->setParentId('-');
        $nodeHome->setOrder(0);
        $nodeHome->setRoutePattern($routePattern);
        $nodeHome->setInFooter(false);
        $nodeHome->setInMenu(true);
        $nodeHome->setSitemapChangefreq('hourly');
        $nodeHome->setSitemapPriority('0.8');

        return $nodeHome;
    }
}


<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Bridge\Console\Command;

use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command for executing actions.
 */
class ListCommand extends BridgeCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('list')
            ->setDescription('Lists registered components');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $services = $this->registry->getServices();

        $actions = array();

        foreach ($services as $service) {
            foreach ($service->getGroups() as $group) {
                foreach ($group->getActions() as $action) {
                    $actions[] = array(
                        $service->getName(),
                        $group->getName(),
                        $action->getName(),
                    );
                }
            }
        }

        $table = new Table($output);

        $table->setHeaders(array('Service', 'Group', 'Action'))
            ->setRows($actions);

        $table->render();
    }
}


<?php

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

namespace Predis\Protocol\Text;

use Predis\CommunicationException;
use Predis\Connection\CompositeConnectionInterface;
use Predis\Protocol\ProtocolException;
use Predis\Protocol\ResponseReaderInterface;

/**
 * Response reader for the standard Redis wire protocol.
 *
 * @link http://redis.io/topics/protocol
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ResponseReader implements ResponseReaderInterface
{
    protected $handlers;

    /**
     *
     */
    public function __construct()
    {
        $this->handlers = $this->getDefaultHandlers();
    }

    /**
     * Returns the default handlers for the supported type of responses.
     *
     * @return array
     */
    protected function getDefaultHandlers()
    {
        return array(
            '+' => new Handler\StatusResponse(),
            '-' => new Handler\ErrorResponse(),
            ':' => new Handler\IntegerResponse(),
            '$' => new Handler\BulkResponse(),
            '*' => new Handler\MultiBulkResponse(),
        );
    }

    /**
     * Sets the handler for the specified prefix identifying the response type.
     *
     * @param string                           $prefix  Identifier of the type of response.
     * @param Handler\ResponseHandlerInterface $handler Response handler.
     */
    public function setHandler($prefix, Handler\ResponseHandlerInterface $handler)
    {
        $this->handlers[$prefix] = $handler;
    }

    /**
     * Returns the response handler associated to a certain type of response.
     *
     * @param string $prefix Identifier of the type of response.
     *
     * @return Handler\ResponseHandlerInterface
     */
    public function getHandler($prefix)
    {
        if (isset($this->handlers[$prefix])) {
            return $this->handlers[$prefix];
        }

        return;
    }

    /**
     * {@inheritdoc}
     */
    public function read(CompositeConnectionInterface $connection)
    {
        $header = $connection->readLine();

        if ($header === '') {
            $this->onProtocolError($connection, 'Unexpected empty reponse header');
        }

        $prefix = $header[0];

        if (!isset($this->handlers[$prefix])) {
            $this->onProtocolError($connection, "Unknown response prefix: '$prefix'");
        }

        $payload = $this->handlers[$prefix]->handle($connection, substr($header, 1));

        return $payload;
    }

    /**
     * Handles protocol errors generated while reading responses from a
     * connection.
     *
     * @param CompositeConnectionInterface $connection Redis connection that generated the error.
     * @param string                       $message    Error message.
     */
    protected function onProtocolError(CompositeConnectionInterface $connection, $message)
    {
        CommunicationException::handle(
            new ProtocolException($connection, "$message [{$connection->getParameters()}]")
        );
    }
}


<?php

class WP_Post_Type_Util {

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

    /* Instance
    ---------------------------------------------- */

    /**
     * Instance of the class.
     *
     * @var WP_Post_Type_Util
     */
    protected static $instance = null;

    /**
     * Get accessor method for instance property.
     *
     * @return WP_Post_Type_Util Instance of the class.
     */
    public static function get_instance() {

        if ( null == self::$instance ) {

            self::$instance = new self;

        }

        return self::$instance;

    }

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

    /**
     * Determines whether or not post meta can be saved.
     *
     * @param int $post_id The id of the post being saved.
     * @param string $action The feature's action.
     * @param string $nonce The feature's nonce.
     * @return boolean Whether the post meta can saved or not.
     */
    public function can_save_post_meta( $post_id, $action, $nonce ) {

        $is_autosave = wp_is_post_autosave( $post_id );
        $is_revision = wp_is_post_revision( $post_id );
        $is_valid_nonce = ( isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ], $action ) );

        return ! ( $is_autosave || $is_revision ) && $is_valid_nonce;

    }

    /**
     * Determines if the current screen is the add or edit screen for a given post type.
     *
     * @param string $post_type Post type of screen to check.
     * @return boolean Whether or not the current screen is the add or edit screen for a given post type.
     */
    public function is_post_type_add_or_edit_screen( $post_type ) {

        return
            $this->is_post_type_add_screen( $post_type )
            || $this->is_post_type_edit_screen( $post_type );

    }

    /**
     * Determines if the current screen is the add screen for a given post type.
     *
     * @param string $post_type Post type of screen to check.
     * @return boolean Whether or not the current screen is the add screen for a given post type.
     */
    public function is_post_type_add_screen( $post_type ) {

        $screen = get_current_screen();

        return
            $this->is_post_type_screen( $post_type )
            && 'add' === $screen->action;

    }

    /**
     * Determines if the current screen is the edit screen for a given post type.
     *
     * @param string $post_type Post type of screen to check.
     * @return boolean Whether or not the current screen is the edit screen for a given post type.
     */
    public function is_post_type_edit_screen( $post_type ) {

        return
            $this->is_post_type_screen( $post_type )
            && ( array_key_exists( 'action', $_REQUEST ) && 'edit' === $_REQUEST[ 'action' ] );

    }

    /**
     * Determines if the current screen is for a given post type.
     *
     * @param string $post_type Post type of screen to check.
     * @return boolean Whether or not the current screen is  for a given post type.
     */
    public function is_post_type_screen( $post_type ) {

        $screen = get_current_screen();

        return $post_type === $screen->post_type;

    }

    /**
     * Determines if the post meta being saved is for a given post type.
     *
     * @param string $post_type Post type of post meta to save.
     * @return boolean Whether or not the post meta being saved is for a given post type.
     */
    public function is_post_type_saving_post_meta( $post_type ) {

        return ! empty( $_POST ) && $post_type === $_POST[ 'post_type' ];

    }

}


<?php

/**
 * Manage Sessions
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib;

/**
 * This class manage the Sessions
 *
 * @category  	lib
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Session
{
	/**
	 * constructor
	 *
	 * @access public
	 * @return \Venus\lib\Session
	 */
	public function __construct()
	{
		$this->start();
	}

  	/**
  	 * set a value
  	 *
  	 * @access public
  	 * @param  string $sName name of the session
  	 * @param  mixed $mValue value of this sesion var
  	 * @return Session
  	 */
  	public function set(string $sName, $mValue) : Session
	{
    	$_SESSION[$sName] = $mValue;
    	return $this;
  	}

  	/**
  	 * set a value
  	 *
  	 * @access public
  	 * @param  string $sName name of the session
  	 * @return mixed
  	 */
  	public function get(string $sName)
	{
  		if (isset($_SESSION[$sName])) { return $_SESSION[$sName]; }
  		else { return false; }
  	}

  	/**
  	 * start the session
  	 *
  	 * @access public
  	 * @return mixed
  	 */
  	public function start()
	{
		if (!session_id()) { session_start(); }
  	}

  	/**
  	 * set a flashbag value
  	 *
  	 * @access public
  	 * @param  string $sName name of the session
  	 * @param  string $sValue value of this sesion var
  	 * @return \Venus\lib\Session
	 */
 	 public function setFlashBag($sName, $sValue)
	 {
  		if (!isset($_SESSION['flashbag'])) { $_SESSION['flashbag'] = array(); }

  		$_SESSION['flashbag'][$sName] = $sValue;
  		return $this;
	}

	/**
	 * destroy the session
	 *
	 * @access public
	 * @return mixed
	 */
	public function destroy()
	{
		session_start();

		$_SESSION = array();

		if (ini_get("session.use_cookies")) {

			$aParams = session_get_cookie_params();

		    setcookie(session_name(), '', time() - 42000,
		        $aParams["path"], $aParams["domain"],
		        $aParams["secure"], $aParams["httponly"]
		    );
		}

		session_destroy();
	}

    /**
     * @return mixed
     */
    public function getSessionId() : string
    {
        return session_id();
    }
}


<?php

namespace Isolate\LazyObjects\Object\Property;

use Isolate\LazyObjects\Exception\InvalidArgumentException;
use Isolate\LazyObjects\Object\PropertyAccessor;
use Isolate\LazyObjects\Proxy\LazyProperty;

/**
 * @api
 */
final class Initializer
{
    /**
     * @var array
     */
    private $initializedProperties;

    /**
     * @var PropertyAccessor
     */
    private $propertyAccessor;

    public function __construct()
    {
        $this->propertyAccessor = new PropertyAccessor();
        $this->initializedProperties = [];
    }

    /**
     * @param array $lazyProperties
     * @param string $triggerMethod
     * @param $targetObject
     * @throws InvalidArgumentException
     *
     * @api
     */
    public function initialize($lazyProperties = [], $triggerMethod, $targetObject)
    {
        foreach ($lazyProperties as $property) {
            /* @var $property LazyProperty */
            $this->validateLazyProperty($property);

            if ($this->wasInitialized($property)) {
                continue ;
            }

            if (!$property->hasTriggers()) {
                $this->initializeProperty($property, $targetObject);
                continue ;
            }

            if ($property->isTriggeredBy($triggerMethod)) {
                $this->initializeProperty($property, $targetObject);
                continue ;
            }
        }
    }

    /**
     * @param $property
     * @throws InvalidArgumentException
     */
    private function validateLazyProperty($property)
    {
        if (!$property instanceof LazyProperty) {
            throw new InvalidArgumentException("Only lazy properties can be initialized");
        }
    }

    /**
     * @param LazyProperty $property
     * @return bool
     */
    private function wasInitialized(LazyProperty $property)
    {
        return in_array((string) $property->getName(), $this->initializedProperties, true);
    }

    /**
     * @param LazyProperty $property
     */
    private function markAsInitialized(LazyProperty $property)
    {
        $this->initializedProperties[] = (string) $property->getName();
    }

    /**
     * @param LazyProperty $property
     * @param $targetObject
     */
    private function initializeProperty(LazyProperty $property, $targetObject)
    {
        $defaultValue = $this->propertyAccessor->get($targetObject, (string)$property->getName());
        $newValue = $property->getValueInitializer()->initialize($targetObject, $defaultValue);
        $this->propertyAccessor->set($targetObject, (string)$property->getName(), $newValue);
        $this->markAsInitialized($property);

        if ($property->hasInitializationCallback()) {
            $property->getInitializationCallback()->execute($defaultValue, $newValue, $targetObject);
        }
    }
}


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

namespace Predis\Connection;

use Predis\Command\CommandInterface;
use Predis\Response\Error as ErrorResponse;
use Predis\Response\ErrorInterface as ErrorResponseInterface;
use Predis\Response\Status as StatusResponse;

/**
 * Standard connection to Redis servers implemented on top of PHP's streams.
 * The connection parameters supported by this class are:.
 *
 *  - scheme: it can be either 'redis', 'tcp', 'rediss', 'tls' or 'unix'.
 *  - host: hostname or IP address of the server.
 *  - port: TCP port of the server.
 *  - path: path of a UNIX domain socket when scheme is 'unix'.
 *  - timeout: timeout to perform the connection (default is 5 seconds).
 *  - read_write_timeout: timeout of read / write operations.
 *  - async_connect: performs the connection asynchronously.
 *  - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
 *  - persistent: the connection is left intact after a GC collection.
 *  - ssl: context options array (see http://php.net/manual/en/context.ssl.php)
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class StreamConnection extends AbstractConnection
{
    /**
     * Disconnects from the server and destroys the underlying resource when the
     * garbage collector kicks in only if the connection has not been marked as
     * persistent.
     */
    public function __destruct()
    {
        if (isset($this->parameters->persistent) && $this->parameters->persistent) {
            return;
        }

        $this->disconnect();
    }

    /**
     * {@inheritdoc}
     */
    protected function assertParameters(ParametersInterface $parameters)
    {
        switch ($parameters->scheme) {
            case 'tcp':
            case 'redis':
            case 'unix':
                break;

            case 'tls':
            case 'rediss':
                $this->assertSslSupport($parameters);
                break;

            default:
                throw new \InvalidArgumentException("Invalid scheme: '$parameters->scheme'.");
        }

        return $parameters;
    }

    /**
     * Checks needed conditions for SSL-encrypted connections.
     *
     * @param ParametersInterface $parameters Initialization parameters for the connection.
     *
     * @throws \InvalidArgumentException
     */
    protected function assertSslSupport(ParametersInterface $parameters)
    {
        if (
            filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN) &&
            version_compare(PHP_VERSION, '7.0.0beta') < 0
        ) {
            throw new \InvalidArgumentException('Persistent SSL connections require PHP >= 7.0.0.');
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createResource()
    {
        switch ($this->parameters->scheme) {
            case 'tcp':
            case 'redis':
                return $this->tcpStreamInitializer($this->parameters);

            case 'unix':
                return $this->unixStreamInitializer($this->parameters);

            case 'tls':
            case 'rediss':
                return $this->tlsStreamInitializer($this->parameters);

            default:
                throw new \InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'.");
        }
    }

    /**
     * Creates a connected stream socket resource.
     *
     * @param ParametersInterface $parameters Connection parameters.
     * @param string              $address    Address for stream_socket_client().
     * @param int                 $flags      Flags for stream_socket_client().
     *
     * @return resource
     */
    protected function createStreamSocket(ParametersInterface $parameters, $address, $flags)
    {
        $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);

        if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags)) {
            $this->onConnectionError(trim($errstr), $errno);
        }

        if (isset($parameters->read_write_timeout)) {
            $rwtimeout = (float) $parameters->read_write_timeout;
            $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
            $timeoutSeconds = floor($rwtimeout);
            $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
            stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
        }

        if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
            $socket = socket_import_stream($resource);
            socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
        }

        return $resource;
    }

    /**
     * Initializes a TCP stream resource.
     *
     * @param ParametersInterface $parameters Initialization parameters for the connection.
     *
     * @return resource
     */
    protected function tcpStreamInitializer(ParametersInterface $parameters)
    {
        if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $address = "tcp://$parameters->host:$parameters->port";
        } else {
            $address = "tcp://[$parameters->host]:$parameters->port";
        }

        $flags = STREAM_CLIENT_CONNECT;

        if (isset($parameters->async_connect) && $parameters->async_connect) {
            $flags |= STREAM_CLIENT_ASYNC_CONNECT;
        }

        if (isset($parameters->persistent)) {
            if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
                $flags |= STREAM_CLIENT_PERSISTENT;

                if ($persistent === null) {
                    $address = "{$address}/{$parameters->persistent}";
                }
            }
        }

        $resource = $this->createStreamSocket($parameters, $address, $flags);

        return $resource;
    }

    /**
     * Initializes a UNIX stream resource.
     *
     * @param ParametersInterface $parameters Initialization parameters for the connection.
     *
     * @return resource
     */
    protected function unixStreamInitializer(ParametersInterface $parameters)
    {
        if (!isset($parameters->path)) {
            throw new \InvalidArgumentException('Missing UNIX domain socket path.');
        }

        $flags = STREAM_CLIENT_CONNECT;

        if (isset($parameters->persistent)) {
            if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
                $flags |= STREAM_CLIENT_PERSISTENT;

                if ($persistent === null) {
                    throw new \InvalidArgumentException(
                        'Persistent connection IDs are not supported when using UNIX domain sockets.'
                    );
                }
            }
        }

        $resource = $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags);

        return $resource;
    }

    /**
     * Initializes a SSL-encrypted TCP stream resource.
     *
     * @param ParametersInterface $parameters Initialization parameters for the connection.
     *
     * @return resource
     */
    protected function tlsStreamInitializer(ParametersInterface $parameters)
    {
        $resource = $this->tcpStreamInitializer($parameters);
        $metadata = stream_get_meta_data($resource);

        // Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0).
        if (isset($metadata['crypto'])) {
            return $resource;
        }

        if (is_array($parameters->ssl)) {
            $options = $parameters->ssl;
        } else {
            $options = array();
        }

        if (!isset($options['crypto_type'])) {
            $options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT;
        }

        if (!stream_context_set_option($resource, array('ssl' => $options))) {
            $this->onConnectionError('Error while setting SSL context options');
        }

        if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) {
            $this->onConnectionError('Error while switching to encrypted communication');
        }

        return $resource;
    }

    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        if (parent::connect() && $this->initCommands) {
            foreach ($this->initCommands as $command) {
                $response = $this->executeCommand($command);

                if ($response instanceof ErrorResponseInterface) {
                    $this->onConnectionError("`{$command->getId()}` failed: $response", 0);
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function disconnect()
    {
        if ($this->isConnected()) {
            fclose($this->getResource());
            parent::disconnect();
        }
    }

    /**
     * Performs a write operation over the stream of the buffer containing a
     * command serialized with the Redis wire protocol.
     *
     * @param string $buffer Representation of a command in the Redis wire protocol.
     */
    protected function write($buffer)
    {
        $socket = $this->getResource();

        while (($length = strlen($buffer)) > 0) {
            $written = @fwrite($socket, $buffer);

            if ($length === $written) {
                return;
            }

            if ($written === false || $written === 0) {
                $this->onConnectionError('Error while writing bytes to the server.');
            }

            $buffer = substr($buffer, $written);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function read()
    {
        $socket = $this->getResource();
        while (true) {
            try {
                $this->select([$socket], [], []);
            } catch (\Exception $e) {
                if ($e == 'Interrupted system call') {
                    pcntl_signal_dispatch();
                    continue;
                }
            }
            $chunk = fgets($socket);
            break;
        }

        if ($chunk === false || $chunk === '') {
            $this->onConnectionError('Error while reading line from the server.');
        }

        $prefix = $chunk[0];
        $payload = substr($chunk, 1, -2);

        switch ($prefix) {
            case '+':
                return StatusResponse::get($payload);

            case '$':
                $size = (int) $payload;

                if ($size === -1) {
                    return;
                }

                $bulkData = '';
                $bytesLeft = ($size += 2);

                do {
                    $chunk = fread($socket, min($bytesLeft, 4096));

                    if ($chunk === false || $chunk === '') {
                        $this->onConnectionError('Error while reading bytes from the server.');
                    }

                    $bulkData .= $chunk;
                    $bytesLeft = $size - strlen($bulkData);
                } while ($bytesLeft > 0);

                return substr($bulkData, 0, -2);

            case '*':
                $count = (int) $payload;

                if ($count === -1) {
                    return;
                }

                $multibulk = array();

                for ($i = 0; $i < $count; ++$i) {
                    $multibulk[$i] = $this->read();
                }

                return $multibulk;

            case ':':
                $integer = (int) $payload;

                return $integer == $payload ? $integer : $payload;

            case '-':
                return new ErrorResponse($payload);

            default:
                $this->onProtocolError("Unknown response prefix: '$prefix'.");

                return;
        }
    }

    function select($r, $w, $e)
    {
        set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext = null) {
            $last_error = compact('errno', 'errstr', 'errfile', 'errline', 'errcontext');

            // fwrite notice that the stream isn't ready
            if (strstr($errstr, 'Resource temporarily unavailable')) {
                // it's allowed to retry
                return;
            }
            // stream_select warning that it has been interrupted by a signal
            if (strstr($errstr, 'Interrupted system call')) {
                throw new \Exception("Interrupted system call");
                // it's allowed while processing signals
                return;
            }
            // raise all other issues to exceptions
            throw new \Exception($errstr, $errno);
        });

        try {
            $count = stream_select($r, $w, $e, 10.0);
        } catch (\Exception $e) {
            throw $e;
        } finally {
            restore_error_handler();
        }
        return $count;
    }

    /**
     * {@inheritdoc}
     */
    public function writeRequest(CommandInterface $command)
    {
        $commandID = $command->getId();
        $arguments = $command->getArguments();

        $cmdlen = strlen($commandID);
        $reqlen = count($arguments) + 1;

        $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";

        foreach ($arguments as $argument) {
            $arglen = strlen($argument);
            $buffer .= "\${$arglen}\r\n{$argument}\r\n";
        }

        $this->write($buffer);
    }
}


<?php

/**
 * Manage Log class in your application
 *
 * @category  	Venus\lib
 * @package		Venus\lib\Log\
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Log;

use \Venus\lib\Debug as Debug;
use \Venus\lib\Log\LoggerInterface  as LoggerInterface ;
use \Venus\lib\Log\LogLevel as LogLevel;

/**
 * Manage Log class in your application
 *
 * @category  	Venus\lib
 * @package		Venus\lib\Log\
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
abstract class AbstractLogger implements LoggerInterface
{
	/**
     * Logs with an arbitrary level.
     *
     * @param mixed $level
     * @param string $message
     * @param array $context
     * @return void
     */
    public function log($level, $message, array $context = array())
    {
        if (!isset($context['file'])) { $context['file'] = __FILE__; }
        if (!isset($context['line'])) { $context['line'] = __LINE__; }
        if ($level === null) { $level = LogLevel::INFO; }

        if (Debug::isDebug() === true) {

            if (Debug::getKindOfReportLog() === 'error_log' || Debug::getKindOfReportLog() === 'all') {

                error_log($context['file'].'> (l.'.$context['line'].') '.$message);
            }
            if (Debug::getKindOfReportLog() === 'screen' || Debug::getKindOfReportLog() === 'all') {

                echo '

';
                echo $context['file'].'> (l.'.$context['line'].') '.$message.'
'."\n";
                echo '

';
            }
        }
	}
}


<?php

/*
 * This file is part of the Meta Reader package.
 *
 * (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Temp\MetaReader;

use Temp\MetaReader\Value\MetaValue;
use Temp\MetaReader\Value\ValueBag;

/**
 * Exif extension reader.
 *
 * @author Stephan Wentz <stephan@wentz.it>
 */
class ExifExtensionReader implements ReaderInterface
{
    /**
     * {@inheritdoc}
     */
    public function available()
    {
        return extension_loaded('exif') && function_exists('exif_read_data');
    }

    /**
     * {@inheritdoc}
     */
    public function supports($filename)
    {
        try {
            $result = @\exif_imagetype($filename);
        } catch (\Exception $e) {
            return false;
        }

        return $result !== false;
    }

    /**
     * {@inheritdoc}
     */
    public function read($filename)
    {
        $meta = new ValueBag();

        try {
            $result = @\exif_read_data($filename, '', true);
        } catch (\Exception $e) {
            return $meta;
        }

        if (!empty($result['IFD0'])) {
            foreach ($result['IFD0'] as $key => $value) {
                $meta->set("exif.$key", new MetaValue($value));
            }
        }

        return $meta;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Adapter;

use Doctrine\Common\Collections\ArrayCollection;
use Dothiv\Bundle\ContentfulBundle\Client\HttpClientInterface;
use Dothiv\Bundle\ContentfulBundle\DothivContentfulBundleEvents;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulAssetEvent;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulContentTypeEvent;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulContentTypesEvent;
use Dothiv\Bundle\ContentfulBundle\Event\ContentfulEntryEvent;
use Dothiv\Bundle\ContentfulBundle\Event\DeletedContentfulEntryEvent;
use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use Dothiv\Bundle\ContentfulBundle\Exception\RuntimeException;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulAsset;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulContentType;
use Dothiv\Bundle\ContentfulBundle\Item\DeletedContentfulEntry;
use Dothiv\Bundle\ContentfulBundle\Logger\LoggerAwareTrait;
use Dothiv\Bundle\ContentfulBundle\Adapter\ContentfulEntityReader;
use PhpOption\Option;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class HttpClientAdapter implements ContentfulApiAdapter
{
    use LoggerAwareTrait;

    /**
     * @var string
     */
    private $endpoint = 'https://cdn.contentful.com';

    /**
     * @var HttpClientInterface
     */
    private $client;

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

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

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

    /**
     * @param string                   $spaceId
     * @param HttpClientInterface      $client
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct($spaceId, HttpClientInterface $client, EventDispatcherInterface $dispatcher)
    {
        $this->spaceId    = $spaceId;
        $this->client     = $client;
        $this->dispatcher = $dispatcher;
    }

    /**
     * @return string The next sync URL.
     */
    public function sync()
    {
        $this->log('Syncing from %s ...', $this->getNextSyncUrl());
        $types = $this->syncContentTypes();
        $this->syncFrom($this->getNextSyncUrl(), $types);
        return $this->nextSyncUrl;
    }

    /**
     * @return ContentfulContentType[]|ArrayCollection
     */
    protected function syncContentTypes()
    {
        $data   = $this->fetch($this->buildUrl('content_types'));
        $types  = new ArrayCollection();
        $reader = new ContentfulContentTypeReader($this->spaceId);
        foreach ($data->items as $ctype) {
            $contentType = $reader->getContentType($ctype);
            $this->log('Sync: %s', $contentType);
            /** @var ContentfulContentTypeEvent $event */
            $event                        = $this->dispatcher->dispatch(
                DothivContentfulBundleEvents::CONTENT_TYPE_SYNC,
                new ContentfulContentTypeEvent($contentType)
            );
            $types[$contentType->getId()] = $event->getContentType();
        }
        $this->dispatcher->dispatch(
            DothivContentfulBundleEvents::CONTENT_TYPE_SYNC_ALL,
            new ContentfulContentTypesEvent($types)
        );
        return $types;
    }

    protected function syncFrom($url, ArrayCollection $contentTypes)
    {
        $reader = new ContentfulEntityReader($this->spaceId, $contentTypes);
        $data   = $this->fetch($url);
        foreach ($data->items as $item) {
            $entry = $reader->getEntry($item);
            if ($entry) {
                if ($entry instanceof DeletedContentfulEntry) {
                    $this->log('Delete: %s', $entry);
                    $this->dispatcher->dispatch(DothivContentfulBundleEvents::ENTRY_DELETE, new DeletedContentfulEntryEvent($entry));
                } elseif ($entry instanceof ContentfulAsset) {
                    $this->log('Sync: %s', $entry);
                    $this->dispatcher->dispatch(DothivContentfulBundleEvents::ASSET_SYNC, new ContentfulAssetEvent($entry));
                } else {
                    $this->log('Sync: %s', $entry);
                    $this->dispatcher->dispatch(DothivContentfulBundleEvents::ENTRY_SYNC, new ContentfulEntryEvent($entry));
                }
            }
        }
        if (property_exists($data, 'nextPageUrl')) {
            $this->log('Continuing with next page.');
            $this->syncFrom($data->nextPageUrl, $contentTypes);
        }
        if (property_exists($data, 'nextSyncUrl')) {
            // FIXME: store next sync URL.
            $this->nextSyncUrl = $data->nextSyncUrl;
            $this->log('Done. Start next sync from %s', $data->nextSyncUrl);
        }
    }

    /**
     * @return string
     */
    protected function getNextSyncUrl()
    {
        return Option::fromValue($this->nextSyncUrl)->getOrElse($this->buildUrl('sync', array('initial' => 'true')));
    }

    public function setNextSyncUrl($nextSyncUrl)
    {
        $this->nextSyncUrl = $nextSyncUrl;
    }

    /**
     * @param string $path
     * @param array  $params
     *
     * @return string
     */
    protected function buildUrl($path, array $params = null)
    {
        if ($params == null) {
            $params = array();
        }
        $url = sprintf(
            '%s/spaces/%s/%s?%s',
            $this->endpoint,
            urlencode($this->spaceId),
            $path,
            http_build_query($params)
        );
        return $url;
    }

    /**
     * @param string $url
     *
     * @return object
     * @throws RuntimeException
     */
    protected function fetch($url)
    {
        $response = $this->client->get($url);
        $data     = json_decode($response);
        if (!is_object($data) || !property_exists($data, 'items')) {
            throw new RuntimeException(
                sprintf(
                    'Missing items in response for "%s"',
                    $url
                )
            );
        }
        $this->log('Fetched %d items.', count($data->items));
        return $data;
    }

    /**
     * @param string $endpoint
     *
     * @throws InvalidArgumentException
     */
    public function setEndpoint($endpoint)
    {
        if (!filter_var($endpoint, FILTER_VALIDATE_URL)) {
            throw new InvalidArgumentException(
                sprintf(
                    'Not an url: %s',
                    $endpoint
                )
            );
        }
        $parts          = parse_url($endpoint);
        $this->endpoint = sprintf('%s://%s', $parts['scheme'], $parts['host']);
    }
}


<?php
namespace Devedge\XmlRpc;

use Devedge\Log\NoLog;
use Devedge\XmlRpc\Client\XmlRpcBuilder;
use Devedge\XmlRpc\Client\XmlRpcParser;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;

/**
 * Class Server
 */
class Client implements LoggerAwareInterface
{
    use LoggerAwareTrait;

    /**
     * @var string Version string (to be updated by RMT, dont change manually)
     */
    public static $version = "0.2.0";

    /**
     * @var
     */
    protected $url;

    /**
     * @var
     */
    protected $namespace;

    public function __construct($url, $namespace = null)
    {

        $this->url = $url;
        $this->namespace = $namespace;
    }

    /**
     * invoke a call to the RPC server
     * @param string $method
     * @param array $arguments
     * @return array
     */
    public function invokeRpcCall($method, $arguments = [])
    {
        if (!is_null($this->namespace)) {
            $method = $this->namespace . '.' . $method;
        }

        $body = XmlRpcBuilder::createRequest($method, $arguments);

        $guzzle = new \GuzzleHttp\Client();

        $this->getLogger()->info("sending request for $method to {$this->url}");
        $this->getLogger()->debug(
            "sending request for $method to {$this->url}, with parameters: " . print_r($arguments, true)
        );

        $response = $guzzle->post(
            $this->url,
            [
                'body' => $body,
                'headers' => [
                    'User-Agent' => 'Devedge\XmlRpc\Client/' .self::$version,
                    'Content-Type' => 'text/xml'
                ]
            ]
        );

        // if we have a fault, we will throw an exception
        if ($response->xml()->fault->count() > 0) {
            $this->logger->warning("serverside error occured, details: " . $response->getBody());
            throw XmlRpcParser::parseFault($response->xml()->fault);
        }

        // responses always have only one param
        return array_shift(XmlRpcParser::parseParams($response->xml()->params));
    }

    protected function getLogger()
    {
        // if no logger is set on the first getLogger call we set a null Logger, so we can proceed without
        // errors.
        if (is_null($this->logger)) {
            $this->logger = new NoLog();
        }
        return $this->logger;
    }
}


<?php
namespace app\manage\block;

class SelectBlock extends Block
{

    /**
     * form
     *
     * @param array $data
     * @return string
     */
    public static function form($data = [])
    {
        $data = array_merge(self::$default_form, $data);

        $html = '
';
        $html .= '
' . $data['title'] . '
';
        $html .= '
';
        $html .= '<select name="' . $data['name'] . '" data-am-selected="{btnSize: \'sm\'}">';
        foreach ($data['list'] as $vo) {
            if ($data['value'] === $vo['value']) {
                $html .= '<option selected value="' . $vo['value'] . '">' . $vo['name'] . '</option>';
            } else {
                $html .= '<option value="' . $vo['value'] . '">' . $vo['name'] . '</option>';
            }
        }
        $html .= '</select>';
        $html .= '
';
        $html .= '
';

        return $html;
    }

    /**
     * search
     *
     * @param array $data
     * @return string
     */
    public static function search($data = [])
    {
        $data = array_merge(self::$default_search, $data);

        $html = '
';
        $html .= '
';
        $html .= '<select name="' . $data['name'] . '" class="nd-search-field" data-am-selected="{btnSize: \'sm\'}">';
        if ($data['all']) {
            $html .= '<option value="**">不限</option>';
        }
        foreach ($data['list'] as $vo) {
            if ($data['value'] === $vo['value']) {
                $html .= '<option selected value="' . $vo['value'] . '">' . $vo['name'] . '</option>';
            } else {
                $html .= '<option value="' . $vo['value'] . '">' . $vo['name'] . '</option>';
            }
        }
        $html .= '</select>';
        $html .= '
';
        $html .= '
';

        return $html;
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (is_array(end($arguments))) {
            foreach (array_pop($arguments) as $member => $score) {
                $arguments[] = $score;
                $arguments[] = $member;
            }
        }

        parent::setArguments($arguments);
    }
}


<?php

/*
 * This file is part of the Snide osrc-httpClient package.
 *
 * (c) Pascal DENIS <pascal.denis.75@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Snide\VersionEye;

use Snide\VersionEye\Model\Project;
use Snide\VersionEye\Model\User;
use Snide\VersionEye\Hydrator\SimpleHydrator;
use Guzzle\Http\Client as GuzzleClient;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class Client
 *
 * @author Pascal DENIS <pascal.denis.75@gmail.com>
 */
class Client
{
    /**
     * API URL
     *
     * @var string
     */
    protected $endpoint = 'https://www.versioneye.com/api';

    /**
     * Object Hydrator
     *
     * @var SimpleHydrator
     */
    protected $hydrator;

    /**
     * Guzzle Client
     *
     * @var \Guzzle\Http\Client
     */
    protected $httpClient;

    /**
     * API Key
     * @var string
     */
    protected $apiKey;

    /**
     * Constructor
     *
     * @param string $apiKey
     * @param Hydrator\SimpleHydrator $hydrator
     */
    public function __construct($apiKey = '', SimpleHydrator $hydrator = null)
    {
        if (null === $hydrator) {
            $hydrator = new SimpleHydrator();
        }

        if ($apiKey) {
            $this->setApiKey($apiKey);
        }

        $this->setHydrator($hydrator);

        $this->httpClient = new GuzzleClient($this->endpoint, array());
    }

    /**
     * Fetch data from Projects
     *
     * @return array
     */
    public function fetchProjects()
    {
        $response = $this->getResponse('get', 'v2/projects');
        $projects = array();
        if(is_array($response)) {
            foreach($response as $data) {
                $projects[] = $this->hydrator->hydrate(new Project(), $data);
            }
        }

        return $projects;
    }

    /**
     * Fetch data from Project
     *
     * @param Model\Project $project
     * @return Project
     */
    public function fetchProject(Project $project)
    {
        $response = $this->getResponse(
            'get',
            sprintf('v2/projects/%s', $project->getProjectKey())
        );

        return $this->hydrator->hydrate($project, $response);
    }

    /**
     * Update a project
     *
     * @param Project $project
     * @param string $composerJson path
     * @return array
     */
    public function updateProject(Project $project, $composerJson)
    {

        $response = $this->getResponse(
            'post',
            sprintf('v2/projects/%s', $project->getProjectKey()),
            array(),
            array('project_file' => $composerJson)
        );

        return $this->hydrator->hydrate($project, $response);
    }

    /**
     * Create a project
     *
     * @param string $composerJson
     * @return Project
     */
    public function createProject($composerJson)
    {
        $response = $this->getResponse('post', 'v2/projects', array(), array('upload' => $composerJson));

        return $this->hydrator->hydrate(new Project(), $response);
    }

    /**
     * Fetch me
     *
     * @return User
     */
    public function fetchMe()
    {
        $response = $this->getResponse('get', 'v2/me', array());

        return $this->hydrator->hydrate(new User(), $response);
    }

    /**
     * Fetch a user by username
     *
     * @param User $user
     * @return User
     */
    public function fetchUser(User $user)
    {
        $response = $this->getResponse(
            'get',
            sprintf('v2/users/%s', $user->getUsername())
        );

        return $this->hydrator->hydrate($user, $response);
    }

    /**
     * Ping service API
     *
     * @return boolean
     */
    public function pingService()
    {
        $response = $this->getResponse('get', 'v2/services/ping');

        return $response['success'];
    }

    /**
     * Get API key
     *
     * @return string
     */
    public function getApiKey()
    {
        return $this->apiKey;
    }

    /**
     * Set API key
     *
     * @param string $apiKey
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * Getter hydrator
     *
     * @return SimpleHydrator
     */
    public function getHydrator()
    {
        return $this->hydrator;
    }

    /**
     * Setter hydrator
     *
     * @param SimpleHydrator $hydrator
     */
    public function setHydrator(SimpleHydrator $hydrator)
    {
        $this->hydrator = $hydrator;
    }

    /**
     * Add Http client subscriber
     *
     * @param EventSubscriberInterface $subscriber
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->httpClient->addSubscriber($subscriber);
    }

    /**
     * Get Response from API
     * Response is an array (Result of json_decode)
     *
     * @param string $uri API URI
     * @param array $queryParams Query params
     * @return mixed
     */
    protected function getResponse($method = 'get', $uri, array $queryParams = array(), $postFiles = array())
    {
        $request = $this->httpClient->$method($uri.'?api_key='.$this->apiKey, array(), array('query' => $queryParams));

        if(!empty($postFiles)) {
            $request->addPostFiles($postFiles);
        }

        return $request->send()->json();
    }
}


<?php

/*
 * This file is part of Transfer.
 *
 * For the full copyright and license information, please view the LICENSE file located
 * in the root directory.
 */

namespace Bridge\Console\Command;

use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command for list registered cache pools.
 */
class CachePoolsCommand extends BridgeCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('cache:pools')
            ->setDescription('List registered cache pools');
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $pools = $this->registry->getCachePools();

        $rows = array();

        foreach ($pools as $name => $pool) {
            $rows[] = array($name, get_class($pool));
        }

        $table = new Table($output);

        $table->setHeaders(array('Name', 'Class'))
            ->setRows($rows);

        $table->render();
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (count($arguments) === 2 && is_array($arguments[1])) {
            foreach (array_pop($arguments) as $item) {
                $arguments = array_merge($arguments, $item);
            }
        }

        parent::setArguments($arguments);
    }
}


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

namespace cascade\components\dataInterface;

use cascade\components\helpers\StringHelper;
use cascade\models\Registry;
use canis\helpers\ArrayHelper;
use canis\helpers\Console;

/**
 * Search [[@doctodo class_description:cascade\components\dataInterface\Search]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Search extends \canis\base\Component
{
    /**
     * @var [[@doctodo var_type:interactive]] [[@doctodo var_description:interactive]]
     */
    public static $interactive = true;
    /**
     * @var [[@doctodo var_type:threshold]] [[@doctodo var_description:threshold]]
     */
    public $threshold = 70;

    public $defaultOptionThreshold = 90;
    /**
     * @var [[@doctodo var_type:superSafeAdjust]] [[@doctodo var_description:superSafeAdjust]]
     */
    public $superSafeAdjust = 1.3;
    /**
     * @var [[@doctodo var_type:dataSource]] [[@doctodo var_description:dataSource]]
     */
    public $dataSource;

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

    /**
     * @var [[@doctodo var_type:_localFields]] [[@doctodo var_description:_localFields]]
     */
    protected $_localFields;
    /**
     * @var [[@doctodo var_type:_foreignFields]] [[@doctodo var_description:_foreignFields]]
     */
    protected $_foreignFields = [];

    /**
     * [[@doctodo method_description:searchLocal]].
     *
     * @param cascade\components\dataInterface\DataItem $item         [[@doctodo param_description:item]]
     * @param array                                     $searchParams [[@doctodo param_description:searchParams]] [optional]
     *
     * @return [[@doctodo return_type:searchLocal]] [[@doctodo return_description:searchLocal]]
     */
    public function searchLocal(DataItem $item, $searchParams = [])
    {
        if (empty($searchParams['searchFields'])) {
            $searchParams['searchFields'] = $this->localFields;
        }
        if (empty($searchParams['searchFields'])) {
            return;
        }
        if (!isset($searchParams['limit'])) {
            $searchParams['limit'] = 5;
        }
        $searchParams['skipForeign'] = true;
        $query = [];
        foreach ($this->foreignFields as $field) {
            if (!empty($item->foreignObject->{$field})) {
                $value = $item->foreignObject->{$field};
                if (isset($this->foreignFilter)) {
                    $value = call_user_func($this->foreignFilter, $value);
                }
                $query[] = $value;
            }
        }
        if (empty($query)) {
            return;
        }

        $localClass = $this->dataSource->localModel;
        $searchResults = $localClass::searchTerm(implode(' ', $query), $searchParams);
        $resultsLeft = $totalResults = count($searchResults);
        foreach ($searchResults as $k => $r) {
            // if ($r->descriptor === $query[0]) { continue; }
            $score = (
                ((($resultsLeft/$totalResults) * 100) * .2)
                + (StringHelper::compareStrings($r->descriptor, implode(' ', $query)) * .8)
            );
            $r->score = $score;
            if ($score < $this->threshold) {
                unset($searchResults[$k]);
            } else {
                $reverseKey = $this->dataSource->getReverseKeyTranslation($r->id);
                if (!empty($reverseKey)) {
                    unset($searchResults[$k]);
                }
            }
            $resultsLeft--;
        }
        ArrayHelper::multisort($searchResults, 'scoreSort', SORT_DESC);
        $searchResults = array_values($searchResults);
        if (empty($searchResults)) {
            return;
        } elseif (($safeResult = $this->getSafeResult($searchResults))) {
            $this->dataSource->task->addInfo('Auto-matched "'. implode(' ', $query) .'" to "'. $safeResult->descriptor .'" (Score: '.round($safeResult->score, 2).')', [
                    'query' => $query,
                    'foreignObject' => $item->foreignObject->attributes,
                    'localObject' => ['id' => $safeResult->id, 'descriptor' => $safeResult->descriptor]
            ]);
            return $safeResult->object;
        } else {
            $options = [];
            $resultsNice = [];
            $optionNumber = 1;

            $defaultOption = 'new';
            if ($searchResults[0]->score > $this->defaultOptionThreshold) {
                $defaultOption = '1';
            }
            foreach ($searchResults as $result) {
                $resultsNice['' . $optionNumber] = $result;
                $options['' . $optionNumber] = $result->descriptor . ' (' . round($result->score) . '%)';
                $optionNumber++;
            }
            $options['new'] = 'Create New Object';
            $options['selectObject'] = 'Select Object';
            $select = false;
            $interactionOptions = ['inputType' => 'select', 'options' => $options];
            $interactionOptions['details'] = $item->foreignObject->attributes;
            $interactionOptions['default'] = $defaultOption;
            $callback = [
                'callback' => function ($response) use (&$select, $options) {
                    if (empty($response)) {
                        return false;
                    }
                    if (substr($response, 0, 2) !== '*-' && !isset($options[$response])) {
                        return false;
                    }
                    $select = $response;

                    return true;
                },
            ];
            if (!$this->dataSource->action->createInteraction('Match Object (' . implode(' ', $query) . ')', $interactionOptions, $callback)) {
                return false;
            }

            if ($select === 'new') {
                $this->dataSource->task->addInfo('For "'. implode(' ', $query) .'" user chose to to create new object', [
                        'query' => $query,
                        'foreignObject' => $item->foreignObject->attributes
                ]);
                return;
            } elseif (substr($select, 0, 2) === '*-') {
                $matchedObjectId = substr($select, 2);
                $matchedObject = Registry::getObject($matchedObjectId, false);
                if (!$matchedObject) {
                    $this->dataSource->task->addWarning('For "'. implode(' ', $query) .'" user tried to match it to a different object, but object wasn\'t found! Created new object.', [
                            'query' => $query,
                            'foreignObject' => $item->foreignObject->attributes,
                            'matchedObject' => $matchedObjectId
                    ]);
                    return;
                }
                $this->dataSource->task->addInfo('For "'. implode(' ', $query) .'" matched to an existing object "'. $matchedObject->descriptor .'"', [
                        'query' => $query,
                        'foreignObject' => $item->foreignObject->attributes,
                        'matchedObject' => $matchedObject->attributes
                ]);
                return $matchedObject;
            } else {
                $this->dataSource->task->addInfo('User matched "'. implode(' ', $query) .'" to "'. $resultsNice[$select]->descriptor . '"', [
                        'query' => $query,
                        'foreignObject' => $item->foreignObject->attributes,
                        'localObject' => $resultsNice[$select]->id
                ]);
                return $resultsNice[$select]->object;
            }
        }
    }

    /**
     * [[@doctodo method_description:searchForeign]].
     *
     * @param cascade\components\dataInterface\DataItem $item [[@doctodo param_description:item]]
     *
     * @return [[@doctodo return_type:searchForeign]] [[@doctodo return_description:searchForeign]]
     */
    public function searchForeign(DataItem $item)
    {
        return false;
    }

    /**
     * Set local fields.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setLocalFields($value)
    {
        $this->_localFields = $value;
    }

    /**
     * Get local fields.
     *
     * @return [[@doctodo return_type:getLocalFields]] [[@doctodo return_description:getLocalFields]]
     */
    public function getLocalFields()
    {
        return $this->_localFields;
    }

    /**
     * Set foreign fields.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setForeignFields($value)
    {
        $this->_foreignFields = $value;
    }

    /**
     * Get foreign fields.
     *
     * @return [[@doctodo return_type:getForeignFields]] [[@doctodo return_description:getForeignFields]]
     */
    public function getForeignFields()
    {
        return $this->_foreignFields;
    }

    /**
     * Get module.
     *
     * @return [[@doctodo return_type:getModule]] [[@doctodo return_description:getModule]]
     */
    public function getModule()
    {
        return $this->dataSource->module;
    }

    protected function getSafeResult($results)
    {
        // does it have a result?
        if (!isset($results[0])) {
            return false;
        }
        $firstResult = $results[0];

        // does it have a second option?
        $secondResult = false;
        if (isset($results[1])) {
            $secondResult = $results[1];
        }

        // is it super safe?
        if ($firstResult->score < ($this->threshold * $this->superSafeAdjust)) {
            return false;
        }

        // is its score the same as the next best result?
        if ($secondResult && $secondResult->score === $firstResult->score) {
            return false;
        }

        return $firstResult;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\BonusHybrid\Helper;

use Praxigento\BonusBase\Repo\Data\Rank;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Cfg\Param as CfgParam;
use Praxigento\Downline\Repo\Data\Customer;

/**
 * Hybrid bonus configuration parameters.
 */
class Scheme
    implements \Praxigento\BonusHybrid\Api\Helper\Scheme
{
    const A_RANK_ID = 'RankId';
    const A_SCHEME = 'Scheme';

    /**
     * There are 2 customers with forced qualifications and ranks in Santegra project.
     *
     * @var array [$mlmId=>[$schema, $rankCode], ...]
     */
    private $QUALIFIED_CUSTOMERS = [
        '770000001' => [Cfg::SCHEMA_DEFAULT, Cfg::RANK_PRESIDENT],
        '777017725' => [Cfg::SCHEMA_DEFAULT, Cfg::RANK_PRESIDENT]
    ];
    /**
     * @var array of the customers with forced qualification.
     */
    private $cacheForcedCustomerIds = null;
    /**
     * Cached values for customers with forced ranks. Each customer can be ranked in all schemes.
     *
     * @var array [$custId=>[$schema=>[A_RANK_ID=>$rankId, A_CFG_PARAMS=>[...]], ...], ...]
     */
    private $cacheForcedRanks = null;
    /**
     * @var array of customers with forced qualification from 'Sign Up Volume Debit' (MOBI-635)
     */
    private $cacheSignUpDebitCustIds = null;
    /** @var  \Magento\Framework\DB\Adapter\AdapterInterface */
    private $conn;
    /** @var \Praxigento\Downline\Repo\Dao\Customer */
    private $daoDwnlCust;
    /** @var \Praxigento\Core\Api\App\Repo\Generic */
    private $daoGeneric;
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit */
    private $daoRegSignUpDebit;
    /** @var \Praxigento\BonusHybrid\Repo\Query\SignUpDebit\GetLastCalcIdForPeriod */
    private $queryGetLastSignUpCalcId;
    /** @var \Magento\Framework\App\ResourceConnection */
    private $resource;

    /**
     * Scheme constructor.
     */
    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Core\Api\App\Repo\Generic $daoGeneric,
        \Praxigento\Downline\Repo\Dao\Customer $daoDwnlCust,
        \Praxigento\BonusHybrid\Repo\Dao\Registry\SignUpDebit $daoRegSignUpDebit,
        \Praxigento\BonusHybrid\Repo\Query\SignUpDebit\GetLastCalcIdForPeriod $queryGetLastSignUpCalcId
    ) {
        $this->resource = $resource;
        $this->conn = $resource->getConnection();
        $this->daoGeneric = $daoGeneric;
        $this->daoDwnlCust = $daoDwnlCust;
        $this->daoRegSignUpDebit = $daoRegSignUpDebit;
        $this->queryGetLastSignUpCalcId = $queryGetLastSignUpCalcId;
    }

    /**
     * Get all ranks configuration parameters to create map for forced customers.
     *
     * SELECT
     * pbhcp.*,
     * pbhr.code
     * FROM prxgt_bon_hyb_cfg_param pbhcp
     * LEFT JOIN prxgt_bon_hyb_rank pbhr
     * ON pbhcp.rank_id = pbhr.id
     *
     * @return array [$rankCode => [$scheme=>[$data], ...], ...]
     */
    private function getCfgParamsByRanks()
    {
        /* aliases and tables */
        $asParams = 'pbhcp';
        $asRank = 'pbhr';
        $tblParams = $this->resource->getTableName(CfgParam::ENTITY_NAME);
        $tblRank = $this->resource->getTableName(Rank::ENTITY_NAME);
        // FROM prxgt_bon_hyb_cfg_param pbhcp
        $query = $this->conn->select();
        $query->from([$asParams => $tblParams]);
        // LEFT JOIN prxgt_bon_hyb_rank pbhr ON pbhcp.rank_id = pbhr.id
        $on = "$asParams." . CfgParam::A_RANK_ID . "=$asRank." . Rank::A_ID;
        $cols = [Rank::A_CODE];
        $query->joinLeft([$asRank => $tblRank], $on, $cols);
        // $sql = (string)$query;
        $entries = $this->conn->fetchAll($query);
        $result = [];
        foreach ($entries as $entry) {
            $rankCode = $entry[Rank::A_CODE];
            $rankScheme = $entry[CfgParam::A_SCHEME];
            $result[$rankCode][$rankScheme] = $entry;
        }
        return $result;
    }

    /**
     * IDs for customers with forced qualification.
     *
     * @return array [[Customer::A_CUSTOMER_ID=>..., Customer::A_MLM_ID=>...], ...]
     */
    private function getForcedCustomersIds()
    {
        $mlmIds = array_keys($this->QUALIFIED_CUSTOMERS);
        $where = '';
        foreach ($mlmIds as $one) {
            /* skip first iteration */
            if (strlen($where) > 0) {
                $where .= ' OR ';
            }
            $quoted = $this->conn->quote($one);
            $where .= Customer::A_MLM_ID . "=\"$quoted\"";
        }
        $cols = [Customer::A_CUSTOMER_REF, Customer::A_MLM_ID];
        $result = $this->daoGeneric->getEntities(Customer::ENTITY_NAME, $cols, $where);
        return $result;
    }

    public function getForcedPv($custId, $scheme, $pv)
    {
        $result = $pv;
        /* be sure to have _cached data */
        $this->getForcedQualificationCustomers();
        if (in_array($custId, $this->cacheForcedCustomerIds)) {
            $custData = $this->cacheForcedRanks[$custId];
            $qpv = $custData[$scheme][CfgParam::A_QUALIFY_PV];
            if ($result < $qpv) {
                $result = $qpv;
            }
        }
        return $result;
    }

    /**
     * Load configuration data for customers with forced qualification.
     *
     * @return array
     */
    public function getForcedQualificationCustomers()
    {
        if (is_null($this->cacheForcedRanks)) {
            /* get Customer IDs from DB to map ranks to Mage IDs instead of MLM IDs */
            $custIds = $this->getForcedCustomersIds();
            /* get all ranks with configuration parameters for all schemes */
            $ranks = $this->getCfgParamsByRanks();
            $this->cacheForcedRanks = [];
            foreach ($custIds as $item) {
                $custId = $item[Customer::A_CUSTOMER_REF];
                $ref = $item[Customer::A_MLM_ID];
                $rankCode = $this->QUALIFIED_CUSTOMERS[$ref][1];
                $cfgParamsWithSchemes = $ranks[$rankCode];
                $this->cacheForcedRanks[$custId] = $cfgParamsWithSchemes;
            }
            /* compose map from customer IDs for quick search */
            $this->cacheForcedCustomerIds = array_keys($this->cacheForcedRanks);
        }
        return $this->cacheForcedRanks;
    }

    public function getForcedQualificationCustomersIds()
    {
        $this->getForcedQualificationCustomers();
        return $this->cacheForcedCustomerIds;
    }

    public function getForcedQualificationRank($custId, $scheme)
    {
        $result = null;
        $forced = $this->getForcedQualificationCustomers();
        if (isset($forced[$custId][$scheme])) {
            $result = $forced[$custId][$scheme][CfgParam::A_RANK_ID];
        }
        return $result;
    }

    /**
     * MOBI-635: get customers w/o 100 PV from Sign Up Volume Debit
     */
    protected function getForcedSignUpDebitCustIds()
    {
        if (is_null($this->cacheSignUpDebitCustIds)) {
            $ids = [];
            $calcId = $this->queryGetLastSignUpCalcId->exec();
            $where = \Praxigento\BonusHybrid\Repo\Data\Registry\SignUpDebit::A_CALC_REF . '=' . (int)$calcId;
            $rs = $this->daoRegSignUpDebit->get($where);
            /** @var \Praxigento\BonusHybrid\Repo\Data\Registry\SignUpDebit $one */
            foreach ($rs as $one) {
                $custRef = $one->getCustomerRef();
                $ids[] = $custRef;
            }
            $this->cacheSignUpDebitCustIds = $ids;
        }
        return $this->cacheSignUpDebitCustIds;

    }

    public function getForcedTv($custId, $scheme, $tv)
    {
        $result = $tv;
        /* be sure to have _cached data */
        $this->getForcedQualificationCustomers();
        if (in_array($custId, $this->cacheForcedCustomerIds)) {
            $custData = $this->cacheForcedRanks[$custId];
            $qpv = $custData[$scheme][CfgParam::A_QUALIFY_TV];
            if ($result < $qpv) {
                $result = $qpv;
            }
        }
        return $result;
    }

    public function getQualificationLevels()
    {
        $result = [
            Cfg::SCHEMA_DEFAULT => Cfg::PV_QUALIFICATION_LEVEL_DEF,
            Cfg::SCHEMA_EU => Cfg::PV_QUALIFICATION_LEVEL_EU
        ];
        return $result;
    }

    public function getSchemeByCustomer($data)
    {
        $result = Cfg::SCHEMA_DEFAULT;
        if (is_array($data)) {
            $countryCode = $data[Customer::A_COUNTRY_CODE];
        } elseif ($data instanceof \Praxigento\Core\Data) {
            $countryCode = $data->get(Customer::A_COUNTRY_CODE);
        } else {
            $msg = "Unexpected input data (schema): " . \json_encode(\var_dump($data, true));
            $msg .= \json_encode(\debug_backtrace());
            throw new \Exception($msg);
        }
        $code = strtoupper($countryCode);
        if (
            ($code == 'AT') ||
            ($code == 'DE') ||
            ($code == 'ES') ||
            ($code == 'LU')
        ) {
            $result = Cfg::SCHEMA_EU;
        }
        return $result;
    }

    public function getSchemeByCustomerId($id)
    {
        $data = $this->daoDwnlCust->getById($id);
        $result = $this->getSchemeByCustomer($data);
        return $result;
    }
}


<?php
namespace Lab123\Odin\Traits;

use Lab123\Odin\Requests\FilterRequest;
use Lab123\Odin\Libs\Api;
use App;
use DB;
use Illuminate\Http\Request;

trait ApiActionsChilds
{

    /**
     * Display a listing of the childs resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function childIndex(FilterRequest $filters, $id, $relation)
    {
        $id = $this->getRealId($id);

        $resource = $this->repository->getChilds($id, $relation, $filters);

        if (! $resource || count($resource) < 1) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Display a listing of the child resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function childShow(FilterRequest $filters, $id, $idChild, $relation)
    {
        $id = $this->getRealId($id);
        $idChild = $this->getRealId($idChild);

        $resource = $this->repository->getChild($id, $relation, $idChild, $filters);

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Create a new child
     *
     * @return \Illuminate\Http\Response
     */
    public function childStore($idParent, FilterRequest $filters, $relation)
    {
        $idParent = $this->getRealId($idParent);

        $resource = $this->repository->storeChild($idParent, $relation, $filters->all());

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Create and associate a new child
     *
     * @return \Illuminate\Http\Response
     */
    public function childStoreWithPivot($idParent, $request, $relation)
    {
        $idParent = $this->getRealId($idParent);

        $resource = $this->repository->storeChildAndPivot($idParent, $relation, $request->all());

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Associate a new child
     *
     * @return \Illuminate\Http\Response
     */
    public function childAssociate($request, $idParent, $idChild, $relation)
    {
        $request->request->merge([
            'url' => $request->request->path()
        ]);

        $idParent = $this->getRealId($idParent);
        $idChild = $this->getRealId($idChild);

        $resourceChild = $this->repository->attach($idParent, $idChild, $relation, $request->all());

        if (! $resourceChild) {
            // return $this->notFound();
        }

        return $this->success([
            $resourceChild
        ]);
    }

    /**
     * Dissociate a new child
     *
     * @return \Illuminate\Http\Response
     */
    public function childDissociate($request, $idParent, $idChild, $relation)
    {
        $idParent = $this->getRealId($idParent);
        $idChild = $this->getRealId($idChild);

        if (! $this->repository->detach($idParent, $idChild, $relation)) {
            // return $this->notFound();
        }

        return $this->success([]);
    }

    /**
     * Update a child
     *
     * @return \Illuminate\Http\Response
     */
    public function updateChild($idParent, FilterRequest $filters, $idChild, $relation)
    {
        $idParent = $this->getRealId($idParent);
        $idChild = $this->getRealId($idChild);

        $resource = $this->repository->updateChild($idParent, $relation, $idChild, $filters->all());

        if (! $resource) {
            // return $this->notFound();
        }

        return $this->success($resource);
    }

    /**
     * Delete a child
     *
     * @return \Illuminate\Http\Response
     */
    public function deleteChild($idParent, FilterRequest $filters, $idChild, $relation)
    {
        $idParent = $this->getRealId($idParent);
        $idChild = $this->getRealId($idChild);

        $resource = $this->repository->deleteChild($idParent, $relation, $idChild);

        if ($resource == null) {
            // return $this->notFound();
        }

        return $this->success();
    }
}


<?php

namespace ebussola\common\datatype\number;

use ebussola\common\datatype\Number;

/**
 * Author: Leonardo Branco Shinagawa
 * Date: 17/01/12
 * Time: 14:26
 */
class Percentage extends Number
{

    /**
     * @var boolean
     */
    private $showSymbol = true;

    /**
     * Percentage OF $number is how much Number?
     *
     * @param Number|String $number
     * @return Number
     * Depending on the input, but always an object extended of Number
     *
     * @throws \InvalidArgumentException
     */
    public function of($number)
    {
        $value = clone $this;
        $value->bcmul($number)->bcdiv(100);
        if ($number instanceof Number) {
            $class = get_class($number);
            $value = new $class($value);
        } else {
            if (is_numeric($number)) {
                $value = new Number($value);
            } else {
                throw new \InvalidArgumentException();
            }
        }
        return $value;
    }

    /**
     * @param boolean $value
     * @return Percentage
     */
    public function setShowSymbol($value)
    {
        $this->showSymbol = (bool)$value;
        return $this;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        if ($this->showSymbol) {
            return parent::__toString() . '%';
        } else {
            return parent::__toString();
        }
    }

}


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli\Validator;

use In2pire\Component\Utility\Text;

/**
 * Validator container.
 */
final class Container
{
    /**
     * Create new validator.
     *
     * @param string $validator
     *   Validator ID.
     * @param In2pire\Cli\Command\CliCommand $command
     *   The running command.
     *
     * @return In2pire\Cli\Validator\CliValidator
     *   New validator.
     */
    public static function create($validator, $command)
    {
        static $cache = [];
        $cacheKey = $validator;

        if (isset($cache[$cacheKey]))  {
            $class = $cache[$cacheKey]['class'];
            $validator = $cache[$cacheKey]['validator'];
        } else {
            if (false === strpos($validator, '.')) {
                // Not FQCN
                $class = __NAMESPACE__ . '\\' . String::convertToCamelCase($validator);
            } else {
                // FQCN
                $class = explode('.', $validator);
                $class = array_map(array('In2pire\\Component\\Utility\\Text', 'convertToCamelCase'), $class);
                $class = implode('\\', $class);
                $validator = substr($validator, strrpos($validator, '.') + 1);
            }

            $cache[$cacheKey] = [
                'class' => $class,
                'validator' => $validator
            ];
        }

        if (!class_exists($class)) {
            throw new \RuntimeException('Unknow validator ' . $cacheKey);
        }

        return new $class($command);
    }
}


<?php

namespace Litecms\Forum\Policies;

use Litepie\User\Contracts\UserPolicy;
use Litecms\Forum\Models\Response;

class ResponsePolicy
{

    /**
     * Determine if the given user can view the response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function view(UserPolicy $user, Response $response)
    {
        if ($user->canDo('forum.response.view') && $user->isAdmin()) {
            return true;
        }

        return $response->user_id == user_id() && $response->user_type == user_type();
    }

    /**
     * Determine if the given user can create a response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function create(UserPolicy $user)
    {
        return  $user->canDo('forum.response.create');
    }

    /**
     * Determine if the given user can update the given response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function update(UserPolicy $user, Response $response)
    {
        if ($user->canDo('forum.response.edit') && $user->isAdmin()) {
            return true;
        }

        return $response->user_id == user_id() && $response->user_type == user_type();
    }

    /**
     * Determine if the given user can delete the given response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function destroy(UserPolicy $user, Response $response)
    {
        return $response->user_id == user_id() && $response->user_type == user_type();
    }

    /**
     * Determine if the given user can verify the given response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function verify(UserPolicy $user, Response $response)
    {
        if ($user->canDo('forum.response.verify')) {
            return true;
        }

        return false;
    }

    /**
     * Determine if the given user can approve the given response.
     *
     * @param UserPolicy $user
     * @param Response $response
     *
     * @return bool
     */
    public function approve(UserPolicy $user, Response $response)
    {
        if ($user->canDo('forum.response.approve')) {
            return true;
        }

        return false;
    }

    /**
     * Determine if the user can perform a given action ve.
     *
     * @param [type] $user    [description]
     * @param [type] $ability [description]
     *
     * @return [type] [description]
     */
    public function before($user, $ability)
    {
        if ($user->isSuperuser()) {
            return true;
        }
    }
}


<?php

namespace Tokenly\BitcoinAddressLib;

use BitWasp\Bitcoin\Key\PrivateKeyFactory;
use Exception;

/*
* BitcoinKeyUtils
*/
class BitcoinKeyUtils
{

    ////////////////////////////////////////////////////////////////////////

    public static function publicKeyFromWIF($wif, $verify_address=null) {
        $private_key_instance = PrivateKeyFactory::fromWif($wif);
        $public_key_instance = $private_key_instance->getPublicKey();
        return $public_key_instance->getHex();
    }

    public static function addressFromWIF($wif) {
        $private_key_instance = PrivateKeyFactory::fromWif($wif);
        $address_instance = $private_key_instance->getAddress();
        return $address_instance->getAddress();
    }

    public static function publicKeyFromPrivateKey($private_key_instance) {
        return $private_key_instance->getPublicKey();
    }

    public static function WIFFromPrivateKey($private_key) {
        return $private_key->toWif();
    }

    ////////////////////////////////////////////////////////////////////////

}


<?php

namespace Adolfocuadros\RenqoMicroservice;

use Adolfocuadros\RenqoMicroservice\Exceptions\NotFoundTokenException;
use Adolfocuadros\RenqoMicroservice\Exceptions\ServiceNotFoundException;
use GuzzleHttp\Client;

class HttpService
{
    private $microService;
    private $authToken;
    private $headers;

    private $client;
    private $timeout= 5.0;

    private $success = false;
    private $error;

    private $request;

    function __construct($service) {
        if(config('microservice.api.' . $service) == null) {
            throw new ServiceNotFoundException('Not found service: ' . $service);
        }
        $this->microService = config('microservice.api.' . $service);
        if(isset(getallheaders()['Auth-Token'])) {
            $this->setAuthToken(getallheaders()['Auth-Token']);
        }
    }

    /**
     * @param $resource
     * @param string $method
     * @param $params
     * @param $headers
     * @return mixed|\Psr\Http\Message\ResponseInterface
     * @throws NotFoundTokenException
     */
    public function consume($resource, $method = 'GET', $params, $headers = null) {
        $this->request = $this->client()->request($method, $resource, [
            'form_params' => $params
        ]);
        $this->success = true;
        //return $this->request;
        return $this;
    }

    /** If Success or Fail
     * @param callable $success
     * @param callable $fail
     */
    public function then(callable $success = null, callable $fail = null) {
        if($this->success && is_callable($success)) {
            return $success($this->request, $this->request->getStatusCode());
        } elseif(is_callable($fail)) {
            return $fail($this->error);
        }
    }

    /** Method for initializer guzzle
     * @return Client
     * @throws NotFoundTokenException
     */
    public function client()
    {
        if(empty($this->authToken)) {
            throw new NotFoundTokenException('Token not found');
        }
        //dd($this->microService);
        $this->client = new Client([
            'base_uri' => $this->microService,
            'timeout'  => $this->timeout,
            'headers'  => [
                'Auth-Token' => $this->authToken
            ]
        ]);
        return $this->client;
    }

    /** Add token
     * @param $token
     */
    public function setAuthToken($token) {
        $this->authToken = $token;
        $this->addHeader('Auth-Token', $this->authToken);
    }

    /** Add header for consume
     * @param $header
     * @param $value
     */
    public function addHeader($header, $value) {
        $this->headers[$header] = $value;
    }

    public function body() {
        /*if($this->success) {
            return \GuzzleHttp\json_decode($this->request->getBody()->getContents());
        }*/
        if($this->success) {
            return $this->request->getBody()->getContents();
        }
        return null;
    }

    public function responseJson() {
        if($this->success) {
            return response($this->request->getBody()->getContents(),
                $this->request->getStatusCode(),
                ['Content-Type'=>'application/json']);
        }

        return response('',200,['Content-Type'=>'application/json']);
    }
}


<?php
/*
 * This file is part of the Qimnet update tracker Bundle.
 *
 * (c) Antoine Guigan <aguigan@qimnet.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Qimnet\UpdateTrackerBundle\Routing;
use Qimnet\UpdateTrackerBundle\UpdateTracker\UpdateManagerInterface;
use Symfony\Component\Routing\RouterInterface;

/**
 * Generates timestamped paths
 *
 */
class TimestampedPathGenerator implements TimestampedPathGeneratorInterface
{
    protected $router;
    protected $updateManager;
    protected $timestampParameterName;
    public function __construct(RouterInterface $router, UpdateManagerInterface $updateManager, $timestampParameterName)
    {
        $this->router = $router;
        $this->updateManager = $updateManager;
        $this->timestampParameterName = $timestampParameterName;
    }
    /**
     * Generates an URL containining a timestamp parameter
     *
     * @param  string $name                   The name of the route
     * @param  array  $parameters             The parameters of the route
     * @param  mixed  $updateTrackerName      The update tracker's name or an array of update trackers
     * @param  int    $referenceType          The type of reference to be returned
     * @param  string $timestampParameterName The name of the timestamp parameter
     * @return string
     */
    public function generate($name, array $parameters=array(), $updateTrackerName='global', $referenceType = RouterInterface::ABSOLUTE_PATH, $timestampParameterName=null)
    {
        if (!$timestampParameterName) {
            $timestampParameterName = $this->timestampParameterName;
        }
        $parameters[$timestampParameterName] = $this->updateManager->getLastUpdate($updateTrackerName)->format('U');

        return $this->router->generate($name, $parameters, $referenceType);
    }
}


<?php
namespace core\manage\logic;

use cms\Logic;
use think\Url;
use cms\Common;

class MenuLogic extends Logic
{

    /**
     * 新增菜单
     *
     * @param array $data
     * @return number
     */
    public function addMenu($data)
    {
        $data['menu_flag'] = $this->processMenuFlag($data['menu_url'], $data['menu_build']);
        return $this->model->add($data);
    }

    /**
     * 保存菜单
     *
     * @param array $data
     * @param array $map
     * @return number
     */
    public function saveMenu($data, $map)
    {
        $data['menu_flag'] = $this->processMenuFlag($data['menu_url'], $data['menu_build']);
        return $this->model->saveById($data, $map);
    }

    /**
     * 菜单下拉选择
     *
     * @return array
     */
    public function getMenuSelect()
    {
        $menu_tree = $this->getMenuTree();
        $menu_select = [];
        $menu_select[] = [
            'name' => '无',
            'value' => 0
        ];
        foreach ($menu_tree['main_menu'] as $vo) {
            $menu_select[] = [
                'name' => $vo['menu_name'],
                'value' => $vo['menu_id']
            ];
            foreach ($menu_tree['sub_menu'][$vo['menu_id']] as $ko) {
                $menu_select[] = [
                    'name' => '--' . $ko['menu_name'],
                    'value' => $ko['menu_id']
                ];
            }
        }
        return $menu_select;
    }

    /**
     * 菜单树
     *
     * @return array
     */
    public function getMenuTree()
    {
        $menu = [
            'main_menu' => [],
            'sub_menu' => [],
            'sub_sub_menu' => []
        ];

        // 一级菜单
        $map = [
            'menu_pid' => 0
        ];
        $list = $this->model->where($map)
            ->order('menu_sort asc')
            ->select();

        $main_pids = [];
        foreach ($list as $vo) {
            $main_pids[] = $vo['id'];
            $menu['main_menu'][$vo['id']] = [
                'menu_id' => $vo['id'],
                'menu_name' => $vo['menu_name']
            ];
            $menu['sub_menu'][$vo['id']] = [];
        }

        // 二级菜单
        $map = [
            'menu_pid' => [
                'in',
                $main_pids
            ]
        ];
        $list = $this->model->where($map)
            ->order('menu_sort asc')
            ->select();

        $sub_pids = [];
        foreach ($list as $vo) {
            $sub_pids[] = $vo['id'];
            $menu['sub_menu'][$vo['menu_pid']][$vo['id']] = [
                'menu_id' => $vo['id'],
                'menu_name' => $vo['menu_name']
            ];
            $menu['sub_sub_menu'][$vo['id']] = [];
        }

        // 三级菜单
        $map = [
            'menu_pid' => [
                'in',
                $sub_pids
            ]
        ];
        $list = $this->model->where($map)
            ->order('menu_sort asc')
            ->select();

        $sub_pids = [];
        foreach ($list as $vo) {
            $sub_pids[] = $vo['id'];
            $menu['sub_sub_menu'][$vo['menu_pid']][$vo['id']] = [
                'menu_id' => $vo['id'],
                'menu_name' => $vo['menu_name']
            ];
        }

        return $menu;
    }

    /**
     * 当前菜单
     *
     * @param string $menu_flag
     * @return array
     */
    public function getCurrentMenu($menu_flag = null)
    {
        // 当前菜单
        $current_menu = $this->getMenuByFlag($menu_flag);
        if (empty($current_menu)) {
            return null;
        }

        // 上级菜单
        $parent_menu = $this->model->get($current_menu['menu_pid']);
        if ($parent_menu['menu_pid'] > 0) {
            return $this->getCurrentMenu($parent_menu['menu_flag']);
        } else {
            return $current_menu;
        }
    }

    /**
     * 主菜单
     *
     * @param number $user_id
     * @return array
     */
    public function getMainMenu($user_id)
    {
        // 当前菜单
        $current_menu = $this->getCurrentMenu();

        $main_menu = $this->getMenuByPid(0, $user_id);
        foreach ($main_menu as &$menu) {

            // 菜单权限
            if (empty($menu['menu_url_origin'])) {
                $menu_url = $this->getMainMenuUrl($menu['menu_id'], $user_id);
                is_null($menu_url) || $menu['menu_url'] = $menu_url;
            }

            if ($current_menu && $menu['menu_id'] == $current_menu['menu_pid']) {
                $menu['menu_active'] = 1;
            } else {
                $menu['menu_active'] = 0;
            }
        }
        unset($menu);

        return $main_menu;
    }

    /**
     * 主菜单链接
     */
    public function getMainMenuUrl($menu_id, $user_id)
    {
        $auth_menu = MemberLogic::instance()->getUserMenu($user_id);
        if (! in_array($menu_id, $auth_menu)) {
            return null;
        }

        $map = array(
            'menu_status' => 1,
            'menu_pid' => $menu_id,
            'id' => [
                'in',
                $auth_menu
            ]
        );
        $menu = $this->model->where($map)
            ->order('menu_sort asc')
            ->find();
        return $menu ? Url::build($menu['menu_url']) : '';
    }

    /**
     * 侧边菜单
     *
     * @param number $user_id
     * @return array
     */
    public function getSiderMenu($user_id)
    {
        // 当前菜单
        $current_menu = $this->getCurrentMenu();

        if (empty($current_menu)) {
            return [];
        } else {
            $sider_menu = $this->getMenuByPid($current_menu['menu_pid'], $user_id);
            foreach ($sider_menu as &$menu) {
                if (isset($menu['sub_menu'])) {
                    $menu['menu_active'] = 0;
                    foreach ($menu['sub_menu'] as &$item) {
                        if ($item['menu_id'] == $current_menu['id']) {
                            $item['menu_active'] = 1;
                            $menu['menu_active'] = 1;
                        } else {
                            $item['menu_active'] = 0;
                        }
                    }
                    unset($item);
                } else {
                    if ($menu['menu_id'] == $current_menu['id']) {
                        $menu['menu_active'] = 1;
                    } else {
                        $menu['menu_active'] = 0;
                    }
                }
            }
            unset($menu);
            return $sider_menu;
        }
    }

    /**
     * 根据标识获取菜单
     *
     * @param string $menu_flag
     * @return array
     */
    public function getMenuByFlag($menu_flag = null)
    {
        // 默认当前操作
        if (empty($menu_flag)) {
            if (defined('_MODULE_')) {
                $menu_flag = 'module' . '/' . _MODULE_ . '/' . _CONTROLLER_ . '/' . _ACTION_;
            } else {
                $menu_flag = Common::getCurrentAction();
            }
        }

        $map = array(
            'menu_flag' => $menu_flag,
            'menu_pid' => array(
                'gt',
                0
            )
        );
        return $this->model->where($map)->find();
    }

    /**
     * 根据Pid获取菜单
     *
     * @param number $menu_pid
     * @param number $user_id
     * @return array
     */
    public function getMenuByPid($menu_pid, $user_id)
    {
        $auth_menu = MemberLogic::instance()->getUserMenu($user_id);
        $map = array(
            'menu_status' => 1,
            'menu_pid' => $menu_pid,
            'id' => [
                'in',
                $auth_menu
            ]
        );
        $list = $this->model->where($map)
            ->order('menu_sort asc')
            ->select();

        $menu = array();
        foreach ($list as $v) {
            if ($v['menu_group'] && $menu_pid > 0) {
                $key = 'group_' . md5($v['menu_group']);
                if (! isset($menu[$key])) {
                    $menu[$key] = [
                        'menu_name' => $v['menu_group'],
                        'sub_menu' => []
                    ];
                }
                $menu[$key]['sub_menu'][] = $this->getMenuItem($v);
            } else {
                $key = 'menu_' . $v['id'];
                $menu[$key] = $this->getMenuItem($v);
            }
        }

        return $menu;
    }

    /**
     * 获取菜单项
     *
     * @param array $item
     * @return array
     */
    public function getMenuItem($item)
    {
        return [
            'menu_id' => $item['id'],
            'menu_name' => $item['menu_name'],
            'menu_url_origin' => $item['menu_url'],
            'menu_url' => $item['menu_build'] ? Url::build($item['menu_url']) : $item['menu_url'],
            'menu_target' => $item['menu_target']
        ];
    }

    /**
     * 菜单标识
     *
     * @param string $link
     * @return string
     */
    public function processMenuFlag($link, $menu_build = true)
    {
        // 外链
        if ($menu_build == false) {
            return md5($link);
        }

        // 测试连接
        $url_test = 'path/test/domain';
        $url_path = str_replace($url_test . '.html', '', Url::build($url_test, '', true, true));

        // 相对url
        $url = Url::build($link, '', true, true);
        $url_relative = str_replace([
            $url_path,
            '.html'
        ], '', $url);

        // Url标识
        $arr = explode('/', $url_relative);
        if (strpos($link, '@module') !== false) {
            $arr = array_slice($arr, 0, 4);
        } else {
            $arr = array_slice($arr, 0, 3);
        }
        return implode('/', $arr);
    }

    /**
     * 菜单状态
     *
     * @return array
     */
    public function menuStatus()
    {
        return [
            [
                'name' => '显示',
                'value' => 1
            ],
            [
                'name' => '隐藏',
                'value' => 0
            ]
        ];
    }

    /**
     * 打开方式
     *
     * @return array
     */
    public function menuTarget()
    {
        return [
            [
                'name' => '当前窗口',
                'value' => '_self'
            ],
            [
                'name' => '新窗口',
                'value' => '_blank'
            ]
        ];
    }

    /**
     * 是否需要huild
     *
     * @return array
     */
    public function menuBuild()
    {
        return [
            [
                'name' => '需要',
                'value' => 1
            ],
            [
                'name' => '不需要',
                'value' => 0
            ]
        ];
    }
}