<?php

namespace Reaction\Base;

use Reaction\Exceptions\InvalidArgumentException;
use Reaction\Exceptions\InvalidCallException;
use Reaction;

/**
 * Widget is the base class for widgets.
 *
 * For more details and usage information on Widget, see the [guide article on widgets](guide:structure-widgets).
 *
 * @property string $id ID of the widget.
 * @property \Reaction\Web\View $view The view object that can be used to render views or view files. Note that the
 * type of this property differs in getter and setter. See [[getView()]] and [[setView()]] for details.
 * @property string $viewPath The directory containing the view files for this widget. This property is
 * read-only.
 *
 * Borrowed from yii2
 */
class Widget extends RequestAppComponent implements ViewContextInterface
{
    use Reaction\Helpers\Request\RequestAppHelpersExtractedTrait;

    /**
     * @event Event an event that is triggered when the widget is initialized via [[init()]].
     */
    const EVENT_INIT = 'init';
    /**
     * @event WidgetEvent an event raised right before executing a widget.
     * You may set [[WidgetEvent::isValid]] to be false to cancel the widget execution.
     */
    const EVENT_BEFORE_RUN = 'beforeRun';
    /**
     * @event WidgetEvent an event raised right after executing a widget.
     */
    const EVENT_AFTER_RUN = 'afterRun';

    /**
     * @var string the prefix to the automatically generated widget IDs.
     * @see getId()
     */
    public static $autoIdPrefix = 'w';
    /**
     * @var Widget[] the widgets that are currently being rendered (not ended). This property
     * is maintained by [[begin()]] and [[end()]] methods.
     * @internal
     */
    public static $stack = [];

    /**
     * Initializes the object.
     * This method is called at the end of the constructor.
     * The default implementation will trigger an [[EVENT_INIT]] event.
     */
    public function init()
    {
        parent::init();
        $this->checkAppPersistence();
        $this->emit(self::EVENT_INIT, [$this]);
    }

    /**
     * Begins a widget.
     * This method creates an instance of the calling class. It will apply the configuration
     * to the created instance. A matching [[end()]] call should be called later.
     * As some widgets may use output buffering, the [[end()]] call should be made in the same view
     * to avoid breaking the nesting of output buffers.
     * @param array $config name-value pairs that will be used to initialize the object properties
     * @return static the newly created widget instance
     * @see end()
     */
    public static function begin($config = [])
    {
        $config['class'] = get_called_class();
        /* @var $widget Widget */
        $widget = Reaction::create($config);
        static::$stack[] = $widget;

        return $widget;
    }

    /**
     * Ends a widget.
     * Note that the rendering result of the widget is directly echoed out.
     * @return static the widget instance that is ended.
     * @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
     * @see begin()
     */
    public static function end()
    {
        if (!empty(static::$stack)) {
            $widget = array_pop(static::$stack);
            if (get_class($widget) === get_called_class()) {
                /* @var $widget Widget */
                if ($widget->beforeRun()) {
                    $result = $widget->run();
                    $result = $widget->afterRun($result);
                    echo $result;
                }

                return $widget;
            }

            throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
        }

        throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
    }

    /**
     * Creates a widget instance and runs it.
     * The widget rendering result is returned by this method.
     * @param array $config name-value pairs that will be used to initialize the object properties
     * @return string the rendering result of the widget.
     */
    public static function widget($config = [])
    {
        ob_start();
        ob_implicit_flush(false);
        try {
            /* @var $widget Widget */
            $config['class'] = get_called_class();
            $widget = Reaction::create($config);
            $out = '';
            if ($widget->beforeRun()) {
                $result = $widget->run();
                $out = $widget->afterRun($result);
            }
        } catch (\Exception $e) {
            // close the output buffer opened above if it has not been closed already
            if (ob_get_level() > 0) {
                ob_end_clean();
            }
            throw $e;
        }

        return ob_get_clean() . $out;
    }

    private $_id;

    /**
     * Returns the ID of the widget.
     * @param bool $autoGenerate whether to generate an ID if it is not set previously
     * @return string ID of the widget.
     */
    public function getId($autoGenerate = true)
    {
        if ($autoGenerate && $this->_id === null) {
            $this->_id = static::$autoIdPrefix . $this->htmlHlp->counter++;
        }

        return $this->_id;
    }

    /**
     * Sets the ID of the widget.
     * @param string $value id of the widget.
     */
    public function setId($value)
    {
        $this->_id = $value;
    }

    private $_view;

    /**
     * Returns the view object that can be used to render views or view files.
     * The [[render()]] and [[renderFile()]] methods will use
     * this view object to implement the actual view rendering.
     * If not set, it will default to the "view" application component.
     * @return \Reaction\Web\View the view object that can be used to render views or view files.
     */
    public function getView()
    {
        if ($this->_view === null) {
            return $this->app->view;
        }

        return $this->_view;
    }

    /**
     * Sets the view object to be used by this widget.
     * @param View $view the view object that can be used to render views or view files.
     */
    public function setView($view)
    {
        $this->_view = $view;
    }

    /**
     * Executes the widget.
     * @return string the result of widget execution to be outputted.
     */
    public function run()
    {
    }

    /**
     * Renders a view.
     *
     * The view to be rendered can be specified in one of the following formats:
     *
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
     *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
     * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
     *   The actual view file will be looked for under the [[Module::viewPath|view path]] of the currently
     *   active module.
     * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
     *
     * If the view name does not contain a file extension, it will use the default one `.php`.
     *
     * @param string                 $viewName the view name.
     * @param array                  $params the parameters (name-value pairs) that should be made available in the view.
     * @param Reaction\Web\View|null $view
     * @return string the rendering result.
     * @throws InvalidArgumentException if the view file does not exist.
     */
    public function render($viewName, $params = [], $view = null)
    {
        if ($view !== null) {
            $this->setView($view);
        }
        return $this->getView()->render($viewName, $params, $this);
    }

    /**
     * Renders a view file.
     * @param string                 $file the view file to be rendered. This can be either a file path or a [path alias](guide:concept-aliases).
     * @param array                  $params the parameters (name-value pairs) that should be made available in the view.
     * @param Reaction\Web\View|null $view
     * @return string the rendering result.
     */
    public function renderFile($file, $params = [], $view = null)
    {
        if ($view !== null) {
            $this->setView($view);
        }
        return $this->getView()->renderFile($file, $params, $this);
    }

    /**
     * Returns the directory containing the view files for this widget.
     * The default implementation returns the 'views' subdirectory under the directory containing the widget class file.
     * @return string the directory containing the view files for this widget.
     */
    public function getViewPath()
    {
        $class = Reaction\Helpers\ReflectionHelper::getClassReflection($this);

        return dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views';
    }

    /**
     * This method is invoked right before the widget is executed.
     *
     * The method will trigger the [[EVENT_BEFORE_RUN]] event. The return value of the method
     * will determine whether the widget should continue to run.
     *
     * When overriding this method, make sure you call the parent implementation like the following:
     *
     * ```php
     * public function beforeRun()
     * {
     *     if (!parent::beforeRun()) {
     *         return false;
     *     }
     *
     *     // your custom code here
     *
     *     return true; // or false to not run the widget
     * }
     * ```
     * @return bool
     */
    public function beforeRun()
    {
        $isValid = true;
        $this->emit(self::EVENT_BEFORE_RUN, [$this, &$isValid]);
        return $isValid;
    }

    /**
     * This method is invoked right after a widget is executed.
     *
     * The method will trigger the [[EVENT_AFTER_RUN]] event. The return value of the method
     * will be used as the widget return value.
     *
     * If you override this method, your code should look like the following:
     *
     * ```php
     * public function afterRun($result)
     * {
     *     $result = parent::afterRun($result);
     *     // your custom code here
     *     return $result;
     * }
     * ```
     *
     * @param mixed $result the widget return result.
     * @return mixed
     */
    public function afterRun($result)
    {
        $this->emit(self::EVENT_AFTER_RUN, [$this, &$result]);
        return $result;
    }

    /**
     * Check that RequestApplicationInterface is set
     * @throws Reaction\Exceptions\InvalidConfigException
     */
    protected function checkAppPersistence()
    {
        if (!isset($this->app) || !$this->app instanceof Reaction\RequestApplicationInterface) {
            $message = sprintf("You must specify \$app (RequestApplicationInterface) parameter for widget '%s'", get_called_class());
            throw new Reaction\Exceptions\InvalidConfigException($message);
        }
    }
}


<?php
/**
 * This is an ORM package that manages the persistence of database CRUD operations.
 *
 * @package Kola\PotatoOrm\Model
 * @author  Kolawole ERINOSO <kola.erinoso@gmail.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 */

namespace Kola\PotatoOrm;

use \PDOException;
use Kola\PotatoOrm\Helper\DbConn;
use Kola\PotatoOrm\Helper\Backbone;
use Kola\PotatoOrm\Exception\EmptyTableException;
use Kola\PotatoOrm\Exception\RecordNotFoundException;
use Kola\PotatoOrm\Exception\TableDoesNotExistException;

abstract class Model
{
    /**
     * @var array Array for holding properties set with magic method __set()
     */
    protected $record = [];

    /**
     * Set property dynamically
     *
     * @param string $field Property set dynamically
     * @param string $value Value of property set dynamically
     */
    public function __set($field, $value)
    {
        $this->record[$field] = $value;
    }

    /**
     * Provide a read access to protected $record array
     *
     * @return array $record Array of variables set dynamically with method __set()
     */
    public function getRecord()
    {
        return $this->record;
    }

    /**
     * Get a record in a database table
     *
     * @param int $record Index of record to get
     * @return string|object
     */
    public static function find($record, $dbConn = NULL)
    {
		return self::where('id', $record, $dbConn);
    }

    /**
     * Get a record in the database
     *
     * @param string $field Field name to search under
     * @param string $value Field value to search for
     * @return string|object
     */
    public static function where($field, $value, $dbConn = NULL)
    {
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

        try {
			$query = $dbConn->prepare('SELECT * FROM ' . $table . ' WHERE ' . $field . ' = ?');
			$query->execute([$value]);
        } catch (PDOException $e) {
            return $e->getMessage();
        } finally {
            $dbConn = null;
        }

        if ($query->rowCount()) {
            $found = new static;
            $found->dbData = $query->fetch(DbConn::FETCH_ASSOC);

            return $found;
        } else {
            throw new RecordNotFoundException;
        }
    }

	/**
	 * Delete a record from the database table
	 *
	 * @param int $record Index of record to be deleted
	 * @return bool|string
	 */
	public static function destroy($record, $dbConn = NULL)
	{
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

		try {
			$query = $dbConn->prepare('DELETE FROM ' . $table . ' WHERE id= ' . $record);
			$query->execute();
		} catch (PDOException $e) {
			return $e->getMessage();
		} finally {
			$dbConn = null;
		}

		$check = $query->rowCount();

		if ($check) {
			return $check;
		} else {
			throw new RecordNotFoundException;
		}
	}

	/**
	 * Get all the records in a database table
	 *
	 * @return string|object
	 */
	public static function getAll($dbConn = NULL)
	{
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

		try {
			$query = $dbConn->prepare('SELECT * FROM ' . $table);
			$query->execute();
		} catch (PDOException $e) {
			return $e->getMessage();
		} finally {
			$dbConn = null;
		}

		if ($query->rowCount()) {
			return $query->fetchAll(DbConn::FETCH_ASSOC);
		} else {
			throw new EmptyTableException;
		}
	}

	/**
     * Insert or Update a record in a database table
     *
     * @return bool|string
     */
    public function save($dbConn = NULL)
    {
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

        try {
            if (isset($this->record['dbData']) && is_array($this->record['dbData'])) {
                $sql = 'UPDATE ' . $table . ' SET ' . Backbone::tokenize(implode(',', Backbone::joinKeysAndValuesOfArray($this->record)), ',') . ' WHERE id=' . $this->record['dbData']['id'];
                $query = $dbConn->prepare($sql);
                $query->execute();
            } else {
                $sql = 'INSERT INTO ' . $table . ' (' . Backbone::tokenize(implode(',', array_keys($this->record)), ',') . ')' . ' VALUES ' . '(' . Backbone::tokenize(implode(',', Backbone::generateUnnamedPlaceholders($this->record)), ',') . ')';
                $query = $dbConn->prepare($sql);
                $query->execute(array_values($this->record));
            }
        } catch (PDOException $e) {
            return $e->getMessage();
        } finally {
            $dbConn = null;
        }

        return $query->rowCount();
    }
}


<?php

namespace Framework\Console\Commands;

use Framework\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Serve
 * Ignite Framework Serve command, serves up a PHP app server for development
 *
 * @package Framework\Console\Commands\
 */
class Serve extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Serve the application on the PHP development server";

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->checkPhpVersion();

        $publicPath = realpath(app_path('../public/'));
        chdir($publicPath);

        $host = $this->input->getOption('host');
        $port = $this->input->getOption('port');

        $this->info("Ignite Framework development server started on http://{$host}:{$port}");

        passthru("php -S {$host}:{$port} -t \"{$publicPath}\"");
    }

    /**
     * Check the current PHP version is >= 5.4.
     *
     * @throws \Exception
     * @return void
     */
    protected function checkPhpVersion()
    {
        if (version_compare(PHP_VERSION, '5.4.0', '<'))
        {
            throw new \Exception('This PHP binary is not version 5.4 or greater.');
        }
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'),

            array('port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000),
        );
    }
}


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

/**
 * @category   pear
 * @package    PEAR
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  2007-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 1.7.0
 */
class PEAR_Installer_Role_Cfg extends PEAR_Installer_Role_Common
{
    /**
     * @var PEAR_Installer
     */
    var $installer;

    /**
     * the md5 of the original file
     *
     * @var unknown_type
     */
    var $md5 = null;

    /**
     * Do any unusual setup here
     * @param PEAR_Installer
     * @param PEAR_PackageFile_v2
     * @param array file attributes
     * @param string file name
     */
    function setup(&$installer, $pkg, $atts, $file)
    {
        $this->installer = &$installer;
        $reg = &$this->installer->config->getRegistry();
        $package = $reg->getPackage($pkg->getPackage(), $pkg->getChannel());
        if ($package) {
            $filelist = $package->getFilelist();
            if (isset($filelist[$file]) && isset($filelist[$file]['md5sum'])) {
                $this->md5 = $filelist[$file]['md5sum'];
            }
        }
    }

    function processInstallation($pkg, $atts, $file, $tmp_path, $layer = null)
    {
        $test = parent::processInstallation($pkg, $atts, $file, $tmp_path, $layer);
        if (@file_exists($test[2]) && @file_exists($test[3])) {
            $md5 = md5_file($test[2]);
            // configuration has already been installed, check for mods
            if ($md5 !== $this->md5 && $md5 !== md5_file($test[3])) {
                // configuration has been modified, so save our version as
                // configfile-version
                $old = $test[2];
                $test[2] .= '.new-' . $pkg->getVersion();
                // backup original and re-install it
                PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
                $tmpcfg = $this->config->get('temp_dir');
                $newloc = System::mkdir(array('-p', $tmpcfg));
                if (!$newloc) {
                    // try temp_dir
                    $newloc = System::mktemp(array('-d'));
                    if (!$newloc || PEAR::isError($newloc)) {
                        PEAR::popErrorHandling();
                        return PEAR::raiseError('Could not save existing configuration file '.
                            $old . ', unable to install.  Please set temp_dir ' .
                            'configuration variable to a writeable location and try again');
                    }
                } else {
                    $newloc = $tmpcfg;
                }

                $temp_file = $newloc . DIRECTORY_SEPARATOR . uniqid('savefile');
                if (!@copy($old, $temp_file)) {
                    PEAR::popErrorHandling();
                    return PEAR::raiseError('Could not save existing configuration file '.
                        $old . ', unable to install.  Please set temp_dir ' .
                        'configuration variable to a writeable location and try again');
                }

                PEAR::popErrorHandling();
                $this->installer->log(0, "WARNING: configuration file $old is being installed as $test[2], you should manually merge in changes to the existing configuration file");
                $this->installer->addFileOperation('rename', array($temp_file, $old, false));
                $this->installer->addFileOperation('delete', array($temp_file));
            }
        }

        return $test;
    }
}


<?php
/*
 * This file is part of the Lucid Container package.
 *
 * (c) Mike Thorn <mthorn@devlucid.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Lucid\Router;

/**
 *
 * A class containing a class, method, and parameters for that method that were parsed from a url.
 *
 * @package Lucid.Router
 *
 */
class Route
{
    /**
     *
     * A string that contains the fully qualified name of the class for the route
     *
     * @var string
     *
     */
    public $class = null;

    /**
     *
     * A string that contains the name of a the method for the route
     *
     * @var string
     *
     */
    public $method = null;

    /**
     *
     * A string that contains additional parameters that were parsed from a url
     *
     * @var array
     *
     */
    public $parameters = [];

    public function __construct(string $class, string $method, array $parameters=[])
    {
        $this->class      = $class;
        $this->method     = $method;
        $this->parameters = $parameters;
    }

    /**
     * Instantiates the route's class and calls the route's methods using the parameters found in the url
     *
     * @return mixed
     *
     */
    public function execute(...$constructParameters)
    {
        $class      = $this->class;
        $method     = $this->method;
        $parameters = array_values($this->parameters);

        $instance = new $class(...$constructParameters);
        return $instance->$method(...$parameters);
    }
}


<?php

namespace liteAuth;

class User
{
    private $auth;
    public function __construct($auth, $id)
    {
        $this->id = $id;
        $this->auth = $auth;
        $info = $auth->db->get($this->auth->prefix.'users', ['user', 'first_name', 'surname', 'email', 'admin'], ['id' => $id]);
        foreach($info as $key => $value)
            $this->$key = $value;
        return $this;
    }

    /** Outputs a human readable name, base on firstname and surname, if they exist for the user,
    * but falling back on username, otherwise
    */
    public function name()
    {
        if(isset($this->first_name) && isset($this->surname))
            return $this->first_name . ' ' . $this->surname;
        elseif(isset($this->first_name))
            return $this->first_name;
        else
            return $this->user;
    }

    /** Save any changes to user properties that may have been made to the database
    */
    public function save()
    {
        $reflection = new \ReflectionObject($this);
        $properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
        foreach($properties as $prop)
            $info[$prop->name] = $this->{$prop->name};
        return $this->auth->db->update($this->auth->prefix.'users', $info, ['id' => $this->id]);
    }

    /** Changes the password for the current user
    * takes current password, then the new password twice as inputs
    */
    public function changePass($old, $new1, $new2)
    {
        if(!$this->auth->authUser($this->user, $old))
            return False;
        elseif($new1 != $new2)
            return False;
        else
            $hash = password_hash($new1, PASSWORD_BCRYPT);
            return $this->auth->db->update($this->auth->prefix.'users', ['pass' => $hash] , ['id' => $this->id]);
    }
}


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

namespace CarteBlanche\Loader;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\Kernel;
use \CarteBlanche\Interfaces\DependencyLoaderInterface;

/**
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class FrontControllerLoader implements DependencyLoaderInterface
{

    /**
     * Instance loader
     *
     * @param   array                       $config
     * @param   \CarteBlanche\App\Container $container
     * @return  null/object
     * @throws  \RuntimeException if the config doesn't define a FrontController classname
     */
    public function load(array $config = null, \CarteBlanche\App\Container $container)
    {
        $em_cfg = CarteBlanche::getConfig('default_front_controller');
        if (isset($em_cfg['class'])) {
            $em_class = $em_cfg['class'];
        } else {
            throw new \RuntimeException(
                sprintf('Front controller configuration must define a class name ("%s")!', 'default_front_controller')
            );
        }
        if (!empty($em_class)) {
            $factory = \Library\Factory::create()
                ->factoryName('FrontController')
                ->mustImplement(Kernel::FRONT_CONTROLLER_INTERFACE)
                ->callMethod('getInstance')
                ;
            return $factory->build($em_class);
        }
        return null;
    }

}

// Endfile


<?php

/**
 * This file is part of RawContainer library.
 *
 * Copyright (c) 2014 Tom Kaczocha
 *
 * This Source Code is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * PHP version 5.4
 *
 * @category  PHP
 * @package   RawPHP\RawContainer
 * @author    Taylor Otwell <taylorotwell@gmail.com>
 * @author    Tom Kaczocha <tom@crazydev.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/licenses/mpl.txt MPL
 * @link      http://rawphp.org/
 */

namespace RawPHP\RawContainer;

use Closure;
use RawPHP\RawContainer\Contract\IBindingsBuilder;
use RawPHP\RawContainer\Contract\IContainer;

/**
 * Class BindingsBuilder
 *
 * @package RawPHP\RawContainer
 */
class BindingsBuilder implements IBindingsBuilder
{
    /** @var IContainer */
    protected $container;
    /** @var string */
    protected $concrete;
    /** @var string */
    protected $needs;

    /**
     * @param IContainer $container
     * @param string     $concrete
     */
    public function __construct( IContainer $container, $concrete )
    {
        $this->container = $container;
        $this->concrete  = $concrete;
    }

    /**
     * Define the target that depends on the context.
     *
     * @param  string $abstract
     *
     * @return IBindingsBuilder
     */
    public function needs( $abstract )
    {
        $this->needs = $abstract;

        return $this;
    }

    /**
     * Define the implementation for the contextual binding.
     *
     * @param  Closure|string $implementation
     */
    public function give( $implementation )
    {
        $this->container->addContextualBindings( $this->concrete, $this->needs, $implementation );
    }
}


<?php

/**
 * @author    Sorin Badea <sorin.badea91@gmail.com>
 * @license   MIT license (see the license file in the root directory)
 */

namespace ThinFrame\Foundation\Version;

use Stringy\StaticStringy;
use ThinFrame\Foundation\Exception\InvalidArgumentException;

/**
 * Class Version
 *
 * @package ThinFrame\Foundation\Version
 * @since   0.2
 */
class Version implements VersionInterface
{
    /**
     * @var string
     */
    protected $versionString;
    /**
     * @var int
     */
    protected $major = 0;
    /**
     * @var int
     */
    protected $minor = 0;
    /**
     * @var int
     */
    protected $release = 0;
    /**
     * @var string
     */
    protected $suffix = '';

    /**
     * Constructor
     *
     * @param string $versionString version string
     */
    public function __construct($versionString)
    {
        $this->versionString = trim($versionString);
        $this->parseVersion();
    }

    /**
     * Parse version string
     *
     * @throws \ThinFrame\Foundation\Exception\InvalidArgumentException
     */
    private function parseVersion()
    {
        if (StaticStringy::startsWith($this->versionString, 'v')) {
            $this->versionString = StaticStringy::substr($this->versionString, 1);
        }
        if (strstr($this->versionString, '-')) {
            if (sscanf(
                $this->versionString,
                '%d.%d.%d-%s',
                $this->major,
                $this->minor,
                $this->release,
                $this->suffix
            ) != 4
            ) {
                throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
            }
        } else {
            if (sscanf($this->versionString, '%d.%d.%d', $this->major, $this->minor, $this->release) != 3) {
                throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
            }
        }
    }

    /**
     * Get major version
     *
     * @return int
     */
    public function getMajorVersion()
    {
        return $this->major;
    }

    /**
     * Get minor version
     *
     * @return int
     */
    public function getMinorVersion()
    {
        return $this->minor;
    }

    /**
     * Get release version
     *
     * @return int
     */
    public function getReleaseVersion()
    {
        return $this->release;
    }

    /**
     * Get version suffix
     *
     * @return string
     */
    public function getSuffix()
    {
        return $this->suffix;
    }

    /**
     * Compare with another version
     *
     * @param VersionInterface $version
     *
     * @return int (-1,0,1)
     */
    public function compare(VersionInterface $version)
    {
        if ($this->getMajorVersion() < $version->getMajorVersion()) {
            return -1;
        } elseif ($this->getMajorVersion() > $version->getMajorVersion()) {
            return 1;
        } else {
            if ($this->getMinorVersion() < $version->getMinorVersion()) {
                return -1;
            } elseif ($this->getMinorVersion() > $version->getMinorVersion()) {
                return 1;
            } else {
                if ($this->getReleaseVersion() < $version->getReleaseVersion()) {
                    return -1;
                } elseif ($this->getReleaseVersion() > $version->getReleaseVersion()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * Outputs the original version
     *
     * @return string
     */
    public function __toString()
    {
        return $this->versionString;
    }
}


<?php
/**
 * ClosureTreeBehavior class file.
 * @author Christoffer Niska <christoffer.niska@gmail.com>
 * @copyright Copyright © Christoffer Niska 2014-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package crisu83.yii-arbehaviors.behaviors
 */

/**
 * Active record behavior for handling closure trees.
 * @property CActiveRecord $owner
 */
class ClosureTreeBehavior extends CActiveRecordBehavior
{
    /**
     * @var string the name of the id attribute.
     */
    public $idAttribute = 'id';

    /**
     * @var string the name of the tree model.
     */
    public $treeClass;

    // todo: add runtime caching.

    /**
     * Returns the direct children for the owner.
     * @return CActiveRecord[] the children.
     */
    public function getChildren()
    {
        return $this->getBranch($this->owner->{$this->idAttribute});
    }

    /**
     * Returns the top level items for the owner.
     * @return CActiveRecord[] the items.
     */
    public function getRoot()
    {
        return $this->getBranch(0);
    }

    /**
     * Returns the direct children for the model with the given parent id.
     * @param int $parentId the parent id.
     * @return CActiveRecord[] the children.
     */
    public function getBranch($parentId)
    {
        $criteria = new CDbCriteria();
        $criteria->index = 'descendantId';
        $criteria->addCondition('ancestorId=:parentId AND depth=1');
        $criteria->params[':parentId'] = $parentId;
        $root = CActiveRecord::model($this->treeClass)->findAll($criteria);
        $children = $this->owner->findAllByPk(array_keys($root));
        return $children;
    }

    /**
     * Get the parent of a model.
     * @return CActiveRecord
     */
    public function getParent()
    {
        // Load the "current" level from the tree
        $currentLevel = CActiveRecord::model($this->treeClass)->findByAttributes(
            array('descendantId' => $this->owner->{$this->idAttribute}, 'depth' => 1)
        );

        if ($currentLevel->ancestorId > 0) {
            return CActiveRecord::model(get_class($this->owner))->findByPk($currentLevel->ancestorId);
        } else {
            return null;
        }
    }

    /**
     * Returns the parents for this node.
     * @param bool $includeSelf
     * @return CActiveRecord[] the parents.
     */
    public function getParents($includeSelf = true)
    {
        $parents = array();

        if ($includeSelf) {
            $parents[$this->owner->{$this->idAttribute}] = $this->owner;
        }

        // Try and find a parent
        $parent = $this->getParent();
        if ($parent instanceof CActiveRecord) {
            $parents[$parent->{$this->idAttribute}] = $parent;

            // Fetch any additional ancestry levels
            while ($nextParent = $parent->getParent()) {
                $parents[$nextParent->{$this->idAttribute}] = $nextParent;
                $parent = $nextParent;
            }
        }

        return array_reverse($parents, true);
    }
}


<?php

namespace merry;

class Container implements \ArrayAccess, \RecursiveIterator, \JsonSerializable
{
	/**
	 * Index for a numerically indexed array
	 * @internal
	 * @var int
	 */
	private $index = 0;

	/**
	 * Container
	 * @internal
	 * @var stdClass
	 */
	private $props;

	/**
	 * State for the RecursiveIterator
	 * @internal
	 * @var array
	 */
	private $riter;

	/**
	 * Whether to auto populate a requested property with a new container
	 * @internal
	 * @var bool
	 */
	private $auto;

	/**
	 * Create a new container
	 * @param array $array container data
	 * @param bool $auto whether to auto populate a requested property with a new container
	 */
	function __construct(array $array = null, $auto = true) {
		$this->props = new \stdClass;
		$this->auto = $auto;

		foreach ((array) $array as $property => $value) {
			$this->__set($property, $value);
		}
	}

	/**
	 * Recursively turn a container and its childs into an array
	 * @param \merry\Container $o the Container instance to convert to an array
	 * @return array
	 */
	protected function arrayify(Container $o) {
		$a = [];

		foreach ($o->props as $k => $v) {
			if ($v instanceof Container) {
				$a[$k] = $this->arrayify($v);
			} else {
				$a[$k] = $v;
			}
		}

		return $a;
	}

	/**
	 * Apply one or mor modifier callbacks
	 * @param mixed $modifier
	 * @return \merry\Container
	 */
	public function apply($modifier) {
		if (is_callable($modifier)) {
			foreach ($this->props as $prop => $value) {
				$this->__set($prop, $modifier($value, $prop));
			}
		} else {
			foreach ($modifier as $key => $mod) {
				if (is_callable($mod)) {
					$this->props->$key = $mod(isset($this->props->$key) ? $this->props->$key : null, $key);
				} elseif (is_array($mod)) {
					$this->props->$key->apply($mod);
				} else {
					/* */
				}
			}
		}
		return $this;
	}

	/**
	 * Return the complete config as array
	 * @return array
	 */
	function toArray() {
		return $this->arrayify($this);
	}

	/**
	 * @ignore
	 */
	function &__get($prop) {
		if ($this->auto && !isset($this->props->$prop)) {
			$this->props->$prop = new static;
		}
		return $this->props->$prop;
	}

	/**
	 * @ignore
	 */
	function __set($prop, $value) {
		if (isset($value) && !is_scalar($value) && !($value instanceof Container)) {
			$value = new static((array) $value);
		}
		if (!strlen($prop)) {
			$prop = $this->index++;
		} elseif (is_numeric($prop) && !strcmp($prop, (int) $prop)) {
			/* update internal index */
			if ($prop >= $this->index) {
				$this->index = $prop + 1;
			}
		}

		$this->props->$prop = $value;
	}

	/**
	 * @ignore
	 */
	function __isset($prop) {
		return isset($this->props->$prop);
	}

	/**
	 * @ignore
	 */
	function __unset($prop) {
		unset($this->props->$prop);
	}

	/**
	 * @ignore
	 */
	function offsetGet($o) {
		return $this->props->$o;
	}

	/**
	 * @ignore
	 */
	function offsetSet($o, $v) {
		$this->__set($o, $v);
	}

	/**
	 * @ignore
	 */
	function offsetExists($o) {
		return isset($this->props->$o);
	}

	/**
	 * @ignore
	 */
	function offsetUnset($o) {
		unset($this->props->$o);
	}

	/**
	 * @ignore
	 */
	function rewind() {
		$this->riter = (array) $this->props;
		reset($this->riter);
	}

	/**
	 * @ignore
	 */
	function valid() {
		return NULL !== key($this->riter);
	}

	/**
	 * @ignore
	 */
	function next() {
		next($this->riter);
	}

	/**
	 * @ignore
	 */
	function key() {
		return key($this->riter);
	}

	/**
	 * @ignore
	 */
	function current() {
		return current($this->riter);
	}

	/**
	 * @ignore
	 */
	function hasChildren() {
		return current($this->riter) instanceof Container;
	}

	/**
	 * @ignore
	 */
	function getChildren() {
		return current($this->riter);
	}

	/**
	 * @ignore
	 */
	function jsonSerialize() {
		return $this->arrayify($this);
	}
}

/* vim: set noet ts=4 sw=4: */


<?php

namespace Orbt\StyleMirror\Resource;

use Orbt\ResourceMirror\Resource\GenericResource;

/**
 * Resource class encapsulating the media tag of the linked styles.
 */
class CssResource extends GenericResource
{
    /**
     * CSS media type.
     */
    protected $mediaType;

    /**
     * Creates a CSS resource from URL.
     */
    public static function fromUrl($cssUrl, $baseUrl, $mediaType = 'all')
    {
        // Match URL.
        if (strpos($cssUrl, $baseUrl) === false) {
            throw new \InvalidArgumentException('The CSS URL does not begin with the base URL');
        }

        // Create.
        $baseLength = strlen(rtrim($baseUrl, '/')) + 1;
        $path = substr($cssUrl, $baseLength);
        return new CssResource($path, $mediaType);
    }

    /**
     * Constructs a CSS resource.
     *
     * @param string $path
     *   CSS resource path.
     * @param string $mediaType
     *   A media identifier string. The media type may be composite.
     */
    public function __construct($path, $mediaType = 'all')
    {
        parent::__construct($path);
        $this->mediaType = $mediaType;
    }

    public function getMediaType()
    {
        return $this->mediaType;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Class ResolveDoctrineTargetEntitiesPass
 * @package Ekyna\Bundle\CoreBundle\DependencyInjection\Compiler
 * @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
 * @see https://github.com/Sylius/SyliusResourceBundle/blob/master/DependencyInjection/DoctrineTargetEntitiesResolver.php
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ResolveDoctrineTargetEntitiesPass implements CompilerPassInterface
{
    /**
     * @var array $interfaces
     */
    private $interfaces;

    /**
     * Constructor.
     *
     * @param array $interfaces
     */
    public function __construct(array $interfaces)
    {
        $this->interfaces = $interfaces;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('doctrine.orm.listeners.resolve_target_entity')) {
            throw new \RuntimeException('Cannot find Doctrine RTEL');
        }

        $resolvedInterfaces = [];
        $resolveTargetEntityListener = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');

        foreach ($this->interfaces as $interface => $model) {
            $i = $this->getInterface($container, $interface);
            $c = $this->getClass($container, $model);

            $resolveTargetEntityListener
                ->addMethodCall('addResolveTargetEntity', [$i, $c, []])
            ;

            $resolvedInterfaces[$i] = $c;
        }

        if ($container->hasParameter('ekyna_core.interfaces')) {
            $resolvedInterfaces = array_merge($container->getParameter('ekyna_core.interfaces'), $resolvedInterfaces);
        }
        $container->setParameter('ekyna_core.interfaces', $resolvedInterfaces);

        if (!$resolveTargetEntityListener->hasTag('doctrine.event_listener')) {
            $resolveTargetEntityListener->addTag('doctrine.event_listener', ['event' => 'loadClassMetadata']);
        }
    }

    /**
     * @param ContainerBuilder $container
     * @param string           $key
     *
     * @return string
     * @throws \InvalidArgumentException
     */
    private function getInterface(ContainerBuilder $container, $key)
    {
        if ($container->hasParameter($key)) {
            return $container->getParameter($key);
        }

        if (interface_exists($key)) {
            return $key;
        }

        throw new \InvalidArgumentException(
            sprintf('The interface %s does not exist.', $key)
        );
    }

    /**
     * @param ContainerBuilder $container
     * @param string           $key
     *
     * @return string
     * @throws \InvalidArgumentException
     */
    private function getClass(ContainerBuilder $container, $key)
    {
        if ($container->hasParameter($key)) {
            return $container->getParameter($key);
        }

        if (class_exists($key)) {
            return $key;
        }

        throw new \InvalidArgumentException(
            sprintf('The class %s does not exist.', $key)
        );
    }
}


<?php

/*

This file is part of Mustard.

Mustard is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Mustard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mustard.  If not, see <http://www.gnu.org/licenses/>.

*/

namespace Hamjoint\Mustard\Messaging\Http\Controllers;

use Auth;
use Hamjoint\Mustard\Http\Controllers\Controller;
use Hamjoint\Mustard\Messaging\Message;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;

class MessagingController extends Controller
{
    /**
     * Redirect index requests to inbox.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getIndex()
    {
        return redirect('/messages/inbox');
    }

    /**
     * Return the messages inbox view.
     *
     * @return \Illuminate\View\View
     */
    public function getInbox()
    {
        return view('mustard::messages.inbox', [
            'messages' => Auth::user()->messages()
                ->received()
                ->orderBy('sent', 'desc')
                ->paginate(),
        ]);
    }

    /**
     * Return the messages sent view.
     *
     * @return \Illuminate\View\View
     */
    public function getSent()
    {
        return view('mustard::messages.sent', [
            'messages' => Auth::user()->messages()
                ->sent()
                ->orderBy('sent', 'desc')
                ->paginate(),
        ]);
    }

    /**
     * Return the messaging address book view.
     *
     * @return \Illuminate\View\View
     */
    public function getAddressBook()
    {
        $acquaintances = Auth::user()->getAcquaintances();

        return view('mustard::messages.address-book', [
            'acquaintances' => new Paginator($acquaintances, $acquaintances->count(), config('per_page', 25)),
        ]);
    }

    /**
     * Return the messaging compose view.
     *
     * @return \Illuminate\View\View
     */
    public function getCompose()
    {
        $acquaintances = Auth::user()->getAcquaintances();

        if ($acquaintances->isEmpty()) {
            return redirect()->to('/account/contacts')->withStatus('Your contacts list is empty.');
        }

        return view('mustard::messages.compose', [
            'acquaintances' => $acquaintances->sortBy('username', SORT_NATURAL | SORT_FLAG_CASE),
            'message'       => new Message(),
        ]);
    }

    /**
     * Return the messaging compose reply view.
     *
     * @param int $messageId
     *
     * @return \Illuminate\View\View
     */
    public function getReply($messageId)
    {
        return view('mustard::messages.compose', [
            'message' => Message::findOrFail($messageId),
        ]);
    }

    /**
     * Return the messaging message view.
     *
     * @param int $messageId
     *
     * @return \Illuminate\View\View
     */
    public function getView($messageId)
    {
        $message = Message::find($messageId);

        $message->read = true;

        $message->save();

        return view('mustard::messages.view', [
            'message' => $message,
        ]);
    }

    /**
     * Send a message.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postSend(Request $request)
    {
        $message = new Message();

        $message->subject = $request->input('subject');
        $message->body = $request->input('body');
        $message->sent = time();

        if ($request->input('parent_message_id')) {
            $parent = Message::findOrFail($request->input('parent_message_id'));

            $message->parent()->associate($parent);
        }

        $recipient = User::findOrFail($request->input('recipient_user_id'));

        if (Auth::user()->getAcquaintances()->contains($recipient)) {
            // fail
        }

        $message->recipient()->associate($recipient);

        $message->sender()->associate(Auth::user());

        $sent_copy = clone $message;

        $sent_copy->user()->associate(Auth::user());

        $message->user()->associate($recipient);

        $message->save();

        $sent_copy->save();

        return redirect()->back()->withStatus("Message sent to {$recipient->username}.");
    }

    /**
     * Manage message flags.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postManage(Request $request)
    {
        foreach ($request->input('messages') as $message_id) {
            $message = Message::find($message_id);

            if (is_null($message) || !$request->has('action')) {
                continue;
            }

            switch ($request->input('action')) {
                case 'mark_read':
                    if ($message->read == false) {
                        $message->read = true;

                        $message->save();
                    }

                    break;
                case 'mark_unread':
                    if ($message->read == true) {
                        $message->read = false;

                        $message->save();
                    }

                    break;
                case 'delete':
                    $message->delete();

                    break;
            }
        }

        return redirect()->back();
    }
}


<?php

namespace Sasedev\Commons\SharedBundle\Controller;

use Gaufrette\Adapter\Cache as CacheAdapter;
use Gaufrette\Adapter\Local as LocalAdapter;
use Gaufrette\Filesystem;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\SpecialMetas\CharsetMeta;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\SpecialMetas\Name\Author;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\SpecialLinks\Icon;
use Sasedev\Commons\SharedBundle\HtmlModel\Attributes\Href;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 *
 * @author sasedev <seif.salah@gmail.com>
 */
class VfsController extends BaseController
{

	/**
	 * Constructor
	 */
	public function __construct()
	{
		$metaCharset = new CharsetMeta('utf-8');

		$this->addHeadMeta($metaCharset);

		$metaAuthor = new Author('SASEdev');

		$this->addHeadMeta($metaAuthor);

		$favicon = new Icon(new Href('favicon.ico', true));

		$this->addHeadLink($favicon);

		$this->addTwigVar('menu_active', 'home');

	}

	/**
	 * Get Virtual Files Action
	 *
	 * @param string $file
	 *
	 * @throws NotFoundHttpException
	 * @return Response
	 *
	 * @Route(name="sasedev_commons_shared_vfs_files", path="/Vfs{file}", requirements={"file" = ".*"}, defaults={"file" = null})
	 */
	public function fileAction($file = null)
	{
		if (null == $file) {
			return $this->redirect($this->generateUrl('sasedev_commons_shared_vfs_files', array('file' => '/')));
		}

		$cacheDirectory = $this->getParameter('adapter_cache_dir');
		$local = new LocalAdapter($cacheDirectory, true);
		$localadapter = new LocalAdapter($this->getParameter('adapter_files'));
		$adapter = new CacheAdapter($localadapter, $local, 3600);

		$fsAvatar = new Filesystem($adapter);
		if ($this->endswith($file, '/')) {
			if ($fsAvatar->has($file)) {
				$this->setPageTitle($this->translate('indexof',
					array('%dir%' => $this->generateUrl('sasedev_commons_shared_vfs_files', array('file' => $file)))));

				$this->addTwigVar('pagetitle', $this->translate('indexof_raw',
					array('%dir%' => $this->generateUrl('sasedev_commons_shared_vfs_files', array('file' => $file)))));

				$path = substr($file, 1);
				$fs = $fsAvatar->listKeys($path);

				$listfiles = array();
				foreach ($fs['dirs'] as $key) {
					$fulldir = $key . "/";
					$dirname = $key;
					if (substr($key, 0, strlen($path)) == $path) {
						$dirname = substr($dirname, strlen($path));
					}
					if (!strstr($dirname, "/")) {
						$listfiles[$fulldir] = $dirname;
					}
				}
				foreach ($fs['keys'] as $key) {
					$fullfile = $key;
					$filename = $key;
					if (substr($key, 0, strlen($path)) == $path) {
						$filename = substr($filename, strlen($path));
					}
					if (!strstr($filename, "/")) {
						$listfiles[$fullfile] = $filename;
					}
				}
				$this->addTwigVar('fs', $listfiles);

				return $this->render('SasedevCommonsSharedBundle:Vfs:list_files.html.twig', $this->getTwigVars());
			} else {
				throw new NotFoundHttpException();
			}
		}
		if ($fsAvatar->has($file)) {
			if ($fsAvatar->getAdapter()->isDirectory($file)) {
				$file .= "/";

				return $this->redirect($this->generateUrl('sasedev_commons_shared_vfs_files', array('file' => $file)));
			}
			$reqFile = $fsAvatar->get($file);
			$response = new Response();
			$response->headers->set('Content-Type', 'binary');
			$response->setContent($reqFile->getContent());

			return $response;
		} else {
			throw new NotFoundHttpException();
		}
	}

	/**
	 * Get Temporary Virtual Files Action
	 *
	 * @param string $file
	 *
	 * @throws NotFoundHttpException
	 * @return Response
	 *
	 * @Route(name="sasedev_commons_shared_vfs_tmp_files", path="/tmpVfs{file}", requirements={"file" = ".*"}, defaults={"file" = null})
	 */
	public function tempfileAction($file = null)
	{
		if (null == $file) {
			return $this->redirect($this->generateUrl('sasedev_commons_shared_vfs_tmp_files', array('file' => '/')));
		}

		$cacheDirectory = $this->getParameter('adapter_cache_dir');
		$local = new LocalAdapter($cacheDirectory, true);
		$localadapter = new LocalAdapter($this->getParameter('adapter_tmp_files'));
		$adapter = new CacheAdapter($localadapter, $local, 3600);

		$fsAvatar = new Filesystem($adapter);
		if ($this->endswith($file, '/')) {
			if ($fsAvatar->has($file)) {
				$this->setPageTitle($this->translate('indexof',
					array('%dir%' => $this->generateUrl('sasedev_commons_shared_vfs_tmp_files', array('file' => $file)))));

				$this->addTwigVar('pagetitle', $this->translate('indexof_raw',
					array('%dir%' => $this->generateUrl('sasedev_commons_shared_vfs_tmp_files', array('file' => $file)))));

				$path = substr($file, 1);
				$fs = $fsAvatar->listKeys($path);

				$listfiles = array();
				foreach ($fs['dirs'] as $key) {
					$fulldir = $key . "/";
					$dirname = $key;
					if (substr($key, 0, strlen($path)) == $path) {
						$dirname = substr($dirname, strlen($path));
					}
					if (!strstr($dirname, "/")) {
						$listfiles[$fulldir] = $dirname;
					}
				}
				foreach ($fs['keys'] as $key) {
					$fullfile = $key;
					$filename = $key;
					if (substr($key, 0, strlen($path)) == $path) {
						$filename = substr($filename, strlen($path));
					}
					if (!strstr($filename, "/")) {
						$listfiles[$fullfile] = $filename;
					}
				}
				$this->addTwigVar('fs', $listfiles);

				return $this->render('SasedevCommonsSharedBundle:Vfs:list_temp_files.html.twig', $this->getTwigVars());
			} else {
				throw new NotFoundHttpException();
			}
		}
		if ($fsAvatar->has($file)) {
			if ($fsAvatar->getAdapter()->isDirectory($file)) {
				$file .= "/";

				return $this->redirect($this->generateUrl('sasedev_commons_shared_vfs_tmp_files', array('file' => $file)));
			}
			$reqFile = $fsAvatar->get($file);
			$response = new Response();
			$response->headers->set('Content-Type', 'binary');
			$response->setContent($reqFile->getContent());

			return $response;
		} else {
			throw new NotFoundHttpException();
		}
	}
}


<?php
namespace Nubs\Which\PathBuilder;

/**
 * Appends extensions to an array of files.
 */
trait WindowsExtensionAppenderTrait
{
    /**
     * Append the extensions to the paths.
     *
     * @param array $paths The file paths to append to.
     * @param array $extensions The extensions.
     * @return array The full combination of every path with every extension.
     */
    protected function _appendExtensionsToPaths(array $paths, array $extensions)
    {
        $getPathsWithExtensions = function($path) use($extensions) {
            if ($this->_hasExtension($path)) {
                return [$path];
            }

            $addExtension = function($extension) use($path) {
                return $this->_addExtension($path, $extension);
            };

            return array_map($addExtension, $extensions);
        };

        return call_user_func_array('array_merge', array_map($getPathsWithExtensions, $paths));
    }

    /**
     * Adds an extension to a path.
     *
     * @param string $path The path.
     * @param string $extension The extension to add.
     * @return string The path with extension.
     */
    protected function _addExtension($path, $extension)
    {
        return $path . $extension;
    }

    /**
     * Checks to see if a path already has an extension.
     *
     * @param string $path The path to check.
     * @return boolean True if it has an extension, false otherwise.
     */
    protected function _hasExtension($path)
    {
        return strpos($path, '.') !== false;
    }
}


<?php

namespace Dashifen\Session;

/**
 * Class Session
 *
 * @package Dashifen\Session
 */
class Session implements SessionInterface {

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

	/**
	 * Session constructor.
	 *
	 * @param string $index
	 *
	 * @throws SessionException
	 */
	public function __construct(string $index = SessionInterface::defaultIndex) {
		$this->index = empty($index) ? $this->getIndex() : $index;

		// if we haven't started the session already, we'll make sure we do so
		// now.  if we can't start it, we toss an exception and how the rest of
		// our app knows what to do.

		if (session_id() === "") {
			if (!session_start()) {
				throw new SessionException("Unable to start session",
					SessionException::CANNOT_START);
			}
		}

		// to help avoid colliding with other session information, we're going to
		// put everything we manage into an array identified by the index we were
		// sent or generated above.  but, since we might be reconnecting to a
		// session already in progress, we'll only want to create that array if
		// it's not already present.

		if (!isset($_SESSION[$this->index]) || !is_array($_SESSION[$this->index])) {
			$_SESSION[$this->index] = [];
		}
	}

	protected function getIndex() {

		// if we're reconnecting to a visitor's session, then the index is
		// actually stored in the session for us to find.  if this is the
		// first time we've created a session for this visitor, we'll create
		// one.  our interface defines the index at which we find our index,
		// the index-index if you will.

		return $_SESSION[SessionInterface::defaultIndex] ?? uniqid();
	}

	/**
	 * @return bool
	 */
	public function isAuthenticated(): bool {
		return $this->exists("AUTHENTICATED");
	}

	/**
	 * @param string $index
	 *
	 * @return bool
	 */
	public function exists(string $index): bool {
		return isset($_SESSION[$this->index][$index]);
	}

	/**
	 * @param string $username
	 * @param array  $parameters
	 */
	public function login(string $username, array $parameters = []): void {
		session_regenerate_id();

		// this function is not intended to perform the authentication or authorization
		// routines.  instead, it assumes these are done and simply stores the results of
		// those routines in the session as follows.

		$this->set("AUTHENTICATED", true);
		$this->set("USERNAME", $username);
		foreach ($parameters as $i => $value) {
			$this->set($i, $value);
		}
	}

	/**
	 * @param string $index
	 * @param        $value
	 */
	public function set(string $index, $value): void {
		$_SESSION[$this->index][$index] = $value;
	}

	/**
	 * Destroys a session.
	 *
	 * @return void
	 */
	public function destroy(): void {

		// see example here http://goo.gl/nBVl0

		$this->logout();
		$p = session_get_cookie_params();
		setcookie(session_name(), "", time() - 42000, $p["path"],
			$p["domain"], $p["secure"], $p["httponly"]);

		session_destroy();
	}

	/**
	 * Destroys a session.
	 *
	 * @return void
	 */
	public function logout() {
		$_SESSION[$this->index] = [];
	}

	/**
	 * @param  string $index
	 * @param string  $default
	 *
	 * @return mixed|null
	 */
	public function get(string $index, $default = null) {
		return $this->exists($index) ? $_SESSION[$this->index][$index] : $default;
	}

	/**
	 * @param string $index
	 */
	public function remove(string $index): void {
		unset($_SESSION[$this->index][$index]);
	}

	/**
	 * @return array
	 */
	public function getSession(): array {
		return $_SESSION[$this->index];
	}
}


<?php
/**
 * Class auto-loader
 *
 * PHP versions 4

 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    CVS: $Id: Autoloader.php 313023 2011-07-06 19:17:11Z dufuz $
 * @link       http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
 * @since      File available since Release 0.1
 * @deprecated File deprecated in Release 1.4.0a1
 */

// /* vim: set expandtab tabstop=4 shiftwidth=4: */

if (!extension_loaded("overload")) {
    // die hard without ext/overload
    die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader");
}

/**
 * Include for PEAR_Error and PEAR classes
 */
require_once "PEAR.php";

/**
 * This class is for objects where you want to separate the code for
 * some methods into separate classes.  This is useful if you have a
 * class with not-frequently-used methods that contain lots of code
 * that you would like to avoid always parsing.
 *
 * The PEAR_Autoloader class provides autoloading and aggregation.
 * The autoloading lets you set up in which classes the separated
 * methods are found.  Aggregation is the technique used to import new
 * methods, an instance of each class providing separated methods is
 * stored and called every time the aggregated method is called.
 *
 * @category   pear
 * @package    PEAR
 * @author Stig Bakken <ssb@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.4
 * @link       http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
 * @since      File available since Release 0.1
 * @deprecated File deprecated in Release 1.4.0a1
 */
class PEAR_Autoloader extends PEAR
{
    // {{{ properties

    /**
     * Map of methods and classes where they are defined
     *
     * @var array
     *
     * @access private
     */
    var $_autoload_map = array();

    /**
     * Map of methods and aggregate objects
     *
     * @var array
     *
     * @access private
     */
    var $_method_map = array();

    // }}}
    // {{{ addAutoload()

    /**
     * Add one or more autoload entries.
     *
     * @param string $method     which method to autoload
     *
     * @param string $classname  (optional) which class to find the method in.
     *                           If the $method parameter is an array, this
     *                           parameter may be omitted (and will be ignored
     *                           if not), and the $method parameter will be
     *                           treated as an associative array with method
     *                           names as keys and class names as values.
     *
     * @return void
     *
     * @access public
     */
    function addAutoload($method, $classname = null)
    {
        if (is_array($method)) {
            array_walk($method, create_function('$a,&$b', '$b = strtolower($b);'));
            $this->_autoload_map = array_merge($this->_autoload_map, $method);
        } else {
            $this->_autoload_map[strtolower($method)] = $classname;
        }
    }

    // }}}
    // {{{ removeAutoload()

    /**
     * Remove an autoload entry.
     *
     * @param string $method  which method to remove the autoload entry for
     *
     * @return bool TRUE if an entry was removed, FALSE if not
     *
     * @access public
     */
    function removeAutoload($method)
    {
        $method = strtolower($method);
        $ok = isset($this->_autoload_map[$method]);
        unset($this->_autoload_map[$method]);
        return $ok;
    }

    // }}}
    // {{{ addAggregateObject()

    /**
     * Add an aggregate object to this object.  If the specified class
     * is not defined, loading it will be attempted following PEAR's
     * file naming scheme.  All the methods in the class will be
     * aggregated, except private ones (name starting with an
     * underscore) and constructors.
     *
     * @param string $classname  what class to instantiate for the object.
     *
     * @return void
     *
     * @access public
     */
    function addAggregateObject($classname)
    {
        $classname = strtolower($classname);
        if (!class_exists($classname)) {
            $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname);
            include_once $include_file;
        }
        $obj =& new $classname;
        $methods = get_class_methods($classname);
        foreach ($methods as $method) {
            // don't import priviate methods and constructors
            if ($method{0} != '_' && $method != $classname) {
                $this->_method_map[$method] = $obj;
            }
        }
    }

    // }}}
    // {{{ removeAggregateObject()

    /**
     * Remove an aggregate object.
     *
     * @param string $classname  the class of the object to remove
     *
     * @return bool  TRUE if an object was removed, FALSE if not
     *
     * @access public
     */
    function removeAggregateObject($classname)
    {
        $ok = false;
        $classname = strtolower($classname);
        reset($this->_method_map);
        while (list($method, $obj) = each($this->_method_map)) {
            if (is_a($obj, $classname)) {
                unset($this->_method_map[$method]);
                $ok = true;
            }
        }
        return $ok;
    }

    // }}}
    // {{{ __call()

    /**
     * Overloaded object call handler, called each time an
     * undefined/aggregated method is invoked.  This method repeats
     * the call in the right aggregate object and passes on the return
     * value.
     *
     * @param string $method  which method that was called
     *
     * @param string $args    An array of the parameters passed in the
     *                        original call
     *
     * @return mixed  The return value from the aggregated method, or a PEAR
     *                error if the called method was unknown.
     */
    function __call($method, $args, &$retval)
    {
        $method = strtolower($method);
        if (empty($this->_method_map[$method]) && isset($this->_autoload_map[$method])) {
            $this->addAggregateObject($this->_autoload_map[$method]);
        }
        if (isset($this->_method_map[$method])) {
            $retval = call_user_func_array(array($this->_method_map[$method], $method), $args);
            return true;
        }
        return false;
    }

    // }}}
}

overload("PEAR_Autoloader");

?>


<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
 * PHP Version 5
 *
 * Copyright (c) 1997-2004 The PHP Group
 *
 * This source file is subject to version 3.0 of the PHP license,
 * that is bundled with this package in the file LICENSE, and is
 * available through the world-wide-web at the following url:
 * http://www.php.net/license/3_0.txt.
 * If you did not receive a copy of the PHP license and are unable to
 * obtain it through the world-wide-web, please send a note to
 * license@php.net so we can mail you a copy immediately.
 *
 * @category Console
 * @package  Console_Getopt
 * @author   Andrei Zmievski <andrei@php.net>
 * @license  http://www.php.net/license/3_0.txt PHP 3.0
 * @version  CVS: $Id: Getopt.php 306067 2010-12-08 00:13:31Z dufuz $
 * @link     http://pear.php.net/package/Console_Getopt
 */

require_once 'PEAR.php';

/**
 * Command-line options parsing class.
 *
 * @category Console
 * @package  Console_Getopt
 * @author   Andrei Zmievski <andrei@php.net>
 * @license  http://www.php.net/license/3_0.txt PHP 3.0
 * @link     http://pear.php.net/package/Console_Getopt
 */
class Console_Getopt
{

    /**
     * Parses the command-line options.
     *
     * The first parameter to this function should be the list of command-line
     * arguments without the leading reference to the running program.
     *
     * The second parameter is a string of allowed short options. Each of the
     * option letters can be followed by a colon ':' to specify that the option
     * requires an argument, or a double colon '::' to specify that the option
     * takes an optional argument.
     *
     * The third argument is an optional array of allowed long options. The
     * leading '--' should not be included in the option name. Options that
     * require an argument should be followed by '=', and options that take an
     * option argument should be followed by '=='.
     *
     * The return value is an array of two elements: the list of parsed
     * options and the list of non-option command-line arguments. Each entry in
     * the list of parsed options is a pair of elements - the first one
     * specifies the option, and the second one specifies the option argument,
     * if there was one.
     *
     * Long and short options can be mixed.
     *
     * Most of the semantics of this function are based on GNU getopt_long().
     *
     * @param array  $args          an array of command-line arguments
     * @param string $short_options specifies the list of allowed short options
     * @param array  $long_options  specifies the list of allowed long options
     * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
     *
     * @return array two-element array containing the list of parsed options and
     * the non-option arguments
     * @access public
     */
    function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
    {
        return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
    }

    /**
     * This function expects $args to start with the script name (POSIX-style).
     * Preserved for backwards compatibility.
     *
     * @param array  $args          an array of command-line arguments
     * @param string $short_options specifies the list of allowed short options
     * @param array  $long_options  specifies the list of allowed long options
     *
     * @see getopt2()
     * @return array two-element array containing the list of parsed options and
     * the non-option arguments
     */
    function getopt($args, $short_options, $long_options = null, $skip_unknown = false)
    {
        return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown);
    }

    /**
     * The actual implementation of the argument parsing code.
     *
     * @param int    $version       Version to use
     * @param array  $args          an array of command-line arguments
     * @param string $short_options specifies the list of allowed short options
     * @param array  $long_options  specifies the list of allowed long options
     * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
     *
     * @return array
     */
    function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
    {
        // in case you pass directly readPHPArgv() as the first arg
        if (PEAR::isError($args)) {
            return $args;
        }

        if (empty($args)) {
            return array(array(), array());
        }

        $non_opts = $opts = array();

        settype($args, 'array');

        if ($long_options) {
            sort($long_options);
        }

        /*
         * Preserve backwards compatibility with callers that relied on
         * erroneous POSIX fix.
         */
        if ($version < 2) {
            if (isset($args[0]{0}) && $args[0]{0} != '-') {
                array_shift($args);
            }
        }

        reset($args);
        while (list($i, $arg) = each($args)) {
            /* The special element '--' means explicit end of
               options. Treat the rest of the arguments as non-options
               and end the loop. */
            if ($arg == '--') {
                $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
                break;
            }

            if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
                $non_opts = array_merge($non_opts, array_slice($args, $i));
                break;
            } elseif (strlen($arg) > 1 && $arg{1} == '-') {
                $error = Console_Getopt::_parseLongOption(substr($arg, 2),
                                                          $long_options,
                                                          $opts,
                                                          $args,
                                                          $skip_unknown);
                if (PEAR::isError($error)) {
                    return $error;
                }
            } elseif ($arg == '-') {
                // - is stdin
                $non_opts = array_merge($non_opts, array_slice($args, $i));
                break;
            } else {
                $error = Console_Getopt::_parseShortOption(substr($arg, 1),
                                                           $short_options,
                                                           $opts,
                                                           $args,
                                                           $skip_unknown);
                if (PEAR::isError($error)) {
                    return $error;
                }
            }
        }

        return array($opts, $non_opts);
    }

    /**
     * Parse short option
     *
     * @param string     $arg           Argument
     * @param string[]   $short_options Available short options
     * @param string[][] &$opts
     * @param string[]   &$args
     * @param boolean    $skip_unknown suppresses Console_Getopt: unrecognized option
     *
     * @access private
     * @return void
     */
    function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown)
    {
        for ($i = 0; $i < strlen($arg); $i++) {
            $opt     = $arg{$i};
            $opt_arg = null;

            /* Try to find the short option in the specifier string. */
            if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') {
                if ($skip_unknown === true) {
                    break;
                }

                $msg = "Console_Getopt: unrecognized option -- $opt";
                return PEAR::raiseError($msg);
            }

            if (strlen($spec) > 1 && $spec{1} == ':') {
                if (strlen($spec) > 2 && $spec{2} == ':') {
                    if ($i + 1 < strlen($arg)) {
                        /* Option takes an optional argument. Use the remainder of
                           the arg string if there is anything left. */
                        $opts[] = array($opt, substr($arg, $i + 1));
                        break;
                    }
                } else {
                    /* Option requires an argument. Use the remainder of the arg
                       string if there is anything left. */
                    if ($i + 1 < strlen($arg)) {
                        $opts[] = array($opt,  substr($arg, $i + 1));
                        break;
                    } else if (list(, $opt_arg) = each($args)) {
                        /* Else use the next argument. */;
                        if (Console_Getopt::_isShortOpt($opt_arg)
                            || Console_Getopt::_isLongOpt($opt_arg)) {
                            $msg = "option requires an argument --$opt";
                            return PEAR::raiseError("Console_Getopt:" . $msg);
                        }
                    } else {
                        $msg = "option requires an argument --$opt";
                        return PEAR::raiseError("Console_Getopt:" . $msg);
                    }
                }
            }

            $opts[] = array($opt, $opt_arg);
        }
    }

    /**
     * Checks if an argument is a short option
     *
     * @param string $arg Argument to check
     *
     * @access private
     * @return bool
     */
    function _isShortOpt($arg)
    {
        return strlen($arg) == 2 && $arg[0] == '-'
               && preg_match('/[a-zA-Z]/', $arg[1]);
    }

    /**
     * Checks if an argument is a long option
     *
     * @param string $arg Argument to check
     *
     * @access private
     * @return bool
     */
    function _isLongOpt($arg)
    {
        return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
               preg_match('/[a-zA-Z]+$/', substr($arg, 2));
    }

    /**
     * Parse long option
     *
     * @param string     $arg          Argument
     * @param string[]   $long_options Available long options
     * @param string[][] &$opts
     * @param string[]   &$args
     *
     * @access private
     * @return void|PEAR_Error
     */
    function _parseLongOption($arg, $long_options, &$opts, &$args, $skip_unknown)
    {
        @list($opt, $opt_arg) = explode('=', $arg, 2);

        $opt_len = strlen($opt);

        for ($i = 0; $i < count($long_options); $i++) {
            $long_opt  = $long_options[$i];
            $opt_start = substr($long_opt, 0, $opt_len);

            $long_opt_name = str_replace('=', '', $long_opt);

            /* Option doesn't match. Go on to the next one. */
            if ($long_opt_name != $opt) {
                continue;
            }

            $opt_rest = substr($long_opt, $opt_len);

            /* Check that the options uniquely matches one of the allowed
               options. */
            if ($i + 1 < count($long_options)) {
                $next_option_rest = substr($long_options[$i + 1], $opt_len);
            } else {
                $next_option_rest = '';
            }

            if ($opt_rest != '' && $opt{0} != '=' &&
                $i + 1 < count($long_options) &&
                $opt == substr($long_options[$i+1], 0, $opt_len) &&
                $next_option_rest != '' &&
                $next_option_rest{0} != '=') {

                $msg = "Console_Getopt: option --$opt is ambiguous";
                return PEAR::raiseError($msg);
            }

            if (substr($long_opt, -1) == '=') {
                if (substr($long_opt, -2) != '==') {
                    /* Long option requires an argument.
                       Take the next argument if one wasn't specified. */;
                    if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
                        $msg = "Console_Getopt: option requires an argument --$opt";
                        return PEAR::raiseError($msg);
                    }

                    if (Console_Getopt::_isShortOpt($opt_arg)
                        || Console_Getopt::_isLongOpt($opt_arg)) {
                        $msg = "Console_Getopt: option requires an argument --$opt";
                        return PEAR::raiseError($msg);
                    }
                }
            } else if ($opt_arg) {
                $msg = "Console_Getopt: option --$opt doesn't allow an argument";
                return PEAR::raiseError($msg);
            }

            $opts[] = array('--' . $opt, $opt_arg);
            return;
        }

        if ($skip_unknown === true) {
            return;
        }

        return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
    }

    /**
     * Safely read the $argv PHP array across different PHP configurations.
     * Will take care on register_globals and register_argc_argv ini directives
     *
     * @access public
     * @return mixed the $argv PHP array or PEAR error if not registered
     */
    function readPHPArgv()
    {
        global $argv;
        if (!is_array($argv)) {
            if (!@is_array($_SERVER['argv'])) {
                if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
                    $msg = "Could not read cmd args (register_argc_argv=Off?)";
                    return PEAR::raiseError("Console_Getopt: " . $msg);
                }
                return $GLOBALS['HTTP_SERVER_VARS']['argv'];
            }
            return $_SERVER['argv'];
        }
        return $argv;
    }

}


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

/**
 * Помощник ручной сортировки
 *
 * @package ORM
 * @since 1.00
 */
class ORM_Helper_Ordering
{
    /**
     * Поле, хранящее порядковый номер
     *
     * @var string
     */
    private $fieldName = 'position';

    /**
     * Список полей для группировки
     *
     * @var array
     */
    private $groupBy = array();

    /**
     * Задаёт список полей по которым надо выполнять группировку
     *
     * Считается что записи принадлежат к одной группе, если значения перечисленных полей у всех
     * записей совпадают.
     *
     * @param string $field1  1-е поле для группировки
     * @param ...
     *
     * @return void
     *
     * @since 1.00
     */
    public function groupBy($field1)
    {
        $this->groupBy = func_get_args();
    }

    /**
     * Задаёт имя поля, содержащего порядковый номер
     *
     * @param string $name
     *
     * @return void
     *
     * @since 1.00
     */
    public function setFieldName($name)
    {
        $this->fieldName = $name;
    }

    /**
     * Перемещает запись выше в группе
     * @param ORM_Entity $entity
     *
     * @return void
     *
     * @since 1.00
     */
    public function moveUp(ORM_Entity $entity)
    {
        if (0 == $entity->{$this->fieldName})
        {
            // Выше некуда
            return;
        }
        $table = $entity->getTable();
        $q = $table->createSelectQuery(false);
        $e = $q->expr;
        $group = array();
        foreach ($this->groupBy as $field)
        {
            $group []= $e->eq($field, $q->bindValue($entity->$field));
        }
        $group []= $e->lt($this->fieldName, $q->bindValue($entity->{$this->fieldName}, null,
            PDO::PARAM_INT));
        $q->select('*');
        $q->where(call_user_func_array(array($e, 'lAnd'), $group))->
            orderBy($this->fieldName, ezcQuerySelect::DESC);
        $swap = $table->loadOneFromQuery($q);

        if (!$swap)
        {
            // Выше некуда
            return;
        }

        $this->swap($table, $entity, $swap);
    }

    /**
     * Перемещает запись ниже в группе
     * @param ORM_Entity $entity
     *
     * @return void
     *
     * @since 1.00
     */
    public function moveDown(ORM_Entity $entity)
    {
        $table = $entity->getTable();
        $q = $table->createSelectQuery(false);
        $e = $q->expr;
        $group = array();
        foreach ($this->groupBy as $field)
        {
            $group []= $e->eq($field, $q->bindValue($entity->$field));
        }
        $group []= $e->gt($this->fieldName, $q->bindValue($entity->{$this->fieldName}, null,
            PDO::PARAM_INT));
        $q->select('*');
        $q->where(call_user_func_array(array($e, 'lAnd'), $group))->
            orderBy($this->fieldName, ezcQuerySelect::ASC);
        $swap = $table->loadOneFromQuery($q);

        if (!$swap)
        {
            // Ниже некуда
            return;
        }

        $this->swap($table, $entity, $swap);
    }

    /**
     * Меняет сущности местами в их группе
     *
     * @param ORM_Table  $table  таблица
     * @param ORM_Entity $ent1   сущность 1
     * @param ORM_Entity $ent2   сущность 2
     *
     * @return void
     *
     * @since 1.00
     */
    protected function swap(ORM_Table $table, ORM_Entity $ent1, ORM_Entity $ent2)
    {
        $pos = $ent1->{$this->fieldName};
        $ent1->{$this->fieldName} = $ent2->{$this->fieldName};
        $ent2->{$this->fieldName} = $pos;
        $table->update($ent1);
        $table->update($ent2);
    }
}