<?php declare(strict_types=1);

namespace ts\Reflection;

class ReflectionMethod
{
    use SelfReflectionTrait;

    /**
     * @var \ReflectionMethod
     */
    private $reflectionMethod;

    /**
     * @param string|object $class
     * @param string        $name
     *
     * @throws \ReflectionException
     */
    public function __construct($class, string $name)
    {
        $this->reflectionMethod = new \ReflectionMethod($class, $name);
    }

    /**
     * Exports
     *
     * @link  https://php.net/manual/en/reflector.export.php
     * @return string
     * @since 5.0
     */
    public static function export()
    {
        throw new \RuntimeException('Unsupported method ' . __METHOD__);
    }

    public function isPublic(): bool
    {
        return $this->reflectionMethod->isPublic();
    }

    public function isPrivate(): bool
    {
        return $this->reflectionMethod->isPrivate();
    }

    public function isProtected(): bool
    {
        return $this->reflectionMethod->isProtected();
    }

    public function isAbstract(): bool
    {
        return $this->reflectionMethod->isAbstract();
    }

    public function isFinal(): bool
    {
        return $this->reflectionMethod->isFinal();
    }

    public function isStatic(): bool
    {
        return $this->reflectionMethod->isStatic();
    }

    public function isConstructor(): bool
    {
        return $this->reflectionMethod->isConstructor();
    }

    public function getClosure(object $object = null): \Closure
    {
        $result = $this->reflectionMethod->getClosure($object);
        if (null === $result) {
            throw new \RuntimeException('Unexpeted error in ' . __METHOD__);
        }

        return $result;
    }

    /**
     * @param object|null $object
     * @param mixed       ...$parameters
     *
     * @return mixed
     */
    public function invoke(?object $object = null, ...$parameters)
    {
        return $this->reflectionMethod->invoke($object, ...$parameters);
    }

    /**
     * @param object|null $object
     * @param array       $args
     *
     * @return mixed
     */
    public function invokeArgs(?object $object, array $args)
    {
        return $this->reflectionMethod->invokeArgs($object, $args);
    }

    public function getPrototype(): self
    {
        $reflectionMethod = $this->reflectionMethod->getPrototype();

        return self::constructFromReflectionMethod($reflectionMethod);
    }

    /**
     * For when we need to return instances of self from an existing instance of \ReflectionClass
     *
     * @param \ReflectionMethod $reflectionMethod
     *
     * @return self
     * @throws \ReflectionException
     */
    public static function constructFromReflectionMethod(\ReflectionMethod $reflectionMethod): self
    {
        /**
         * @var self $instance
         */
        $instance                   = self::getSelfReflection()->newInstanceWithoutConstructor();
        $instance->reflectionMethod = $reflectionMethod;

        return $instance;
    }

    public function setAccessible(bool $accessible): void
    {
        $this->reflectionMethod->setAccessible($accessible);
    }

    public function inNamespace(): bool
    {
        return $this->reflectionMethod->inNamespace();
    }

    public function isClosure(): bool
    {
        return $this->reflectionMethod->isClosure();
    }

    public function isDeprecated(): bool
    {
        return $this->reflectionMethod->isDeprecated();
    }

    public function isInternal(): bool
    {
        return $this->reflectionMethod->isInternal();
    }

    public function isUserDefined(): bool
    {
        return $this->reflectionMethod->isUserDefined();
    }

    public function getClosureThis(): object
    {
        return $this->reflectionMethod->getClosureThis();
    }

    public function getClosureScopeClass(): ReflectionClass
    {
        $result = $this->reflectionMethod->getClosureScopeClass();
        if (null === $result) {
            throw new \RuntimeException('Unexpected error in ' . __METHOD__);
        }

        return ReflectionClass::constructFromReflectionClass($result);
    }

    public function getDocComment(): ?string
    {
        return $this->reflectionMethod->getDocComment() ?: null;
    }

    public function getEndLine(): int
    {
        $result = $this->reflectionMethod->getEndLine();
        if (false === $result) {
            throw new \RuntimeException('Unexpected error in ' . __METHOD__);
        }

        return $result;
    }

    public function getExtension(): \ReflectionExtension
    {
        return $this->reflectionMethod->getExtension();
    }

    public function getExtensionName(): string
    {
        return $this->reflectionMethod->getExtensionName();
    }

    public function getFileName(): string
    {
        $result = $this->reflectionMethod->getFileName();
        if (false === $result) {
            throw new \RuntimeException('Unexpected error in ' . __METHOD__);
        }

        return $result;
    }

    public function getName(): string
    {
        return $this->reflectionMethod->getName();
    }

    public function getNamespaceName(): string
    {
        return $this->reflectionMethod->getNamespaceName();
    }

    public function getNumberOfParameters(): int
    {
        return $this->reflectionMethod->getNumberOfParameters();
    }

    public function getNumberOfRequiredParameters(): int
    {
        return $this->reflectionMethod->getNumberOfRequiredParameters();
    }

    public function getParameters(): array
    {
        return $this->reflectionMethod->getParameters();
    }

    public function getReturnType(): ?\ReflectionType
    {
        return $this->reflectionMethod->getReturnType();
    }

    public function getShortName(): string
    {
        return $this->reflectionMethod->getShortName();
    }

    public function getStartLine(): int
    {
        $result = $this->reflectionMethod->getStartLine();
        if (false === $result) {
            throw new \RuntimeException('Unexpected error in ' . __METHOD__);
        }

        return $result;
    }

    public function getStaticVariables(): array
    {
        return $this->reflectionMethod->getStaticVariables();
    }

    public function hasReturnType(): bool
    {
        return $this->reflectionMethod->hasReturnType();
    }

    public function returnsReference(): bool
    {
        return $this->reflectionMethod->returnsReference();
    }

    public function isGenerator(): bool
    {
        return $this->reflectionMethod->isGenerator();
    }

    public function isVariadic(): bool
    {
        return $this->reflectionMethod->isVariadic();
    }

    /**
     * To string
     *
     * @link  https://php.net/manual/en/reflectionfunctionabstract.tostring.php
     * @since 5.0
     */
    public function __toString()
    {
        return $this->reflectionMethod->__toString();
    }
}


<?php
/**
 * Annotation
 *
 * @package     Chrisguitarguy\Annotation
 * @copyright   Christopher Davis <http://christopherdavis.me>
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\Annotation;

/**
 * The default token stream.
 *
 * @since   0.1
 * @author  Christopher Davis <http://christopherdavis.me>
 */
class TokenStream implements TokenStreamInterface
{
    /**
     * The array of tokens returned from the lexer.
     *
     * @since   0.1
     * @access  protected
     * @var     Token[]
     */
    protected $stream = array();

    /**
     * Our current position in the stream.
     *
     * @since   0.1
     * @access  protected
     * @var     int
     */
    protected $position = 0;

    /**
     * Constructor. Set up our array of tokens.
     *
     * @since   0.1
     * @access  public
     * @param   array $stream
     * @return  void
     */
    public function __construct(array $stream)
    {
        $this->stream = $stream;
    }

    /** Iterator **************************************************************/

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->position = 0;
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        return $this->stream[$this->position];
    }

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

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->position++;
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return isset($this->stream[$this->position]);
    }

    /** Countable *************************************************************/

    public function count()
    {
        return count($this->stream);
    }

    /** TokenStreamInterface **************************************************/

    /**
     * {@inheritdoc}
     */
    public function at($pos)
    {
        if (!isset($this->stream[$pos])) {
            throw new \InvalidArgumentException(sprintf('Position "%d" is invalid', $pos));
        }

        return $this->stream[$pos];
    }

    /**
     * {@inheritdoc}
     */
    public function peek($distance=1)
    {
        if (isset($this->stream[$this->position + $distance])) {
            return $this->stream[$this->position + $distance];
        }

        // if we try to peak beyond the end of the stream return the last token
        return $this->stream[count($this->stream) - 1];
    }

    /**
     * {@inheritdoc}
     */
    public function skipUntil($type)
    {
        $found = false;
        while ($this->valid()) {
            if ($this->current()->test($type)) {
                $found = true;
                break;
            }

            $this->next();
        }

        return $found;
    }

    /**
     * {@inheritdoc}
     */
    public function expect($type)
    {
        if (!$this->valid() || !$this->current()->test($type)) {
            throw new \UnexpectedValueException(sprintf(
                'Exepcted token with the type "%s", got "%s" with value "%s"',
                implode('|', (array)$type),
                $this->valid() ? $this->current()->name : 'T_ENDOFSTREAM',
                $this->valid() ? $this->current()->value : 'null'
            ));
        }
    }
}


<?php
/**
 * @package SugiPHP.Auth
 * @author  Plamen Popov <tzappa@gmail.com>
 * @license http://opensource.org/licenses/mit-license.php (MIT License)
 */

namespace SugiPHP\Auth;

class HOTPSecret
{
    const FORMAT_RAW    = "raw";
    const FORMAT_HEX    = "hex";
    const FORMAT_BASE32 = "base32";

    protected $secret;

    /**
     * HOTP Secret constructor.
     *
     * @param string $secret (optional) The secret token in format specified in the second parameter
     * @param string $format (optional) The format of the secret token - defaults to raw format
     */
    public function __construct($secret = null, $format = self::FORMAT_RAW)
    {
        if ($secret !== null) {
            $this->setSecret($secret, $format);
        }
    }

    public function __toString()
    {
        return (string) $this->getSecret();
    }

    /**
     * Sets a secret token.
     *
     * @param string $secret The secret token in format specified in the second parameter
     * @param [type] $format (optional) The format of the secret token - defaults to raw format
     */
    public function setSecret($secret, $format = self::FORMAT_RAW)
    {
        if ($format == static::FORMAT_HEX) {
            $secret = hex2bin($secret);
        } elseif ($format == static::FORMAT_BASE32) {
            $secret = $this->base32decode($secret);
        }

        $this->secret = $secret;
    }

    /**
     * Returns previously set secret token
     *
     * @return string
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * Decodes base32 encoded string.
     * @see SugiPHP\Encode\Base32::decode()
     *
     * @param  string $data
     * @return string
     */
    protected function base32decode($data)
    {
        $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

        // stringify
        $data = (string) $data;
        if ($data === "") {
            return "";
        }
        // using only uppercase letters
        $data = strtoupper($data);
        // removing trailing "="
        $data = rtrim($data, "=");
        // removing everything that is not part of the alphabet
        $data = preg_replace("~[^{$alphabet}]~", "", $data);

        $binary = "";
        foreach (str_split($data) as $char) {
            $binary .= str_pad(decbin(strpos($alphabet, $char)), 5, 0, STR_PAD_LEFT);
        }
        $binary = substr($binary, 0, (floor(strlen($binary) / 8) * 8));

        $result = "";
        foreach (str_split($binary, 8) as $chunk) {
            $chunk = str_pad($chunk, 8, 0, STR_PAD_RIGHT);
            $result .= chr(bindec($chunk));
        }

        return $result;
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

/**
 * Pomocna trida pro cisla
 *
 * @author Attreid <attreid@gmail.com>
 */
class Number extends Lang
{

	/**
	 * Vrati cislo v binarni velikosti
	 * @param float|int $number
	 * @return int
	 */
	private static function getBinary(float $number): int
	{
		$num = 2;
		if ($number < $num) {
			return 0;
		}
		$result = $num;
		while (true) {
			$num *= 2;
			if ($number < $num) {
				return $result;
			}
			$result = $num;
		}
		return 0;
	}

	/**
	 * Vrati zformatovane cislo
	 * @param float $number
	 * @param int $decimal
	 * @return string
	 */
	public static function getNumber(float $number, int $decimal = 2): string
	{
		if (floor($number) == $number) {
			$decimal = 0;
		}

		switch (self::$locale) {
			default:
			case 'cs':
			case 'sk':
			case 'de':
			case 'pl':
				return number_format($number, $decimal, ',', ' ');
			case 'en':
				return number_format($number, $decimal);
		}
	}

	/**
	 * Procenta
	 * @param float $number
	 * @param float $total
	 * @param int $decimal
	 * @return string
	 */
	public static function percent(float $number, float $total, int $decimal = 2): string
	{
		return self::getNumber($number / $total * 100, $decimal) . '%';
	}

	/**
	 * Frekvence
	 * @param float $number
	 * @return string
	 */
	public static function frequency(float $number): string
	{
		if ($number > 1000000000) {
			return self::getNumber($number / 1000000000, 2) . ' GHz';
		} elseif ($number > 1000000) {
			return self::getNumber($number / 1000000, 0) . ' MHz';
		} elseif ($number > 1000) {
			return self::getNumber($number / 1000, 0) . ' KHz';
		} else {
			return self::getNumber($number, 0) . ' Hz';
		}
	}

	/**
	 * Velikost souboru
	 * @param float $number
	 * @param int $decimal
	 * @param bool $binary
	 * @return string
	 */
	public static function size(float $number, int $decimal = 2, bool $binary = false): string
	{
		if ($number > 1024 * 1024 * 1024) {
			if ($binary) {
				$number = self::getBinary($number / (1024 * 1024)) / 1024;
			} else {
				$number = $number / (1024 * 1024 * 1024);
			}
			return self::getNumber($number, $decimal) . ' GB';
		} elseif ($number > 1024 * 1024) {
			$number /= 1024 * 1024;
			if ($binary) {
				$number = self::getBinary($number);
			}
			return self::getNumber($number, $decimal) . ' MB';
		} elseif ($number > 1024) {
			$number /= 1024;
			if ($binary) {
				$number = self::getBinary($number);
			}
			return self::getNumber($number, $decimal) . ' KB';
		} else {
			if ($binary) {
				$number = self::getBinary($number);
			}
			return self::getNumber($number, $decimal) . ' B';
		}
	}

}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace DoctrineModule\Service;

use Doctrine\Common\Cache\CacheProvider;
use RuntimeException;
use Doctrine\Common\Cache\MemcacheCache;
use Doctrine\Common\Cache\MemcachedCache;
use Doctrine\Common\Cache\RedisCache;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Cache ServiceManager factory
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @author  Kyle Spraggs <theman@spiffyjr.me>
 */
class CacheFactory extends AbstractFactory
{
    /**
     * {@inheritDoc}
     *
     * @return \Doctrine\Common\Cache\Cache
     *
     * @throws RuntimeException
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @var $options \DoctrineModule\Options\Cache */
        $options = $this->getOptions($serviceLocator, 'cache');
        $class   = $options->getClass();

        if (!$class) {
            throw new RuntimeException('Cache must have a class name to instantiate');
        }

        $instance = $options->getInstance();

        if (is_string($instance) && $serviceLocator->has($instance)) {
            $instance = $serviceLocator->get($instance);
        }

        switch ($this->name) {
            case 'filesystem':
                $cache = new $class($options->getDirectory());
                break;

            case 'predis':
                $cache = new $class($instance);
                break;

            default:
                $cache = new $class;
        }

        if ($cache instanceof MemcacheCache) {
            /* @var $cache MemcacheCache */
            $cache->setMemcache($instance);
        } elseif ($cache instanceof MemcachedCache) {
            /* @var $cache MemcachedCache */
            $cache->setMemcached($instance);
        } elseif ($cache instanceof RedisCache) {
            /* @var $cache RedisCache */
            $cache->setRedis($instance);
        }

        if ($cache instanceof CacheProvider && ($namespace = $options->getNamespace())) {
            $cache->setNamespace($namespace);
        }

        return $cache;
    }

    /**
     * {@inheritDoc}
     */
    public function getOptionsClass()
    {
        return 'DoctrineModule\Options\Cache';
    }
}


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.data
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizDataSql.php 3858 2011-04-23 01:14:49Z jixian2003 $
 */

namespace Openbizx\Data;

/**
 * Class << BizDataSql >> is the class to constrcut SQL statement for BizDataObj
 *
 * @package openbiz.bin.data
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 */
class BizDataSql
{
    protected $_tableColumns = null;
    protected $_tableJoins = null;
    protected $_joinAliasList = array();
    protected $_tableAliasList = array();
    protected $_sqlWhere = null;
    protected $_orderBy = null;
    protected $_otherSQL = null;
    protected $_aliasIndex = 0;
    protected $_mainTable;
	public $hasJoinCondition = false;

    public function __construct()
    {
    }

	public function isfresh()
	{
		return $this->_mainTable ? false : true;
	}

    /**
     * Add main table in the sql statement T0 alias
     *
     * @param string $mainTable main table name
     * @return void
     **/
    public function addMainTable($mainTable)
    {
        $this->_mainTable = "$mainTable";
        $this->_tableJoins = " `$mainTable` T0 ";
    }

    /**
     * Add a join table in the sql statement Ti alias
     * <pre>
     *   SELECT T1.col, T2.col
     *   FROM table1 T1
     *       INNER JOIN table2 T2 ON T1.col1=T2.col1
     *       LEFT JOIN  table3 T3 ON T1.col1=T3.col1
     *   WHERE
     * </pre>
     *
     * @param TableJoin $tableJoin table join object
     * @return void
     **/
    public function addJoinTable($tableJoin, $sqlHelper=null)
    {
        $table = $tableJoin->table;
        $joinType = $tableJoin->joinType;
        $column = $tableJoin->column;
        $joinRef = $tableJoin->joinRef;
        $columnRef = $tableJoin->columnRef;
		$joinCondition = $tableJoin->joinCondition;

        $alias = "T".(count($this->_joinAliasList)+1);   // start with T1, T2
        $this->_joinAliasList[$tableJoin->objectName] = $alias;
        $this->_tableAliasList[$table] = $alias;
        $aliasRef = $this->getJoinAlias($joinRef);
        $this->_tableJoins .= " $joinType `$table` $alias ON $alias.$column = $aliasRef.$columnRef ";
		if (!empty($joinCondition)) {
			$this->_tableJoins .= " AND $joinCondition";
			$this->hasJoinCondition = true;
		}
    }

	public function getTableJoinStm() { return $this->_tableJoins; }

	public function setTableJoinStm($tableJoinStm) { return $this->_tableJoins = $tableJoinStm; }

    /**
     * Add a join table and cloumn in the sql statement
     *
     * @param string $join table join name
     * @param string $column column name
     * @return void
     **/
    public function addTableColumn($join, $column, $alias=null)
    {
        $tcol = $this->getTableColumn($join, $column);
        if ($alias) $tcol .= " AS ".$alias;
        if (!$this->_tableColumns)
            $this->_tableColumns = $tcol;
        else
            $this->_tableColumns .= ", ".$tcol;
    }

    /**
     * Add SQL expression in the sql statement
     * sqlExpr has format of "...join1.column1, ... join2.column2...". Replace join with alias
     *
     * @param string $sqlExpr sql expression
     * @param string $alias sql alias
     * @return void
     **/
    public function addSqlExpression($sqlExpr, $alias=null)
    {
        if ($alias)
            $sqlExpr .= ' AS '.$alias;
        if (!$this->_tableColumns)
            $this->_tableColumns = $sqlExpr;
        else
            $this->_tableColumns .= ", ".$sqlExpr;
    }

    /**
     * Get join table alias
     *
     * @param string $join name of join
     * @return string join table alias
     */
    public function getJoinAlias($join)
    {
        if (!$join) // main table, no join
            return "T0";
        else
            return $this->_joinAliasList[$join];
    }

    /**
     * Get table column, combine a table with a column.
     *
     * @param string $join join name
     * @param string $col column
     * @return string table column combination string
     */
    public function getTableColumn($join, $col)
    {
        // check the function format on $col
        $alias = $this->getJoinAlias($join);
        return "$alias.`$col`";
    }

    /**
     * Reset SQL to be empty
     *
     * @return avoid
     */
    public function resetSQL()
    {
        $this->_sqlWhere = null;
        $this->_orderBy = null;
        $this->_otherSQL = null;
    }

    /**
     * Add the where clause (search rule) into the SQL statement
     *
     * @param string $sqlWhere SQL WHERE clause
     * @return void
     */
    public function addSqlWhere($sqlWhere)
    {
        if ($sqlWhere == null)
            return;
        if ($this->_sqlWhere == null)
        {
            $this->_sqlWhere = $sqlWhere;
        }
        elseif (strpos($this->_sqlWhere, $sqlWhere) === false)
        {
            $this->_sqlWhere .= " AND " . $sqlWhere;
        }
    }

    /**
     * Add order by clause
     *
     * @param string $orderBy SQL ORDER BY clause
     * @return void
     **/
    public function addOrderBy($orderBy)
    {
        if ($orderBy == null)
            return;
        if ($this->_orderBy == null)
        {
            $this->_orderBy = $orderBy;
        }
        elseif (strpos($this->_orderBy, $orderBy) === false)
        {
            $this->_orderBy .= " AND " . $orderBy;
        }
    }

    /**
     * Add other SQL clause
     *
     * @param string $otherSQL additional SQL statment
     * @return void
     **/
    public function addOtherSQL($otherSQL)
    {
        if ($otherSQL == null)
            return;
        if ($this->_otherSQL == null)
        {
            $this->_otherSQL = $otherSQL;
        }
        elseif (strpos($this->_otherSQL, $otherSQL) === false)
        {
            $this->_otherSQL .= " AND " . $otherSQL;
        }
    }

    /**
     * Add association in the SQL
     *
     * @param array $assoc additional SQL statment
     * @return void
     **/
    public function addAssociation($assoc)
    {
        $where = "";
        if ($assoc["Relationship"] == "1-M" || $assoc["Relationship"] == "M-1" || $assoc["Relationship"] == "1-1")
        {
            // assc table should same as maintable
            if ($assoc["Table"] != $this->_mainTable) return;
            // add table to join table
            $mytable_col = $this->getTableColumn(null, $assoc["Column"]);
            // construct table.column = 'field value'
            $where = $mytable_col." = '".$assoc["FieldRefVal"]."'";

            $mytable_col2 = $this->getTableColumn(null, $assoc["Column2"]);
            if($assoc["Column2"]){
            	$where .= " AND ".$mytable_col2." = '".$assoc["FieldRefVal2"]."'";
            }
            $mytable_cond_col = $this->getTableColumn(null, $assoc["CondColumn"]);
            if($assoc["CondColumn"]){
            	$where .= " AND $mytable_cond_col ='".$assoc["CondValue"]."' ";
            }
        	if($assoc["Condition"]){
            	$where .= " AND ".$assoc["Condition"]." ";
            }
        }
        elseif ($assoc["Relationship"] == "M-M" || $assoc["Relationship"] == "Self-Self")
        {
            // ... INNER JOIN xtable TX ON TX.column2 = T0.column
            // WHERE ... Tx.column1 = 'PrtTableColumnValue'
            $mytable_col = $this->getTableColumn(null, $assoc["Column"]);   // this table's alias.column
            $xtable = $assoc["XTable"];    // xtable's name
            $column1 = $assoc["XColumn1"]; // xtable column1
            $column2 = $assoc["XColumn2"]; // xtable column2
            $xalias = "TX";
            if (isset($this->_tableAliasList[$xtable]))
                $xalias = $this->_tableAliasList[$xtable];

            // add a table join for the xtable if such join of the table is not there before (note: may report error if has same join).
            //if (strpos($this->tableJoins, "JOIN $xtable") === false)
            if (!isset($this->_tableAliasList[$xtable]))
            {
                $this->_tableJoins .= " INNER JOIN `$xtable` $xalias ON $xalias.$column2 = $mytable_col ";
                $this->_tableAliasList[$xtable] = $xalias;
            }

            // add a new where condition
            if($assoc["Relationship"] == "Self-Self")
            {
            	$columnId = $this->getTableColumn("", $assoc["ParentRecordIdColumn"]);
            	$where = "($xalias.$column1 = '".$assoc["FieldRefVal"]."' OR $xalias.$column2 = '".$assoc["FieldRefVal"]."' ) AND $columnId != '".$assoc["FieldRefVal"]."'";
            	$this->_tableJoins .=  " OR $xalias.$column1 = $mytable_col ";
            }else{
            	$where = "$xalias.$column1 = '".$assoc["FieldRefVal"]."'";
            }
        }

        if (strlen($where) > 1)
            $this->addSqlWhere($where);
    }

    /**
     * Get the SQL statement
     *
     * @return string SQL statement
     */
    public function getSqlStatement()
    {
        $ret = "SELECT " . $this->_tableColumns;
        $ret .= " FROM " . $this->_tableJoins;

        if ($this->_sqlWhere != null)
        {
            $ret .= " WHERE " . $this->_sqlWhere;
        }
        /*
        if ($this->orderBy != null)
        {
            $ret .= " ORDER BY " . $this->orderBy;
	}
        */
        if ($this->_otherSQL != null)
        {
            $ret .= " " . $this->_otherSQL;
        }
        if ($this->_orderBy != null)
        {
            $ret .= " ORDER BY " . $this->_orderBy;
        }
        return $ret;
    }
}
?>


<?php
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.data
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: DataSet.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Data;

use Openbizx\Data\DataRecord;

/**
 * DataSet class is the wrapper class of record array.
 * It is recommmended to be used in data update and deletion.
 *
 * @package openbiz.bin.data
 * @author Rocky Swen
 * @copyright Copyright (c) 2007-2009
 * @access public
 **/
class DataSet implements \Iterator, \ArrayAccess, \Countable
{
    /**
     * Record in array format
     *
     * @var array
     */
    protected $varValue = array();

    /**
     * Reference of {@link BizDataObj}
     *
     * @var BizDataObj
     */
    protected $bizDataObj = null;

    /**
     * Initialize DataSet
     *
     * @param array $recArray record array.
     * @param BizDataObj $bizObj BizDataObj instance
     * @return void
     */
    public function __construct($bizObj)
    {
        $this->bizDataObj = $bizObj;
    }

    // Iterator methods BEGIN---------

    /**
     * Get item value of array
     *
     * @param mixed $key
     * @return mixed
     */
    public function get($key)
    {
        if (isset($this->varValue[$key])) {
            return new DataRecord($this->varValue[$key], $this->bizDataObj);
        } else {
            return NULL;
        }
    }

    /**
     * Set item value of array
     *
     * @param mixed $key
     * @param mixed $val
     */
    public function set($key, $val)
    {
        $this->varValue[$key] = $val;

    }

    /**
     * Rewind, Send pointer to start of list
     *
     * @return void
     */
    public function rewind()
    {
        reset($this->varValue);
    }

    /**
     * Return element at current pointer position
     *
     * @return mixed
     */
    public function current()
    {
        return current($this->varValue);
    }

    /**
     * Return current key (i.e., pointer value)
     *
     * @return mixed
     */
    public function key()
    {
        return key($this->varValue);
    }

    /**
     * Return element at current pointer and advance pointer
     *
     * @return mixed
     */
    public function next()
    {
        return next($this->varValue);
    }

    /**
     * Confirm that there is an element at the current pointer position
     *
     * @return boolean
     */
    public function valid()
    {
        return $this->current() !== false;
    }

    // ArrayAccess methods

    /**
     * Check is offset value (by key) exist?
     *
     * @param mixed $key
     * @return mixed
     */
    public function offsetExists($key)
    {
        return isset($this->varValue[$key]);
    }

    /**
     * Get value of offset (by key)
     *
     * @param mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->get($key);
    }

    /**
     * Set value of offset by key
     *
     * @param mixed $key
     * @param mixed $value
     */
    public function offsetSet($key, $value)
    {
        $this->set($key, $value);
    }

    /**
     * Unset element by key
     *
     * @param mixed $key key of element
     */
    public function offsetUnset($key)
    {
        unset($this->varValue[$key]);
    }

    public function count()
    {
        return count($this->varValue);
    }

    /**
     * Return record in array
     *
     * @return array record array
     */
    public function toArray()
    {
        return $this->varValue;
    }

    /**
     * Get reference object with given object name
     *
     * @param string $objName name of the object reference
     * @return obejct the instance of reference object
     */
    public function getRefObject($objName)
    {
        return $this->bizDataObj->getRefObject($objName);
    }

}
?>


<?php

namespace Interpro\QS\Db;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Taxonomy\Fields\Field;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Extractor\Contracts\Db\Joiner;
use Interpro\Extractor\Contracts\Db\JoinMediator;
use Interpro\Extractor\Db\QueryBuilder;
use Interpro\QS\Exception\QSException;

class QSJoiner implements Joiner
{
    private $joinMediator;

    public function __construct(JoinMediator $joinMediator)
    {
        $this->joinMediator = $joinMediator;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'qs';
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\Field $field
     * @param array $join_array
     *
     * @return mixed
     */
    public function joinByField(Field $field, $join_array)
    {
        $fieldType = $field->getFieldType();
        $entity_name = $fieldType->getName();
        $field_name = $field->getName();

        $rank_name = $fieldType->getRank();

        if($rank_name === TypeRank::BLOCK)
        {
            $model_table = 'blocks';
        }
        elseif($rank_name === TypeRank::GROUP)
        {
            $model_table = 'groups';
        }
        else
        {
            throw new QSException('Не корректный ранг типа '.$entity_name.': '.$rank_name);
        }

        $join_q = new QueryBuilder(DB::table('refs'));
        $join_q->select(['refs.entity_name', 'refs.entity_id']);
        $join_q->whereRaw('refs.ref_entity_name = "'.$entity_name.'"');
        $join_q->whereRaw('refs.name = "'.$field_name.'"');

        //Если в продолжения пути нет, то $field_name и есть нужное поле
        foreach($join_array['sub_levels'] as $levelx_field_name => $sub_array)
        {
            if($levelx_field_name === 'id')
            {
                $join_q->addSelect('ref_entity_id as '.$sub_array['full_field_names'][0]);//Законцовка - в массиве только одно поле x_..x_id
            }
            else
            {
                if($levelx_field_name === 'slug' or $levelx_field_name === 'title' or $levelx_field_name === 'sorter' or $levelx_field_name === 'predefined' or $levelx_field_name === 'show' or $levelx_field_name === 'name')//Собственное поле
                {
                    $sub_q = new QueryBuilder(DB::table($model_table));

                    $sub_q->select([$model_table.'.name as entity_name', $model_table.'.id as entity_id', $model_table.'.'.$levelx_field_name.' as '.$join_array['full_field_names'][0]]);//Законцовка - в массиве только одно поле x_..x_id
                    $sub_q->whereRaw($model_table.'.name = "'.$entity_name.'"');
                }
                else//Присоединяемое поле
                {
                    $nextField = $fieldType->getField($levelx_field_name);
                    $sub_q = $this->joinMediator->externalJoin($nextField, $sub_array);
                }

                $join_q->leftJoin(DB::raw('('.$sub_q->toSql().') AS '.$levelx_field_name.'_table'), function($join) use ($levelx_field_name)
                {
                    $join->on('refs.ref_entity_name', '=', $levelx_field_name.'_table.entity_name');
                    $join->on('refs.ref_entity_id',   '=', $levelx_field_name.'_table.entity_id');
                });

                foreach($sub_array['full_field_names'] as $full_field_name)
                {
                    $join_q->addSelect($full_field_name);//Из $sub_q пришли поля с именами, добавляем все в текущую выборку
                }
            }
        }

        return $join_q;
    }

}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Definition\Type;

use Innmind\Rest\Client\{
    Definition\Types,
    Definition\Type,
    Exception\DomainException,
    Exception\NormalizationException,
    Exception\DenormalizationException,
};
use Innmind\Immutable\{
    Str,
    SetInterface,
    Set,
};

final class SetType implements Type
{
    const PATTERN = '~set<(?<inner>.+)>~';

    private $inner;
    private $denormalized;

    public function __construct(Type $inner)
    {
        $this->inner = $inner;
        $this->denormalized = new Set(
            $inner instanceof DateType ?
                \DateTimeImmutable::class : (string) $inner
        );
    }

    public static function fromString(string $type, Types $build): Type
    {
        $type = new Str($type);

        if (!$type->matches(self::PATTERN)) {
            throw new DomainException;
        }

        return new self(
            $build(
                (string) $type
                    ->capture(self::PATTERN)
                    ->get('inner')
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function normalize($data)
    {
        if (!$data instanceof SetInterface) {
            throw new NormalizationException(
                'The value must be an instance of Innmind\Immutable\SetInterface'
            );
        }

        return $data->reduce(
            [],
            function(array $values, $value): array {
                $values[] = $this->inner->normalize($value);

                return $values;
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function denormalize($data)
    {
        if (!\is_array($data)) {
            throw new DenormalizationException('The value must be an array');
        }

        $set = $this->denormalized;

        try {
            foreach ($data as $value) {
                $set = $set->add(
                    $this->inner->denormalize($value)
                );
            }

            return $set;
        } catch (\Throwable $e) {
            throw new DenormalizationException('The value must be a valid set');
        }
    }

    public function __toString(): string
    {
        return 'set<'.$this->inner.'>';
    }
}


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace DoctrineModule\Controller;

use Symfony\Component\Console\Application;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ConsoleModel;
use DoctrineModule\Component\Console\Input\RequestInput;

/**
 * Index controller
 *
 * @license MIT
 * @author Aleksandr Sandrovskiy <a.sandrovsky@gmail.com>
 */
class CliController extends AbstractActionController
{
    /**
     * @var \Symfony\Component\Console\Application
     */
    protected $cliApplication;

    /**
     * @param \Symfony\Component\Console\Application $cliApplication
     */
    public function __construct(Application $cliApplication)
    {
        $this->cliApplication = $cliApplication;
    }

    /**
     * Index action - runs the console application
     */
    public function cliAction()
    {
        $exitCode = $this->cliApplication->run(new RequestInput($this->getRequest()));

        if (is_numeric($exitCode)) {
            $model = new ConsoleModel();
            $model->setErrorLevel($exitCode);

            return $model;
        }
    }
}


<?php

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Resource.php 4179 2011-05-26 07:40:53Z rockys $
 */

namespace Openbizx\Helpers;

use Openbizx\Openbizx;
use Openbizx\I18n\I18n;

//use XMLParser;

/**
 * Resource class
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org>
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 * @todo loadMessage(),
 *       getXmlFileWithPath(),
 *       getTplFileWithPath,
 *       getLibFileWithPath
 */
class TemplateHelper
{

    /**
     * Get smarty template
     * @return Smarty smarty object
     */
    public static function getSmartyTemplate()
    {
        $smarty = new \SmartyBC;
        $useTheme = !defined('OPENBIZ_USE_THEME') ? 0 : OPENBIZ_USE_THEME;
        if ($useTheme) {
            $theme = Openbizx::$app->getCurrentTheme();
            $themePath = $theme;    // Openbizx::$app->getConfiguration()->GetThemePath($theme);
            if (is_dir(OPENBIZ_THEME_PATH . "/" . $themePath . "/template")) {
                $templateRoot = OPENBIZ_THEME_PATH . "/" . $themePath . "/template";
            } else {
                $templateRoot = OPENBIZ_THEME_PATH . "/" . $themePath . "/templates";
            }
            $smarty->setTemplateDir($templateRoot);
            $compileDir = defined('OPENBIZ_SMARTY_CPL_PATH') ? OPENBIZ_SMARTY_CPL_PATH . "/" . $themePath : $templateRoot . "/cpl";
            $smarty->setCompileDir($compileDir);
            $smarty->setConfigDir($templateRoot . "/cfg");
            $smarty->config_load('tpl.conf');
        } else {
            if (defined('SMARTY_TPL_PATH')) {
                $smarty->setTemplateDir( SMARTY_TPL_PATH );
            }
            if (defined('OPENBIZ_SMARTY_CPL_PATH')) {
                $smarty->setCompileDir( OPENBIZ_SMARTY_CPL_PATH . "/" . $themePath );
            }
            if (defined('SMARTY_CFG_PATH')) {
                $smarty->setConfigDir( SMARTY_CFG_PATH );
            }
        }

        if (!is_dir($smarty->compile_dir)) {
            mkdir($smarty->compile_dir, 0777);
        }

        // load the config file which has the images and css url defined
        $smarty->assign('app_url', OPENBIZ_APP_URL);
        $smarty->assign('app_index', OPENBIZ_APP_INDEX_URL);
        $smarty->assign('js_url', OPENBIZ_JS_URL);
        $smarty->assign('css_url', OPENBIZ_THEME_URL . "/" . $theme . "/css");
        $smarty->assign('resource_url', OPENBIZ_RESOURCE_URL);
        $smarty->assign('resource_php', OPENBIZ_RESOURCE_PHP);
        $smarty->assign('theme_js_url', OPENBIZ_THEME_URL . "/" . $theme . "/js");
        $smarty->assign('theme_url', OPENBIZ_THEME_URL . "/" . $theme);
        $smarty->assign('image_url', OPENBIZ_THEME_URL . "/" . $theme . "/images");
        $smarty->assign('lang', strtolower(I18n::getCurrentLangCode()));
        $smarty->assign('lang_name', I18n::getCurrentLangCode());

        return $smarty;
    }

    /**
     * Get \Zend Template
     * @return \Zend_View zend view template object
     */
    public static function getZendTemplate()
    {
        $view = new \Zend_View();
        if (defined('SMARTY_TPL_PATH')) {
            $view->setScriptPath(SMARTY_TPL_PATH);
        }

        $theme = Openbizx::$app->getCurrentTheme();

        // load the config file which has the images and css url defined
        $view->app_url = OPENBIZ_APP_URL;
        $view->app_index = OPENBIZ_APP_INDEX_URL;
        $view->js_url = OPENBIZ_JS_URL;
        $view->css_url = OPENBIZ_THEME_URL . "/" . $theme . "/css";
        $view->resource_url = OPENBIZ_RESOURCE_URL;
        $view->theme_js_url = OPENBIZ_THEME_URL . "/" . $theme . "/js";
        $view->theme_url = OPENBIZ_THEME_URL . "/" . $theme;
        $view->image_url = OPENBIZ_THEME_URL . "/" . $theme . "/images";
        $view->lang = strtolower(I18n::getCurrentLangCode());

        return $view;
    }

    /**
     * Get openbiz template file path by searching modules/package, /templates
     *
     * @param string $className
     * @return string php library file path
     * */
    public static function getTplFileWithPath($templateFile, $packageName)
    {
        //for not changing a lot things, the best injection point is added theme support here.
        $theme = Openbizx::$app->getCurrentTheme();
        $themePath = $theme;    // Openbizx::$app->getConfiguration()->GetThemePath($theme);
        if ($themePath) {
            $templateRoot = OPENBIZ_THEME_PATH . "/" . $themePath . "/template";
        } else {
            $templateRoot = SMARTY_TPL_PATH;
        }

        $names = explode(".", $packageName);
        if (count($names) > 0) {
            $moduleName = $names[0];
        }
        $packagePath = str_replace('.', '/', $packageName);
        // check the leading char '@'
        $checkExtModule = true;
        if (strpos($packagePath, '@') === 0) {
            $packagePath = substr($packagePath, 1);
            $checkExtModule = false;
        }

        $searchTpls = array(
            Openbizx::$app->getModulePath() . "/$packagePath/template/$templateFile",
            dirname(Openbizx::$app->getModulePath() . "/$packagePath") . "/template/$templateFile",
            Openbizx::$app->getModulePath() . "/$moduleName/template/$templateFile",
            //Openbizx::$app->getModulePath()."/common/template/$templateFile",
            $templateRoot . "/$templateFile"
        );
        if ($checkExtModule && defined('MODULE_EX_PATH')) {
            array_unshift($searchTpls, MODULE_EX_PATH . "/$packagePath/template/$templateFile");
        }

        // device
        if (defined('OPENBIZ_CLIENT_DEVICE')) {
            array_unshift($searchTpls, Openbizx::$app->getModulePath() . "/$moduleName/template/" . OPENBIZ_CLIENT_DEVICE . "/$templateFile");
        }

        foreach ($searchTpls as $tplFile) {
            if (file_exists($tplFile)) {
                return $tplFile;
            }
        }
        $errmsg = MessageHelper::getMessage("UNABLE_TO_LOCATE_TEMPLATE_FILE", array($templateFile));
        trigger_error($errmsg, E_USER_ERROR);
        return null;
    }

    /**
     * Get list of default template location
     * @return array
     */
    private static function getDefaultTemplateLocations()
    {
        return array(
            Openbizx::$app->getModulePath() . "/$packagePath/template/$templateFile",
            dirname(Openbizx::$app->getModulePath() . "/$packagePath") . "/template/$templateFile",
            Openbizx::$app->getModulePath() . "/$moduleName/template/$templateFile",
            //Openbizx::$app->getModulePath()."/common/template/$templateFile",
            $templateRoot . "/$templateFile"
        );
    }

}


<?php

namespace Interpro\QuickStorage\Laravel;

use Illuminate\Container\Container as App;
use Illuminate\Support\Facades\Log;
use Interpro\QuickStorage\Concept\Exception\BuildQueryException;
use Interpro\QuickStorage\Concept\Param\GroupParam;
use Interpro\QuickStorage\Concept\QSource as QSourceInterface;
use Interpro\QuickStorage\Concept\Sorting\GroupSortingSet;
use Interpro\QuickStorage\Concept\Specification\GroupSpecificationSet;
use Interpro\QuickStorage\Concept\StorageStructure as StorageStructureInterface;
use Illuminate\Support\Facades\DB;

class QSource implements QSourceInterface
{
    private $storageStruct;
    private $app;
    private $groupSortingSet;
    private $groupSpecificationSet;
    private $groupParam;

    public function __construct(StorageStructureInterface $storageStruct, App $app, GroupSortingSet $groupSortingSet, GroupSpecificationSet $groupSpecificationSet, GroupParam $groupParam)
    {
        $this->app           = $app;
        $this->storageStruct = $storageStruct;
        $this->groupSortingSet = $groupSortingSet;
        $this->groupSpecificationSet = $groupSpecificationSet;
        $this->groupParam = $groupParam;
    }

    private function select_field_for_block($query, $block_name, $field_name)
    {
        $model = $this->app->make($this->storageStruct->getModelNameByFieldBlock($block_name, $field_name));

        $table_q = $model->selectRaw('block_name as '.$field_name.'_block, value as '.$field_name)
            ->whereRaw('name = "'.$field_name.'"')
            ->whereRaw('group_id = 0');

        $query->leftJoin(DB::raw('('.$table_q->toSql().') AS '.$field_name.'_table'), function($join) use ($field_name)
        {
            $join->on('blocks.name', '=', $field_name.'_table.'.$field_name.'_block');
        });
    }

    private function select_field_for_group($query, $block_name, $group_name, $field_name)
    {
        $model = $this->app->make($this->storageStruct->getModelNameByFieldGroup($block_name, $group_name, $field_name));

        $table_q = $model->selectRaw('group_id as '.$field_name.'_group_id, value as '.$field_name)
            ->whereRaw('name = "'.$field_name.'"');

        $query->leftJoin(DB::raw('('.$table_q->toSql().') AS '.$field_name.'_table'), function($join) use ($field_name)
        {
            $join->on('groups.id', '=', $field_name.'_table.'.$field_name.'_group_id');
        });
    }

    /**
     * @param string $block_name
     *
     * @return array
     */
    public function blockQuery($block_name)
    {
        $model_block = $this->app->make('Interpro\QuickStorage\Laravel\Model\Block');

        $block_q = $model_block->query();

        $block_q->where('name', '=', $block_name);

        $fields = $this->storageStruct->getBlockFieldsFlat($block_name);

        $fields_except = ['name', 'title', 'show'];

        foreach($fields as $field_name)
        {
            if(!in_array($field_name, $fields_except))
            {
                $this->select_field_for_block($block_q, $block_name, $field_name);
            }
        }

        $collection = $block_q->get($fields);

        if(!$collection->isEmpty())
        {
            $block_obj = $collection->first();

            return $block_obj->toArray();

        }else{

            throw new BuildQueryException('Блок '.$block_name.' не найден в базе данных.');
        }
    }

    /**
     * @param string $block_name
     * @param string $group_name
     *
     * @return array
     */
    public function groupQuery($block_name, $group_name)
    {
        $model_group = $this->app->make('Interpro\QuickStorage\Laravel\Model\Group');

        $group_q = $model_group->query();

        $group_q->where('group_name', '=', $group_name);

        $fields = $this->storageStruct->getGroupFieldsFlat($block_name, $group_name);

        $fields_except = ['id', 'owner_id', 'group_name', 'group_owner_name', 'block_name', 'title', 'slug', 'sorter', 'show'];

        foreach($fields as $field_name)
        {
            if(!in_array($field_name, $fields_except))
            {
                $this->select_field_for_group($group_q, $block_name, $group_name, $field_name);
            }
        }

        //Условия
        $this->groupSpecificationSet->setCurrentGroup($group_name);
        foreach($this->groupSpecificationSet as $spec)
        {
            $spec->asScope($group_q);
        }

        //Сортировка
        $this->groupSortingSet->setCurrentGroup($group_name);
        foreach($this->groupSortingSet as $spec)
        {
            $spec->apply($group_q);
        }

        //Применить параметры
        $this->groupParam->apply($group_name, $group_q);

        return $group_q->get($fields)->toArray();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     *
     * @return array
     */
    public function groupCount($block_name, $group_name)
    {
        $model_group = $this->app->make('Interpro\QuickStorage\Laravel\Model\Group');

        $group_q = $model_group->query();

        $group_q->where('group_name', '=', $group_name);

        $fields = $this->storageStruct->getGroupFieldsFlat($block_name, $group_name);

        //Условия могут быть на любое из полей, поэтому подсоединим все
        $fields_except = ['id', 'owner_id', 'group_name', 'group_owner_name', 'block_name', 'title', 'slug', 'sorter', 'show'];

        foreach($fields as $field_name)
        {
            if(!in_array($field_name, $fields_except))
            {
                $this->select_field_for_group($group_q, $block_name, $group_name, $field_name);
            }
        }

        //Условия
        $this->groupSpecificationSet->setCurrentGroup($group_name);
        foreach($this->groupSpecificationSet as $spec)
        {
            $spec->asScope($group_q);
        }

        return $group_q->count();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param int $group_id
     *
     * @return array
     */
    public function groupItemQuery($block_name, $group_name, $group_id)
    {
        $model_group = $this->app->make('Interpro\QuickStorage\Laravel\Model\Group');

        $group_q = $model_group->query();

        $group_q->where('block_name', '=', $block_name);
        $group_q->where('group_name', '=', $group_name);
        $group_q->where('id', '=', $group_id);

        $fields = $this->storageStruct->getGroupFieldsFlat($block_name, $group_name);

        $fields_except = ['id', 'owner_id', 'group_name', 'group_owner_name', 'block_name', 'title', 'slug', 'sorter', 'show'];

        foreach($fields as $field_name)
        {
            if(!in_array($field_name, $fields_except))
            {
                $this->select_field_for_group($group_q, $block_name, $group_name, $field_name);
            }
        }

        $collection = $group_q->get($fields);

        if(!$collection->isEmpty())
        {
            $item_obj = $collection->first();

            return $item_obj->toArray();

        }else{

            throw new BuildQueryException('Данные элемента группы ('.$group_name.'-'.$group_id.') не найдены в базе.');
        }
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param string $slug
     *
     * @return array
     */
    public function groupItemBySlugQuery($block_name, $group_name, $slug)
    {
        $model_group = $this->app->make('Interpro\QuickStorage\Laravel\Model\Group');

        $group_q = $model_group->query();

        $group_q->where('block_name', '=', $block_name);
        $group_q->where('group_name', '=', $group_name);
        $group_q->where('slug', '=', $slug);

        $fields = $this->storageStruct->getGroupFieldsFlat($block_name, $group_name);

        $fields_except = ['id', 'owner_id', 'group_name', 'group_owner_name', 'block_name', 'title', 'slug', 'sorter', 'show'];

        foreach($fields as $field_name)
        {
            if(!in_array($field_name, $fields_except))
            {
                $this->select_field_for_group($group_q, $block_name, $group_name, $field_name);
            }
        }

        $collection = $group_q->get($fields);

        if(!$collection->isEmpty())
        {
            $item_obj = $collection->first();

            return $item_obj->toArray();

        }else{

            throw new BuildQueryException('Данные элемента группы по слагу ('.$group_name.'-'.$slug.') не найдены в базе.');
        }
    }

    /**
     * @param string $block_name
     * @param string $image_name
     *
     * @return array
     */
    public function oneImageQueryForBlock($block_name, $image_name)
    {
        $model_image = $this->app->make('Interpro\QuickStorage\Laravel\Model\Imageitem');

        $image_q = $model_image->query();

        $image_q->where('block_name', '=', $block_name);
        $image_q->where('name', '=', $image_name);

        $collection = $image_q->get();

        if(!$collection->isEmpty())
        {
            $block_obj = $collection->first();

            return $block_obj->toArray();

        }else{

            throw new BuildQueryException('Данные картинки '.$image_name.' блока '.$block_name.' не найдены в базе.');
        }
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param int $group_id
     * @param string $image_name
     *
     * @return array
     */
    public function oneImageQueryForGroup($block_name, $group_name, $group_id, $image_name='')
    {
        $model_image = $this->app->make('Interpro\QuickStorage\Laravel\Model\Imageitem');

        $image_q = $model_image->query();

        $image_q->where('block_name', '=', $block_name);
        $image_q->where('group_name', '=', $group_name);
        if($image_name){$image_q->where('name', '=', $image_name);}
        $image_q->where('group_id', '=', $group_id);

        return $image_q->get()->toArray();
    }

    /**
     * @param string $block_name
     *
     * @return array
     */
    public function imageQueryForBlock($block_name)
    {
        $model_image = $this->app->make('Interpro\QuickStorage\Laravel\Model\Imageitem');

        $image_q = $model_image->query();

        $image_q->where('block_name', '=', $block_name);
        $image_q->where('group_id', '=', 0);

        return $image_q->get()->toArray();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     *
     * @return array
     */
    public function imageQueryForGroup($block_name, $group_name)
    {
        $model_image = $this->app->make('Interpro\QuickStorage\Laravel\Model\Imageitem');

        $image_q = $model_image->query();

        $image_q->where('block_name', '=', $block_name);
        $image_q->where('group_name', '=', $group_name);

        return $image_q->get()->toArray();
    }

    //Запросы для кропов картинок
    /**
     * @param string $block_name
     * @param string $image_name
     *
     * @return array
     */
    public function cropQueryForBlock($block_name, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}

        return $crop_q->get()->toArray();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param string $image_name
     *
     * @return array
     */
    public function cropQueryForGroup($block_name, $group_name, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        $crop_q->where('group_name', '=', $group_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}

        return $crop_q->get()->toArray();
    }

    /**
     * @param string $block_name
     * @param string $image_name
     * @param string $crop_name
     *
     * @return array
     */
    public function cropQueryForBlockForCrop($block_name, $crop_name, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}
        $crop_q->where('name', '=', $crop_name);

        $collection = $crop_q->get();

        if(!$collection->isEmpty())
        {
            $_obj = $collection->first();

            return $_obj->toArray();

        }else{

            throw new BuildQueryException('Данные кропа '.$crop_name.' блока '.$block_name.' картинки '.$image_name.' не найдены в базе.');
        }
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param string $image_name
     *
     * @return array
     */
    public function cropQueryForGroupForCrop($block_name, $group_name, $crop_name, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        $crop_q->where('group_name', '=', $group_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}
        $crop_q->where('name', '=', $crop_name);

        return $crop_q->get()->toArray();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param int $group_id
     * @param string $image_name
     * @param string $crop_name
     *
     * @return array
     */
    public function oneCropQueryForGroup($block_name, $group_name, $group_id, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        $crop_q->where('group_name', '=', $group_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}
        $crop_q->where('group_id',   '=', $group_id);

        return $crop_q->get()->toArray();
    }

    /**
     * @param string $block_name
     * @param string $group_name
     * @param int $group_id
     * @param string $image_name
     * @param string $crop_name
     *
     * @return array
     */
    public function oneCropQueryForGroupForCrop($block_name, $group_name, $group_id, $crop_name, $image_name='')
    {
        $model_crop = $this->app->make('Interpro\QuickStorage\Laravel\Model\Cropitem');

        $crop_q = $model_crop->query();

        $crop_q->where('block_name', '=', $block_name);
        $crop_q->where('group_name', '=', $group_name);
        if($image_name){$crop_q->where('image_name', '=', $image_name);}
        $crop_q->where('name',       '=', $crop_name);
        $crop_q->where('group_id',   '=', $group_id);

        $collection = $crop_q->get();

        if(!$collection->isEmpty())
        {
            $_obj = $collection->first();

            return $_obj->toArray();

        }else{

            throw new BuildQueryException('Данные кропа '.$crop_name.' блока '.$block_name.' группы '.$group_name.' картинки '.$image_name.' не найдены в базе.');
        }
    }

}


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: LabelList.php 543 2009-10-03 08:50:00Z mr_a_ton$
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;
use Openbizx\Easy\Element\OptionElement;

/**
 * LabelList class is element that show description (read only) from Selection.xml
 *
 * @package openbiz.bin.easy.element
 * @author Agus Suhartono, Rocky Swen (original ListBox author)
 * @copyright Copyright (c) 2009
 * @version 1.0
 * @access public
 */
class LabelList extends OptionElement
{
    public $blankOption;

    /**
     * Read metadata info from metadata array and store to class variable
     *
     * @param array $xmlArr metadata array
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->link = isset($xmlArr["ATTRIBUTES"]["LINK"]) ? $xmlArr["ATTRIBUTES"]["LINK"] : null;
        $this->blankOption = isset($xmlArr["ATTRIBUTES"]["BLANKOPTION"]) ? $xmlArr["ATTRIBUTES"]["BLANKOPTION"] : null;
    }
    /**
     * Get link that evaluated by Expression::evaluateExpression
     *
     * @return string link
     */
    protected function getLink()
    {
        if ($this->link == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

    /**
     * Render, draw the element to show description
     *
     * @return string HTML text
     */
    public function render()
    {
    	$value = $this->text ? $this->getText() : $this->value;
        $fromList   = array();
        $this->getFromList($fromList);
        $valueArr = explode(',', $this->value);
        $style = $this->getStyle();
        $func = $this->getFunction();
        $id = $this->objectName;
        $selectedStr = '';

        $selectedStr = $value;

        foreach ($fromList as $option)
        {
            $test = array_search($option['val'], $valueArr);
            if (!($test === false))
            {
                $selectedStr = $option['txt'] ;
                break;
            }
        }

        if($selectedStr=="0" || $selectedStr==null){
        	$selectedStr = $this->blankOption;
        }

        if ($this->getLink())
        {
            $link = $this->getLink();
            $sHTML = "" . $selectedStr . "";
        }
        else
            $sHTML = "" . $selectedStr . "";

        if($this->backgroundColor)
        {
            	$bgcolor = $this->getBackgroundColor();
       			if($bgcolor){
            		$sHTML = "
$sHTML
";
            	}
        }
        return $sHTML;
    }
}
?>


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Textarea.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\OptionElement;

/**
 * Textarea class is element for render html Textarea
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class Textarea extends OptionElement
{
	public $blankOption;

	public function readMetaData(&$xmlArr){
		parent::readMetaData($xmlArr);
		$this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_textarea";
		$this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : "input_textarea_error";
		$this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : "input_textarea_focus";
		$this->blankOption = isset($xmlArr["ATTRIBUTES"]["BLANKOPTION"]) ? $xmlArr["ATTRIBUTES"]["BLANKOPTION"] : null;
	}
   /**
    * Render, draw the element according to the mode
    *
    * @return string HTML text
    */
    public function render()
    {

        $disabledStr = ($this->getEnabled() == "N") ? "DISABLED=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();
    	if($formobj->errors[$this->objectName]){
			$func .= "onchange=\"this.className='$this->cssClass'\"";
		}else{
			$func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
		}
        $sHTML .= "<TEXTAREA NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" $disabledStr $this->htmlAttr $style $func>".$this->value."</TEXTAREA>";

        if($this->selectFrom){
        	$fromList = array();
	        $this->getFromList($fromList);
	        $valueArray = explode(',', $this->value);
	        $sHTML .= "
objectName ."_suggestion\" class=\"input_textarea_suggestion\" >";
	        if ($this->blankOption) // ADD a blank option
	        {
	            $entry = explode(",",$this->blankOption);
	            $text = $entry[0];
	            $value = ($entry[1]!= "") ? $entry[1] : null;
	            $entryList = array("val" => $value, "txt" => $text );
	            $sHTML .= "

".$entryList['txt']."

";
	        }

	        foreach ($fromList as $option)
	        {
	            $sHTML .= "
objectName."').value+='".$option['val']."'\" >".$option['txt']."
";
	        }
	        $sHTML .= "
";
        }
        return $sHTML;
    }

}

?>


<?php

namespace Environaut\Report\Results\Settings;

use Environaut\Checks\ICheck;
use Environaut\Report\Results\Settings\ISetting;

/**
 * Simple value holder with a name as key and a group name to be used to group/namespace settings.
 */
class Setting implements ISetting
{
    /**
     * @var string setting name
     */
    protected $name;

    /**
     * @var string name of group this setting belongs to
     */
    protected $group;

    /**
     * @var mixed value of this setting
     */
    protected $value;

    /**
     * @var int value of this setting
     */
    protected $flag;

    /**
     * Create a new setting instance.
     *
     * @param string $name name of setting
     * @param mixed $value value for that key
     * @param string $group group name that may be used to namespace/group settings
     */
    public function __construct($name, $value, $group = ICheck::DEFAULT_GROUP_NAME, $flag = ISetting::NORMAL)
    {
        $this->name = $name;
        $this->value = $value;
        $this->group = $group;
        $this->flag = $flag;
    }

    /**
     * Returns the name or key of this setting.
     *
     * @return string name of this setting
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Return the value of this setting.
     *
     * @return mixed value of this setting
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Returns the group name of this setting that may be useful for separating settings by group on export.
     *
     * @return string group name
     */
    public function getGroup()
    {
        return $this->group;
    }

    /**
     * Returns the type of setting.
     *
     * @return int flag
     */
    public function getFlag()
    {
        return $this->flag;
    }

    /**
     * Determines whether this setting's flag value is contained in the given flag value.
     *
     * For example: If this setting has a flag of ISetting::NORMAL (1) a given $flag value
     * of (ISetting::SENSITIVE | ISetting::WHATEVER) would not match.
     *
     * @param int $flag setting type value to check against, default is null and matches always
     *
     * @return boolean true if this setting's flag is in the given flag
     */
    public function matchesFlag($flag = null)
    {
        if (null !== $flag) {
            return ($this->flag & $flag);
        }

        return true;
    }

    /**
     * Determines whether this setting's group matches the given groups.
     *
     * @param mixed $groups string or array with group names, default null matches always
     *
     * @return boolean true when this setting's group matches the given groups
     */
    public function matchesGroup($groups = null)
    {
        if (null !== $groups) {
            $group_names = self::getGroupNames($groups);
            return in_array($this->group, $group_names);
        }

        return true;
    }

    /**
     * Returns a flat array with four keys (name, group, value and flag).
     *
     * @return array flat associative array representation of this setting
     */
    public function toArray()
    {
        return array(
            'name' => $this->name,
            'value' => $this->value,
            'group' => $this->group,
            'flag' => $this->flag,
        );
    }

    /**
     * @param mixed $groups string with comma separated group names or an array of group names
     *
     * @return array of group names
     */
    public static function getGroupNames($groups = null)
    {
        $group_names = array();

        if (null === $groups || (!is_string($groups) && !is_array($groups))) {
            return array();
        }

        if (is_string($groups)) {
            $groups = explode(',', $groups);
        }

        foreach ($groups as $group_name) {
            $group_names[] = trim($group_name);
        }

        return $group_names;
    }
}