<?php

/**
 * Openbizx Framework (http://openbizx.github.io/)
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @copyright Copyright (c) 2015 Mpu Technology
 * @license   http://opensource.org/licenses/BSD-3-Clause
 * @link      http://openbizx.github.io/
 */

namespace Openbizx\Object;

use Openbizx\Object\ObjectHelper;

/**
 * This class is base class for Openbizx
 * This class is adapted from Yii Object but loose couple
 * so other application can use this package individualy
 *
 * @link https://github.com/openbizx/openbizx/blob/master/src/Object/Object.php
 * @author Agus Suhartono <agus.suhartono@gmail.com>
 * @since 1.0
 */
class Object
{

    /**
     * Returns the fully qualified name of this class.
     *  This method can use as identifier of singleton object.
     *  For example object that subtitute MetaObject
     *
     * @return string the fully qualified name of this class.
     */
    public static function className()
    {
        return get_called_class();
    }

    /**
     * Constructor.
     * @param array $config [optional]
     */
    public function __construct($config = [])
    {
        if (!empty($config)) {
            ConfiguratorManager::configure($this, $config);
        }
        $this->init();
    }

    /**
     * Initializes the object.
     * This method is invoked at the end of the constructor after the object is initialized with the
     * given configuration.
     * Please don't put initialize code in __contructor()
     */
    public function init()
    {

    }

    /**
     * Returns the value of an object property.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `$value = $object->property;`.
     * @param string $name the property name
     * @return mixed the property value
     * @throws UnknownPropertyException if the property is not defined
     * @throws InvalidCallException if the property is write-only
     * @see __set()
     */
    public function __get($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter)) {
            return $this->$getter();
        } elseif (method_exists($this, 'set' . $name)) {
            //throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
            throw new \Exception('Getting write-only property: ' . get_class($this) . '::' . $name);
        } else {
            //throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
            throw new \Exception('Getting unknown property: ' . get_class($this) . '::' . $name);
        }
    }

    /**
     * Sets value of an object property.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `$object->property = $value;`.
     * @param string $name the property name or the event name
     * @param mixed $value the property value
     * @throws UnknownPropertyException if the property is not defined
     * @throws InvalidCallException if the property is read-only
     * @see __get()
     */
    public function __set($name, $value)
    {
        $setter = 'set' . $name;
        if (method_exists($this, $setter)) {
            $this->$setter($value);
        } elseif (method_exists($this, 'get' . $name)) {
            //throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
            throw new \Exception('Setting read-only property: ' . get_class($this) . '::' . $name);
        } else {
            //throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
            throw new \Exception('Setting unknown property: ' . get_class($this) . '::' . $name);
        }
    }

    /**
     * Checks if the named property is set (not null).
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `isset($object->property)`.
     *
     * Note that if the property is not defined, false will be returned.
     * @param string $name the property name or the event name
     * @return boolean whether the named property is set (not null).
     */
    public function __isset($name)
    {
        $getter = 'get' . $name;
        if (method_exists($this, $getter)) {
            return $this->$getter() !== null;
        } else {
            return false;
        }
    }

    /**
     * Sets an object property to null.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when executing `unset($object->property)`.
     *
     * Note that if the property is not defined, this method will do nothing.
     * If the property is read-only, it will throw an exception.
     * @param string $name the property name
     * @throws InvalidCallException if the property is read only.
     */
    public function __unset($name)
    {
        $setter = 'set' . $name;
        if (method_exists($this, $setter)) {
            $this->$setter(null);
        } elseif (method_exists($this, 'get' . $name)) {
            throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
        }
    }

    /**
     * Calls the named method which is not a class method.
     *
     * Do not call this method directly as it is a PHP magic method that
     * will be implicitly called when an unknown method is being invoked.
     * @param string $name the method name
     * @param array $params method parameters
     * @throws UnknownMethodException when calling unknown method
     * @return mixed the method return value
     */
    public function __xcall($name, $params)
    {
        throw new UnknownMethodException('Unknown method: ' . get_class($this) . "::$name()");
    }

    /**
     * Returns a value indicating whether a property is defined.
     * A property is defined if:
     *
     * - the class has a getter or setter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property is defined
     * @see canGetProperty()
     * @see canSetProperty()
     */
    public function hasProperty($name, $checkVars = true)
    {
        return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
    }

    /**
     * Returns a value indicating whether a property is readable.
     * A property is readable if:
     *
     * - the class has a getter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property can be read
     * @see isReadableProperty()
     */
    public function canGetProperty($name, $checkVars = true)
    {
        return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
    }

    /**
     * Returns a value indicating whether a property is writable.
     * A property is writable if:
     *
     * - the class has a setter method associated with the specified name
     *   (in this case, property name is case-insensitive);
     * - the class has a member variable with the specified name (when `$checkVars` is true);
     *
     * @param string $name the property name
     * @param boolean $checkVars whether to treat member variables as properties
     * @return boolean whether the property can be written
     * @see isReadableProperty()
     */
    public function isWritableProperty($name, $checkVars = true)
    {
        return method_exists($this, 'set' . $name) || ($checkVars && property_exists($this, $name));
    }

    /**
     * Returns a value indicating whether a method is defined.
     *
     * The default implementation is a call to php function `method_exists()`.
     * You may override this method when you implemented the php magic method `__call()`.
     * @param string $name the property name
     * @return boolean whether the property is defined
     */
    public function hasMethod($name)
    {
        return method_exists($this, $name);
    }

    /**
     * Converts the object into an array.
     * The default implementation will return all public property values as an array.
     *
     * @return array the array representation of the object
     * @todo Maybe this method must inherit from Arrayable interface.
     */
    public function toArray()
    {
        return ObjectHelper::getObjectVars($this);
    }

}


<?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
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: DynaView.php 3284 2011-02-22 06:56:33Z rockys $
 */

namespace Openbizx\Easy;

use Openbizx\Easy\WebPage;
/**
 * DynaView class is the class that contains list of forms dinamicaly.
 * View is same as html page.
 *
 * @package openbiz.bin.easy
 * @author rocky swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class DynaView extends WebPage
{
    /**
     * Initialize DynaView with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    public function __construct(&$xmlArr)
    {
        parent::__construct($xmlArr);

        $this->processURL();
    }

    /**
     * Process URL to get the form param and add the form in the FormRefs
     *
     * @return void
     */
    protected function processURL()
    {
        // if url has form=...
        $paramForm = isset($_GET['form']) ? $_GET['form'] : null;
        $paramCForm = isset($_GET['cform']) ? $_GET['cform'] : null;

        if (!$paramForm)
            return;

        // add the form in FormRefs
        if ($paramForm)
        {
        	if($this->isInFormRefLibs($paramForm))
	        	{
	            $xmlArr["ATTRIBUTES"]["NAME"] = $paramForm;
	            $xmlArr["ATTRIBUTES"]["SUBFORMS"] = $paramCForm ? $paramCForm : "";
	            $formRef = new FormReference($xmlArr);
	            $this->formRefs->set($paramForm, $formRef);
	            if ($paramCForm)
	            {
	            	if($this->isInFormRefLibs($paramCForm))
	            	{
		                $xmlArr["ATTRIBUTES"]["NAME"] = $paramCForm;
		                $xmlArr["ATTRIBUTES"]["SUBFORMS"] = "";
		                $cformRef = new FormReference($xmlArr);
		                $this->formRefs->set($paramCForm, $cformRef);
	            	}
	            }
        	}
        }

        // check url arg as fld:name=val
        $getKeys = array_keys($_GET);
        $paramFields = null;
        foreach ($getKeys as $key)
        {
            if (substr($key, 0, 4) == "fld:")
            {
                $fieldName = substr($key, 4);
                $fieldValue = $_GET[$key];
                $paramFields[$fieldName] = $fieldValue;
            }
        }

        if (!$paramFields)
            return;

        $paramForm = $this->prefixPackage($paramForm);
        $formObj = Openbizx::getObject($paramForm);
        $formObj->setRequestParams($paramFields);
    }
}

?>


<?php
namespace Simphotonics\Utils;

/**
 * @author D Reschner <d.reschner@simphotonics.com>
 * @copyright 2016 Simphotonics
 * Description: Web utility methods.
 */
class WebUtils
{
    /**
     * Returns 'baseURI'.
     * @method baseURI
     * @return string  baseUri
     * Examples:
     *     http:://google.com/ => google
     *     /index.php          => index
     *     user/logout/        => logout
     *     user/post/?msg='...'=> post
     */
    public static function baseURI()
    {
        // Check if uri contains a query.
        $uri = $_SERVER['REQUEST_URI'];
        $qmIsHere  = strpos($uri, '?');
        $uri  = ($qmIsHere === false) ? $uri :
            substr($uri, 0, $qmIsHere);
        // Get file name
        return pathinfo($uri)['filename'];
    }

    public static function getURI()
    {
        return $_SERVER['REQUEST_URI'];
    }
}


<?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: InputText.php 3313 2011-02-24 04:32:17Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\InputElement;
/**
 * InputText class is element for input text
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class IDCardReader extends InputElement
{
	protected function readMetaData(&$xmlArr){
		parent::readMetaData($xmlArr);
		$this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_cardreader";
		$this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass."_error";
		$this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass."_focus";
	}
    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	if($this->value!=null){
    		$value = $this->value;
    	}else{
    		$value = $this->getText();
    	}

    	if($value==""){
    		$value = $this->getDefaultValue();
    	}
        $disabledStr = ($this->getEnabled() == "N") ? "READONLY=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();

        $formobj = $this->GetFormObj();
    	if($formobj->errors[$this->objectName]){
			$func .= "onchange=\"this.className='$this->cssClass'\"";
		}else{
			$func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
		}

        //$sHTML = "<INPUT ReadOnly=\"Enabled\" NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" VALUE=\"" . $value . "\" $disabledStr $this->htmlAttr $style $func />";
        //$sHTML .= "
objectName ."_status\" >Standing By";

        $sHTML = "
objectName . "_reader\" $disabledStr $this->htmlAttr $style $func >
        				objectName ."_code\" >$value

<input ReadOnly=\"Enabled\" type=\"hidden\" NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName ."\" VALUE=\"\" />

";

		$elementName = $this->objectName;
        $sHTML .= "";
        return $sHTML;
    }

}

?>


<?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\Authentication\Adapter;

use DoctrineModule\Options\Authentication as AuthenticationOptions;
use Zend\Authentication\Adapter\AbstractAdapter;
use Zend\Authentication\Adapter\Exception;
use Zend\Authentication\Result as AuthenticationResult;

/**
 * Authentication adapter that uses a Doctrine object for verification.
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @since   0.5.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 * @author  Michaël Gallego <mic.gallego@gmail.com>
 */
class ObjectRepository extends AbstractAdapter
{
    /**
     * @var AuthenticationOptions
     */
    protected $options;

    /**
     * Contains the authentication results.
     *
     * @var array
     */
    protected $authenticationResultInfo = null;

    /**
     * Constructor
     *
     * @param array|AuthenticationOptions $options
     */
    public function __construct($options = array())
    {
        $this->setOptions($options);
    }

    /**
     * @param  array|AuthenticationOptions $options
     * @return ObjectRepository
     */
    public function setOptions($options)
    {
        if (!$options instanceof AuthenticationOptions) {
            $options = new AuthenticationOptions($options);
        }

        $this->options = $options;
        return $this;
    }

    /**
     * @return AuthenticationOptions
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set the value to be used as the identity
     *
     * @param  mixed $identityValue
     * @return ObjectRepository
     * @deprecated use setIdentity instead
     */
    public function setIdentityValue($identityValue)
    {
        $this->identity = $identityValue;
        return $this;
    }

    /**
     * @return string
     * @deprecated use getIdentity instead
     */
    public function getIdentityValue()
    {
        return $this->identity;
    }

    /**
     * Set the credential value to be used.
     *
     * @param  mixed $credentialValue
     * @return ObjectRepository
     * @deprecated use setCredential instead
     */
    public function setCredentialValue($credentialValue)
    {
        $this->credential = $credentialValue;
        return $this;
    }

    /**
     * @return string
     * @deprecated use getCredential instead
     */
    public function getCredentialValue()
    {
        return $this->credential;
    }

    /**
     * {@inheritDoc}
     */
    public function authenticate()
    {
        $this->setup();
        $options  = $this->options;
        $identity = $options
            ->getObjectRepository()
            ->findOneBy(array($options->getIdentityProperty() => $this->identity));

        if (!$identity) {
            $this->authenticationResultInfo['code']       = AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND;
            $this->authenticationResultInfo['messages'][] = 'A record with the supplied identity could not be found.';

            return $this->createAuthenticationResult();
        }

        $authResult = $this->validateIdentity($identity);

        return $authResult;
    }

    /**
     * This method attempts to validate that the record in the resultset is indeed a
     * record that matched the identity provided to this adapter.
     *
     * @param  object                              $identity
     * @throws Exception\UnexpectedValueException
     * @return AuthenticationResult
     */
    protected function validateIdentity($identity)
    {
        $credentialProperty = $this->options->getCredentialProperty();
        $getter             = 'get' . ucfirst($credentialProperty);
        $documentCredential = null;

        if (method_exists($identity, $getter)) {
            $documentCredential = $identity->$getter();
        } elseif (property_exists($identity, $credentialProperty)) {
            $documentCredential = $identity->{$credentialProperty};
        } else {
            throw new Exception\UnexpectedValueException(
                sprintf(
                    'Property (%s) in (%s) is not accessible. You should implement %s::%s()',
                    $credentialProperty,
                    get_class($identity),
                    get_class($identity),
                    $getter
                )
            );
        }

        $credentialValue = $this->credential;
        $callable        = $this->options->getCredentialCallable();

        if ($callable) {
            $credentialValue = call_user_func($callable, $identity, $credentialValue);
        }

        if ($credentialValue !== true && $credentialValue !== $documentCredential) {
            $this->authenticationResultInfo['code']       = AuthenticationResult::FAILURE_CREDENTIAL_INVALID;
            $this->authenticationResultInfo['messages'][] = 'Supplied credential is invalid.';

            return $this->createAuthenticationResult();
        }

        $this->authenticationResultInfo['code']       = AuthenticationResult::SUCCESS;
        $this->authenticationResultInfo['identity']   = $identity;
        $this->authenticationResultInfo['messages'][] = 'Authentication successful.';

        return $this->createAuthenticationResult();
    }

    /**
     * This method abstracts the steps involved with making sure that this adapter was
     * indeed setup properly with all required pieces of information.
     *
     * @throws Exception\RuntimeException - in the event that setup was not done properly
     */
    protected function setup()
    {
        if (null === $this->identity) {
            throw new Exception\RuntimeException(
                'A value for the identity was not provided prior to authentication with ObjectRepository '
                . 'authentication adapter'
            );
        }

        if (null === $this->credential) {
            throw new Exception\RuntimeException(
                'A credential value was not provided prior to authentication with ObjectRepository'
                . ' authentication adapter'
            );
        }

        $this->authenticationResultInfo = array(
            'code' => AuthenticationResult::FAILURE,
            'identity' => $this->identity,
            'messages' => array()
        );
    }

    /**
     * Creates a Zend\Authentication\Result object from the information that has been collected
     * during the authenticate() attempt.
     *
     * @return \Zend\Authentication\Result
     */
    protected function createAuthenticationResult()
    {
        return new AuthenticationResult(
            $this->authenticationResultInfo['code'],
            $this->authenticationResultInfo['identity'],
            $this->authenticationResultInfo['messages']
        );
    }
}


<?php

namespace Interpro\QS\Db;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Contracts\Taxonomy\Fields\RefField;
use Interpro\Core\Helpers;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Extractor\Contracts\Collections\MapBCollection;
use Interpro\Extractor\Contracts\Collections\MapCCollection;
use Interpro\Extractor\Contracts\Creation\CItemBuilder;
use Interpro\Extractor\Contracts\Creation\CollectionFactory;
use Interpro\Extractor\Contracts\Db\AMapper;
use Interpro\Extractor\Contracts\Db\MappersMediator;
use Interpro\Extractor\Contracts\Selection\Tuner;
use Interpro\Extractor\Fields\AARefField;
use Interpro\Extractor\Items\AItem;
use Interpro\Extractor\Contracts\Selection\SelectionUnit;
use Interpro\Extractor\Fields\ABOwnField;
use Interpro\Extractor\Fields\ACOwnField;
use Interpro\QS\Creation\QSItemFactory;
use Interpro\QS\Exception\QSException;

class QSAMapper implements AMapper
{
    private $factory;
    private $collectionFactory;
    private $cItemBuilder;
    private $mappersMediator;
    private $qsQuerier;
    private $tuner;
    private $items = [];
    private $collections = [];
    private $local_fields = ['id', 'name', 'slug', 'title', 'sorter', 'show', 'predefined', 'updated_at', 'created_at'];

    public function __construct(QSItemFactory $factory, CollectionFactory $collectionFactory, CItemBuilder $cItemBuilder, MappersMediator $mappersMediator, QSQuerier $qsQuerier, Tuner $tuner)
    {
        $this->factory           = $factory;
        $this->collectionFactory = $collectionFactory;
        $this->cItemBuilder      = $cItemBuilder;
        $this->mappersMediator   = $mappersMediator;
        $this->qsQuerier         = $qsQuerier;
        $this->tuner             = $tuner;
    }

    private function local($field_name)
    {
        return in_array($field_name, $this->local_fields);
    }

    /**
     * @return void
     */
    public function reset()
    {
        $this->items = [];
        $this->collections = [];
    }

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

    private function createRefField(AItem $owner, RefField $refMeta, & $refs_array)
    {
        $fieldType = $refMeta->getFieldType();

        $field_name = $refMeta->getName();
        $key = $field_name.'_'.$owner->getSelfRef()->getId();

        if(array_key_exists($key, $refs_array))
        {
            $id = $refs_array[$key]['ref_entity_id'];
        }
        else
        {
            $id = 0;
        }

        $ref = new \Interpro\Core\Ref\ARef($fieldType, $id);

        $field_type_family = $fieldType->getFamily();

        $mapper = $this->mappersMediator->getAMapper($field_type_family);

        $newField = new AARefField($owner, $refMeta, $ref, $mapper);

        return $newField;
    }

    /**
     * @param AItem $owner
     * @param OwnField $ownMeta
     * @param array & $result
     *
     * @return \Interpro\Extractor\Fields\ACOwnField
     */
    private function createLocalCField(AItem $owner, OwnField $ownMeta, & $result)
    {
        $field_name = $ownMeta->getName();
        $fieldType = $ownMeta->getFieldType();

        if(array_key_exists($field_name, $result))
        {
            $scalarItem = $this->cItemBuilder->create($fieldType, $result[$field_name]);
        }
        else
        {
            $scalarItem = $this->cItemBuilder->createCap($fieldType);
        }

        $newField = new ACOwnField($owner, $ownMeta);
        $newField->setItem($scalarItem);

        return $newField;
    }

    private function createExternalBFieldByRef(AItem $owner, OwnField $ownMeta, MapBCollection $map)
    {
        $field_name = $ownMeta->getName();

        $ref = $owner->getSelfRef();

        $fieldItem = $map->getItem($ref, $field_name);
        $newField = new ABOwnField($owner, $ownMeta);
        $newField->setItem($fieldItem);

        return $newField;
    }

    private function createExternalCFieldByRef(AItem $owner, OwnField $ownMeta, MapCCollection $map)
    {
        $field_name = $ownMeta->getName();

        $ref = $owner->getSelfRef();

        $scalarItem = $map->getItem($ref, $field_name);
        $newField = new ACOwnField($owner, $ownMeta);
        $newField->setItem($scalarItem);

        return $newField;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param bool $asUnitMember
     *
     * @return \Interpro\Extractor\Contracts\Items\AItem
     */
    public function getByRef(ARef $ref, $asUnitMember = false)
    {
        $type  = $ref->getType();
        $rank = $type->getRank();
        $type_name = $type->getName();
        $id = $ref->getId();

        if($rank === TypeRank::GROUP and $asUnitMember)
        {
            $selectionUnit = $this->tuner->getSelection($type_name, 'group');

            $collection = $this->select($selectionUnit);

            return $collection->getItem($id);
        }

        $result = $this->qsQuerier->selectByRef($ref);
        $result = Helpers::laravel_db_result_to_array($result->get());

        if(count($result) === 0)
        {
            throw new QSException('При получении элемента не найдены данные в таблице '.$type_name.': по ссылке '.$ref.'!');
        }

        $refs_array = $this->qsQuerier->getRefValues($type_name, $id);

        $item = $this->factory->create($ref);

        //====================================================поля
        $ownsMetaCollection = $type->getOwns();

        foreach($ownsMetaCollection as $ownMeta)
        {
            $fieldType = $ownMeta->getFieldType();
            $fieldMode = $ownMeta->getMode();

            $field_name = $ownMeta->getName();

            if($this->local($field_name)) //все поля локального хранения - С типы
            {
                $newField = $this->createLocalCField($item, $ownMeta, $result[0]);
            }
            else
            {
                if($fieldMode === TypeMode::MODE_B)
                {
                    $mapper = $this->mappersMediator->getBMapper($fieldType->getFamily());
                    $map = $mapper->getByRef($ref);
                    $newField = $this->createExternalBFieldByRef($item, $ownMeta, $map);
                }
                elseif($fieldMode === TypeMode::MODE_C)
                {
                    $mapper = $this->mappersMediator->getCMapper($fieldType->getFamily());
                    $map = $mapper->getByRef($ref);
                    $newField = $this->createExternalCFieldByRef($item, $ownMeta, $map);
                }
                else
                {
                    throw new QSException('В типе '.$type_name.' обнаружено поле-собственность типа отличного от В или С: '.$field_name.'('.$fieldMode.')!');
                }
            }

            $item->setOwn($newField);
            $item->setField($newField);
        }

        //====================================================ссылки
        $refsMetaCollection = $type->getRefs();

        foreach($refsMetaCollection as $refMeta)
        {
            $newField = $this->createRefField($item, $refMeta, $refs_array);

            $item->setRef($newField);
            $item->setField($newField);
        }

        return $item;
    }

    /**
     * @param \Interpro\Extractor\Contracts\Selection\SelectionUnit $selectionUnit
     *
     * @return \Interpro\Extractor\Contracts\Collections\MapGroupCollection
     */
    public function select(SelectionUnit $selectionUnit)
    {
        $key = 'number_'.$selectionUnit->getNumber();

        if(array_key_exists($key, $this->collections))
        {
            return $this->collections[$key];
        }

        //====================================================
        $type = $selectionUnit->getType();
        $type_name = $type->getName();

        $mapCollection = $this->collectionFactory->createMapGroupCollection($type);

        $qb = $this->qsQuerier->selectByUnit($selectionUnit);

        $result_array = Helpers::laravel_db_result_to_array($qb->get());

        $id_set = array_column($result_array, 'id');

        $selectionUnit->addId($id_set);
        $selectionUnit->complete();

        $ownsMetaCollection = $type->getOwns();
        $refsMetaCollection = $type->getRefs();

        $refs_array = $this->qsQuerier->getRefValues($type_name, $id_set);

        foreach($result_array as $item_result)
        {
            $ref = new \Interpro\Core\Ref\ARef($type, (int)$item_result['id']);

            $item = $this->factory->create($ref);

            //====================================================поля
            foreach($ownsMetaCollection as $ownMeta)
            {
                $fieldType = $ownMeta->getFieldType();
                $fieldMode = $ownMeta->getMode();

                $field_name = $ownMeta->getName();

                if($this->local($field_name)) //все поля локального хранения - С типы
                {
                    $newField = $this->createLocalCField($item, $ownMeta, $item_result);
                }
                else
                {
                    if($fieldMode === TypeMode::MODE_B)
                    {
                        $mapper = $this->mappersMediator->getBMapper($fieldType->getFamily());
                        $map = $mapper->select($selectionUnit);//Селект кэшируется в маппере полей, обращаемся каждий раз при поиске поля
                        $newField = $this->createExternalBFieldByRef($item, $ownMeta, $map);
                    }
                    elseif($fieldMode === TypeMode::MODE_C)
                    {
                        $mapper = $this->mappersMediator->getCMapper($fieldType->getFamily());
                        $map = $mapper->select($selectionUnit);//Селект кэшируется в маппере полей, обращаемся каждий раз при поиске поля
                        $newField = $this->createExternalCFieldByRef($item, $ownMeta, $map);
                    }
                    else
                    {
                        throw new QSException('В типе '.$type_name.' обнаружено поле-собственность типа отличного от В или С: '.$field_name.'('.$fieldMode.')!');
                    }
                }

                $item->setOwn($newField);
                $item->setField($newField);
            }

            //====================================================ссылки
            foreach($refsMetaCollection as $refMeta)
            {
                $newField = $this->createRefField($item, $refMeta, $refs_array);

                $item->setRef($newField);
                $item->setField($newField);
            }

            $mapCollection->addItem($item);
        }

        $this->collections[$key] = $mapCollection;

        return $mapCollection;
    }

    /**
     * @param \Interpro\Extractor\Contracts\Selection\SelectionUnit $selectionUnit
     *
     * @return int
     */
    public function count(SelectionUnit $selectionUnit)
    {
        $qb = $this->qsQuerier->selectByUnit($selectionUnit);

        return $qb->count();
    }

}


<?php
/**
 * Created by PhpStorm.
 * User: hua
 * Date: 2017/8/4
 * Time: 下午6:09
 */

namespace DdvPhp\DdvUtil\Laravel;
use DdvPhp\DdvUtil\Exception;
use \DdvPhp\DdvUtil\String\Conversion;
use \Illuminate\Database\Eloquent\Model as EloquentModel;
use Closure;

/**
 * @mixin EloquentBuilder
 * @mixin \Illuminate\Database\Query\Builder
 * @mixin \Illuminate\Database\Eloquent\Builder
 */
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
    /**
     * 直接获取第一条数据
     * @param  array  $columns
     * @return Model|object|static|null
     */
    public function firstHump($columns = array('*'), $isColumnsAutoHumpToUnderline = true){
        if ($isColumnsAutoHumpToUnderline){
            foreach ($columns as $index => $key){
                $columns[$index] = Conversion::humpToUnderline($key);
            }
        }
        $res = $this->first($columns);
        if ($res instanceof EloquentModel){
            $res->toHump();
        }
        return $res;
    }
    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function firstHumpArray(...$parameters){
        $res = $this->firstHump(...$parameters);
        if ($res instanceof EloquentModel){
            $res = $res->toArray();
        }
        return $res;
    }
    /**
     * Execute the query as a "select" statement.
     *
     * @param  array  $columns
     * @return EloquentCollection|static[]
     */
    public function getHump($columns = array('*'), $isColumnsAutoHumpToUnderline = true){
        if ($isColumnsAutoHumpToUnderline){
            foreach ($columns as $index => $key){
                $columns[$index] = Conversion::humpToUnderline($key);
            }
        }
        $res = $this->get($columns);
        if ($res instanceof EloquentCollection){
            foreach ($res as $item){
                if ($item instanceof EloquentModel){
                    $item->toHump();
                }
            }
        }
        return $res;
    }
    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function getHumpArray(...$parameters){
        return $this->getHump(...$parameters)->toArray();
    }
    /**
     * 返回DdvPage对象
     * @return \DdvPhp\DdvPage $page [分页对象]
     */
    public function getDdvPage (...$parameters) {
        array_unshift($parameters, $this);
        return \DdvPhp\DdvPage::create(...$parameters);
    }
    /**
     * 返回DdvPage数组
     * @return array $data [数据数组]
     */
    public function getDdvPageModel () {
        return $this->getDdvPage(...func_get_args())->getRes();
    }
    /**
     * 返回DdvPage 驼峰数组
     * @return array $data [驼峰数组]
     */
    public function getDdvPageHumpModel () {
        $res = $this->getDdvPageModel();
        if (isset($res)&&isset($res['lists'])&&is_array($res['lists'])){
            foreach ($res['lists'] as $index => $value){
                if ((!empty($value))&&is_object($value)&&method_exists($value, 'toHump')){
                    $res['lists'][$index] = $value->toHump();
                }
            }
        }
        return $res;
    }
    /**
     * 返回DdvPage数组
     * @return array $data [数据数组]
     */
    public function getDdvPageArray () {
        return $this->getDdvPage(...func_get_args())->toArray();
    }
    /**
     * 返回DdvPage 驼峰数组
     * @return array $data [驼峰数组]
     */
    public function getDdvPageHumpArray () {
        return $this->getDdvPage(...func_get_args())->toHumpArray();
    }

    /**
     * @param $ddvIf
     * @param null $whereCall
     * @return $this
     * @throws Exception
     */
    public function whereDdvIf($ddvIf, $whereCall = null){
        if (empty($whereCall)) {
            if ($ddvIf instanceof Closure) {
                $whereCall = $ddvIf;
                $ddvIf = true;
            }else{
                throw new Exception('Must have a closure parameter', 'MUST_HAVE_A_CLOSURE_PARAMETER');
            }
        } elseif ($whereCall instanceof Closure) {
            if ($ddvIf instanceof Closure) {
                $ddvIf = $ddvIf($this);
            }
        }
        if ($ddvIf){
            $res = $whereCall($this);
            if (!empty($res)){
                return $res;
            }
        }
        return $this;
    }
    public function __construct(\Illuminate\Database\Query\Builder $query)
    {
        parent::__construct($query);
        $this->passthru[] = 'getDdvPage';
        $this->passthru[] = 'getDdvPageArray';
    }

}


<?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: OptionElement.php 3561 2011-03-30 06:15:47Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\I18n\I18n;
use Openbizx\Data\Helpers\QueryStringParam;
use Openbizx\Object\ObjectFactoryHelper;
use Openbizx\Easy\Element\InputElement;

/**
 * OptionElement is the base class of element that render list (from Selection.xml)
 * Used by :
 *   - {@link AutoSuggest}
 *   - {@link Checkbox}
 *   - {@link ColumnList}
 *   - {@link EditCombobox}
 *   - {@link LabelList}
 *   - {@link Listbox}
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class OptionElement extends InputElement
{

    public $selectFrom;
    public $selectFromSQL;
    public $selectedList;

    /**
     * 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->selectFrom = isset($xmlArr["ATTRIBUTES"]["SELECTFROM"]) ? $xmlArr["ATTRIBUTES"]["SELECTFROM"] : null;
        $this->selectedList = isset($xmlArr["ATTRIBUTES"]["SELECTEDLIST"]) ? $xmlArr["ATTRIBUTES"]["SELECTEDLIST"] : null;
        $this->selectFromSQL = isset($xmlArr["ATTRIBUTES"]["SELECTFROMSQL"]) ? $xmlArr["ATTRIBUTES"]["SELECTFROMSQL"] : null;
    }

    /**
     * Get select from
     *
     * @return string
     */
    protected function getSelectFrom()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectFrom, $formobj);
    }

    protected function getSelectedList()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectedList, $formobj);
    }

    protected function getSelectFromSQL()
    {
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->selectFromSQL, $formobj);
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        return "";
    }

    /**
     * Get from list
     *
     * @param array $list
     * @return void
     */
    public function getFromList(&$list, $selectFrom = null)
    {
        if (!$selectFrom) {
            $selectFrom = $this->getSelectFrom();
        }
        if (!$selectFrom) {
            return $this->getSQLFromList($list);
        }
        $this->getXMLFromList($list, $selectFrom);
        if ($list != null)
            return;
        $this->getDOFromList($list, $selectFrom);
        if ($list != null)
            return;
        $this->getSimpleFromList($list, $selectFrom);
        if ($list != null)
            return;

        return;
    }

    protected function getXMLFromList(&$list, $selectFrom)
    {
        $pos0 = strpos($selectFrom, "(");
        $pos1 = strpos($selectFrom, ")");
        if ($pos0 > 0 && $pos1 > $pos0) {  // select from xml file
            $xmlFile = substr($selectFrom, 0, $pos0);
            $tag = substr($selectFrom, $pos0 + 1, $pos1 - $pos0 - 1);
            $tag = strtoupper($tag);
            $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($xmlFile);
            if (!$xmlFile) {
                return false;
            }

            $xmlArr = &ObjectFactoryHelper::getXmlArray($xmlFile);
            if ($xmlArr) {
                $i = 0;
                if (!isset($xmlArr["SELECTION"][$tag])) {
                    return false;
                }
                if (!$xmlArr["SELECTION"][$tag][0]) {
                    $array = $xmlArr["SELECTION"][$tag];
                    unset($xmlArr["SELECTION"][$tag]);
                    $xmlArr["SELECTION"][$tag][0] = $array;
                }
                foreach ($xmlArr["SELECTION"][$tag] as $node) {
                    $list[$i]['val'] = $node["ATTRIBUTES"]["VALUE"];
                    $list[$i]['pic'] = $node["ATTRIBUTES"]["PICTURE"];
                    if ($node["ATTRIBUTES"]["TEXT"]) {
                        $list[$i]['txt'] = $node["ATTRIBUTES"]["TEXT"];
                    } else {
                        $list[$i]['txt'] = $list[$i]['val'];
                    }
                    $i++;
                }
                $this->translateList($list, $tag); // supprot multi-language
            }
            return true;
        }
        return false;
    }

    protected function getDOFromList(&$list, $selectFrom)
    {
        $pos0 = strpos($selectFrom, "[");
        $pos1 = strpos($selectFrom, "]");
        if ($pos0 > 0 && $pos1 > $pos0) {  // select from bizObj
            // support BizObjName[BizFieldName] or
            // BizObjName[BizFieldName4Text:BizFieldName4Value] or
            // BizObjName[BizFieldName4Text:BizFieldName4Value:BizFieldName4Pic]
            $bizObjName = substr($selectFrom, 0, $pos0);
            $pos3 = strpos($selectFrom, ":");
            if ($pos3 > $pos0 && $pos3 < $pos1) {
                $fieldName = substr($selectFrom, $pos0 + 1, $pos3 - $pos0 - 1);
                $fieldName_v = substr($selectFrom, $pos3 + 1, $pos1 - $pos3 - 1);
            } else {
                $fieldName = substr($selectFrom, $pos0 + 1, $pos1 - $pos0 - 1);
                $fieldName_v = $fieldName;
            }
            $pos4 = strpos($fieldName_v, ":");
            if ($pos4) {
                $fieldName_v_mixed = $fieldName_v;
                $fieldName_v = substr($fieldName_v_mixed, 0, $pos4);
                $fieldName_p = substr($fieldName_v_mixed, $pos4 + 1, strlen($fieldName_v_mixed) - $pos4 - 1);
                unset($fieldName_v_mixed);
            }
            $commaPos = strpos($selectFrom, ",", $pos1);
            if ($commaPos > $pos1) {
                $searchRule = trim(substr($selectFrom, $commaPos + 1));
            }

            /* @var $bizObj BizDataObj */
            $bizObj = Openbizx::getObject($bizObjName);
            if (!$bizObj) {
                return false;
            }

            $recList = array();
            $oldAssoc = $bizObj->association;
            $bizObj->association = null;
            QueryStringParam::reset();
            $recList = $bizObj->directFetch($searchRule);
            $bizObj->association = $oldAssoc;

            foreach ($recList as $rec) {
                $list[$i]['val'] = $rec[$fieldName_v];
                $list[$i]['txt'] = $rec[$fieldName];
                $list[$i]['pic'] = $rec[$fieldName_p];
                $i++;
            }

            return true;
        }
        return false;
    }

    protected function getSimpleFromList(&$list, $selectFrom)
    {
        // in case of a|b|c
        if (strpos($selectFrom, "[") > 0 || strpos($selectFrom, "(") > 0) {
            return;
        }
        $recList = explode('|', $selectFrom);
        foreach ($recList as $rec) {
            $list[$i]['val'] = $rec;
            $list[$i]['txt'] = $rec;
            $list[$i]['pic'] = $rec;
            $i++;
        }
    }

    public function getSQLFromList(&$list)
    {
        $sql = $this->getSelectFromSQL();
        if (!$sql)
            return;
        $formObj = $this->getFormObj();
        $do = $formObj->getDataObj();
        $db = $do->getDBConnection();
        try {
            $resultSet = $db->query($sql);
            $recList = $resultSet->fetchAll();
            foreach ($recList as $rec) {
                $list[$i]['val'] = $rec[0];
                $list[$i]['txt'] = isset($rec[1]) ? $rec[1] : $rec[0];
                $i++;
            }
        } catch (Exception $e) {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
            $this->errorMessage = "Error in SQL query: " . $sql . ". " . $e->getMessage();
            throw new Openbizx\Data\Exception($this->errorMessage);
            return null;
        }
    }

    protected function translateList(&$list, $tag)
    {
        $module = $this->getModuleName($this->selectFrom);
        if (empty($module)) {
            $module = $this->getModuleName($this->formName);
        }
        for ($i = 0; $i < count($list); $i++) {
            $key = 'SELECTION_' . strtoupper($tag) . '_' . $i . '_TEXT';
            $list[$i]['txt'] = I18n::t($list[$i]['txt'], $key, $module, $this->getTransLOVPrefix());
        }
    }

    protected function getTransLOVPrefix()
    {
        $nameArr = explode(".", $this->selectFrom);
        for ($i = 1; $i < count($nameArr) - 1; $i++) {
            $prefix .= strtoupper($nameArr[$i]) . "_";
        }
        return $prefix;
    }

}

?>


<?php

namespace Interpro\QuickStorage\Laravel;

use Interpro\QuickStorage\Concept\Param\GroupParam;
use Interpro\QuickStorage\Concept\QueryAgent as QueryAgentInterface;
use Interpro\QuickStorage\Concept\Repository as RepositoryInterface;
use Interpro\QuickStorage\Concept\Sorting\GroupSortingSet;
use Interpro\QuickStorage\Concept\Specification\GroupSpecificationSet;
use Interpro\QuickStorage\Laravel\Collection\GroupCollection;
use Interpro\QuickStorage\Laravel\Item\BlockItem;
use Interpro\QuickStorage\Laravel\Item\GroupItem;
use Interpro\QuickStorage\Laravel\Sorting\GroupSorting;
use Interpro\QuickStorage\Laravel\Sorting\RandomGroupSorting;
use Interpro\QuickStorage\Laravel\Specification\GroupSpecificationEq;

class QueryAgent implements QueryAgentInterface{

    protected $repository;
    private $groupSortingSet;
    private $groupSpecificationSet;
    private $groupParam;

    /**
     * @param  \Interpro\QuickStorage\Concept\Repository $repository
     * @param  \Interpro\QuickStorage\Concept\Sorting\GroupSortingSet $groupSortingSet
     * @param  \Interpro\QuickStorage\Concept\Specification\GroupSpecificationSet $groupSpecificationSet
     * @param  \Interpro\QuickStorage\Concept\Param\GroupParam $groupParam
     * @return void
     */
    public function __construct(
        RepositoryInterface $repository,
        GroupSortingSet $groupSortingSet,
        GroupSpecificationSet $groupSpecificationSet,
        GroupParam $groupParam
    ){
        $this->repository = $repository;
        $this->groupSortingSet = $groupSortingSet;
        $this->groupSpecificationSet = $groupSpecificationSet;
        $this->groupParam = $groupParam;
    }

    public function setSorts(array $sorts)
    {
        foreach($sorts as $group_name=>$sort_arr)
        {
            $this->groupSortingSet->reset($group_name);

            if(is_array($sort_arr))
            {
                foreach($sort_arr as $field_name=>$sort_way)
                {
                    if($field_name == 'random')
                    {
                        $sort_obj = new RandomGroupSorting($group_name);
                    }else{
                        $sort_obj = new GroupSorting($group_name, $field_name, $sort_way);
                    }

                    $this->groupSortingSet->add($group_name, $sort_obj);
                }
            }
        }
    }

    public function setEqSpecs(array $specs)
    {
        foreach($specs as $group_name=>$spec_arr)
        {
            $this->groupSpecificationSet->reset($group_name);

            if(is_array($spec_arr))
            {
                foreach($spec_arr as $field_name=>$spec_val)
                {
                    $spec_obj = new GroupSpecificationEq($group_name, $field_name, $spec_val);

                    $this->groupSpecificationSet->add($group_name, $spec_obj);
                }
            }
        }
    }

    public function setParams(array $params)
    {
        foreach($params as $group_name=>$param_arr)
        {
            if(is_array($param_arr))
            {
                foreach($param_arr as $param_name=>$param_val)
                {
                    $this->groupParam->set($group_name, $param_name, $param_val);
                }
            }
        }
    }

    /**
     * Получить элемент блока с полями
     *
     * @param string $name
     * @param array $sorts
     * @param array $specs
     * @param array $params
     * @return \Interpro\QuickStorage\Concept\Item\BlockItem
     */
    public function getBlock($name, $sorts, $specs, $params=[])
    {
        $this->setSorts($sorts);
        $this->setEqSpecs($specs);
        $this->setParams($params);

        $fields_arr = $this->repository->getBlock($name);

        $block_item = new BlockItem($fields_arr, 0);

        return $block_item;
    }

    /**
     * Получить коллекцию элементов группы по имени
     *
     * @param string $block_name
     * @param string $name
     * @param array $sorts
     * @param array $specs
     * @param array $params
     * @return \Interpro\QuickStorage\Concept\Collection\GroupCollection
     */
    public function getGroup($block_name, $name, $sorts, $specs, $params=[])
    {
        $this->groupSortingSet->reset($name);
        $this->groupSpecificationSet->reset($name);
        $this->groupParam->reset($name);

        $this->setSorts($sorts);
        $this->setEqSpecs($specs);
        $this->setParams($params);

        $items_arr = $this->repository->getGroup($block_name, $name);

        $group_coll = new GroupCollection($block_name, $name, $items_arr);

        return $group_coll;
    }

    /**
     * Получить коллекцию элементов группы по имени
     *
     * @param string $block_name
     * @param string $name
     * @param array $specs
     * @return int
     */
    public function getGroupCount($block_name, $name, $specs)
    {
        $this->groupSpecificationSet->reset($name);
        $this->setEqSpecs($specs);

        return $this->repository->getGroupCount($block_name, $name);
    }

    /**
     * Получить коллекцию элементов группы по имени
     *
     * @param string $block_name
     * @param string $name
     * @param array $sorts
     * @param array $specs
     * @param array $params
     * @return \Interpro\QuickStorage\Concept\Collection\GroupCollection
     */
    public function getGroupFlat($block_name, $name, $sorts, $specs, $params=[])
    {
        $this->groupSortingSet->reset($name);
        $this->groupSpecificationSet->reset($name);
        $this->groupParam->reset($name);

        $this->setSorts($sorts);
        $this->setEqSpecs($specs);
        $this->setParams($params);

        $items_arr = $this->repository->getGroupFlat($block_name, $name);

        $group_coll = new GroupCollection($block_name, $name, $items_arr);

        return $group_coll;
    }

    /**
     * Получить коллекцию элементов группы по имени
     *
     * @param string $block_name
     * @param string $group_name
     * @param int $group_id
     * @return \Interpro\QuickStorage\Concept\Item\GroupItem
     */
    public function getGroupItem($block_name, $group_name, $group_id)
    {
        $item_arr = $this->repository->getGroupItem($block_name, $group_name, $group_id);

        $item = new GroupItem($item_arr);

        return $item;

    }

    /**
     * Получить коллекцию элементов группы по имени
     *
     * @param string $block_name
     * @param string $group_name
     * @param string $slug
     * @return \Interpro\QuickStorage\Concept\Item\GroupItem
     */
    public function getGroupItemBySlug($block_name, $group_name, $slug)
    {
        $item_arr = $this->repository->getGroupItemBySlug($block_name, $group_name, $slug);

        $item = new GroupItem($item_arr);

        return $item;
    }

}


<?php

namespace Interpro\QS\Executors;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Executor\AUpdateExecutor;
use Interpro\Core\Contracts\Mediator\RefConsistMediator;
use Interpro\Core\Contracts\Mediator\UpdateMediator;
use Interpro\Core\Contracts\Ref\ARef as ARefInterface;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\QS\Exception\QSException;
use Interpro\QS\Model\Block;
use Interpro\QS\Model\Group;
use Interpro\QS\Model\Ref;
use Interpro\Core\Ref\ARef;

class UpdateExecutor implements AUpdateExecutor
{
    private $refConsistMediator;
    private $updateMediator;

    public function __construct(RefConsistMediator $refConsistMediator, UpdateMediator $updateMediator)
    {
        $this->updateMediator = $updateMediator;
        $this->refConsistMediator = $refConsistMediator;
    }

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

    private function slugExist($name, $slug)
    {
        $collection = Group::where('slug', $slug)->where('name', $name)->get();

        return !$collection->isEmpty();
    }

    private function refExist(AType $type, $id)
    {
        $ref = new ARef($type, $id);

        return $this->refConsistMediator->exist($ref);
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param array $values
     *
     * @return void
     */
    public function update(ARefInterface $Aref, array $values)
    {
        $type = $Aref->getType();
        $type_name = $type->getName();

        $id = $Aref->getId();

        $type_rank = $type->getRank();

        $self_fields = ['slug', 'title','sorter', 'predefined','show'];

        //[[[
        DB::beginTransaction();

        if($type_rank === TypeRank::BLOCK)
        {
            $model = Block::find($type_name);
            if(!$model)
            {
                throw new QSException('Не найден блок по имени '.$type_name.'!');
            }

            if(array_key_exists('show', $values))
            {
                $model->show = (bool) $values['show'];
            }

            if(array_key_exists('title', $values))
            {
                $model->title = $values['title'];
            }

            $model->save();
        }
        elseif($type_rank === TypeRank::GROUP)
        {
            $model = Group::find($id);
            if(!$model)
            {
                throw new QSException('Не найден элемент группы '.$type_name.'('.$id.')!');
            }

            if(array_key_exists('slug', $values))
            {
                if($model->predefined)
                {
                    throw new QSException('Нельзя изменять slug для предопределенного элемента '.$type_name.' уже установлено: '.$model->slug.', передано '.$values['slug'].'!');
                }

                if($values['slug'] !== $model->slug and $this->slugExist($type_name, $values['slug']))
                {
                    throw new QSException('Значение slug '.$values['slug'].' для типа '.$type_name.' уже занято!');
                }

                $model->slug = $values['slug'];
            }

            if(array_key_exists('show', $values))
            {
                $model->show = (bool) $values['show'];
            }

            if(array_key_exists('title', $values))
            {
                $model->title = $values['title'];
            }

            if(array_key_exists('sorter', $values))
            {
                $model->sorter = $values['sorter'];
            }

            if(array_key_exists('predefined', $values))
            {
                //С помощью update можно включить, но выключить нельзя, только удалить
                $model->predefined = ($model->predefined or $values['predefined']);
            }

            $model->save();
        }
        else
        {
            throw new QSException('При сохранении изменений передан тип с рангом отличным от блока и группы: '.$type->getRank().'!');
        }

        $refs = $type->getRefs();

        foreach($refs as $ref_name => $ref)
        {
            $refType = $ref->getFieldType();

            $ref_type_name = $refType->getName();

            if(array_key_exists($ref_name, $values))
            {
                $ref_entity_id = (int) $values[$ref_name];

                if (!$this->refExist($refType, $ref_entity_id))
                {
                    throw new QSException('Сущность по ссылке отсутствует: '.$ref_type_name.'('.$ref_entity_id.')!');
                }

                $refModel = Ref::firstOrNew(['entity_name' => $type_name, 'entity_id' => $id, 'name' => $ref_name, 'ref_entity_name' => $ref_type_name]);
                $refModel->ref_entity_id = $ref_entity_id;
                $refModel->save();
            }
        }

        $owns = $type->getOwns();

        foreach($owns as $own_name => $own)
        {
            if(in_array($own_name, $self_fields))
            {
                continue;
            }

            $family = $own->getFieldTypeFamily();
            $mode = $own->getMode();

            if(array_key_exists($own_name, $values))
            {
                $value = $values[$own_name];

                if($mode === TypeMode::MODE_B)
                {
                    $updater = $this->updateMediator->getBUpdateExecutor($family);
                    $updater->update($Aref, $own, $value);
                }
                elseif($mode === TypeMode::MODE_C)
                {
                    $updater = $this->updateMediator->getCUpdateExecutor($family);
                    $updater->update($Aref, $own, $value);
                }
            }
        }

        DB::commit();
        //]]]
    }
}


<?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\Easy\Element\LabelText;

/**
 * LabelPassword class is element that show text with mask (for password)
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2009
 * @version 1.0
 * @access public
 */
class LabelPassword extends LabelText
{
    public $sortable;
    public $columnStyle;
    public $maskChar;
    public $maskLength;

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->maskChar = isset($xmlArr["ATTRIBUTES"]["MASKCHAR"]) ? $xmlArr["ATTRIBUTES"]["MASKCHAR"] : "*";
        $this->maskLength = isset($xmlArr["ATTRIBUTES"]["MASKLENGTH"]) ? $xmlArr["ATTRIBUTES"]["MASKLENGTH"] : 6;
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $sHTML = "<span $style $func> ".str_repeat($this->maskChar, $this->maskLength)." </span>";
        return $sHTML;
    }

}

?>


<?php

namespace Environaut\Export\Formatter;

use Environaut\Report\IReport;
use Environaut\Report\Results\Messages\Message;
use Environaut\Export\Formatter\BaseFormatter;

/**
 * Simple formatter that takes messages from the results
 * of the given report and enhances them according to their
 * severity etc.
 */
class ConsoleMessageFormatter extends BaseFormatter
{
    /**
     * Default sprintf compatible format for messages. May be changed via parameters.
     */
    const DEFAULT_FORMAT = '[%1$s] [%2$s] %3$s';

    /**
     * Returns a formatted string consisting of all
     * messages from the results of the given report.
     *
     * @param IReport $report report to take results (and messages) from
     *
     * @return string messages formatted with the configured format
     */
    public function format(IReport $report)
    {
        $output = '';
        $format = $this->getParameters()->get('format', self::DEFAULT_FORMAT);

        $results = $report->getResults();
        foreach ($results as $result) {
            $messages = $result->getMessages();
            foreach ($messages as $message) {
                switch($message->getSeverity()) {
                    case Message::SEVERITY_FATAL:
                    case Message::SEVERITY_ERROR:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<error>' . $message->getText() . '</error>'
                        );
                        break;
                    case Message::SEVERITY_NOTICE:
                    case Message::SEVERITY_WARN:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<comment>' . $message->getText() . '</comment>'
                        );
                        break;
                    case Message::SEVERITY_INFO:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<info>' . $message->getText() . '</info>'
                        );
                        break;
                    case Message::SEVERITY_DEBUG:
                    default:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            $message->getText()
                        );
                        break;
                }

                $output .= PHP_EOL;
            }
        }

        return $output;
    }
}


<?php

namespace Openbizx\Object;

use Openbizx\Openbizx;
use Openbizx\Helpers\XMLParser;

/**
 * Helper class for ObjectFactory
 *
 * @author agus
 */
class ObjectFactoryHelper
{

    private static $_xmlFileList = [];
    private static $_xmlArrayList = [];

    /**
     * Get Xml file with path
     *
     * Search the object metedata file as objname+.xml in metedata directories
     * name convension: demo.BOEvent points to metadata/demo/BOEvent.xml
     * new in 2.2.3, demo.BOEvent can point to modules/demo/BOEvent.xml
     *
     * @param string $objectName xml object name
     * @return string xml config file path
     * */
    public static function getXmlFileWithPath($objectName)
    {
        if (isset(self::$_xmlFileList[$objectName])) {
            return self::$_xmlFileList[$objectName];
        }
        // replace "." with "/"
        $xmlFile = str_replace(".", "/", $objectName);
        $xmlFile .= ".xml";
        $xmlFile = "/" . $xmlFile;

        // search in modules directory first
        $xmlFileList[] = Openbizx::$app->getModulePath() . $xmlFile;
        $xmlFileList[] = OPENBIZ_APP_PATH . $xmlFile;
        $xmlFileList[] = OPENBIZ_META . $xmlFile;

        foreach ($xmlFileList as $xmlFileItem) {
            if (file_exists($xmlFileItem)) {
                self::$_xmlFileList[$objectName] = $xmlFileItem;
                return $xmlFileItem;
            }
        }
        self::$_xmlFileList[$objectName] = null;
        return null;
    }

    /**
     * Get Xml Array.
     * If xml file has been compiled (has .cmp), load the cmp file as array;
     * otherwise, compile the .xml to .cmp first new 2.2.3, .cmp files
     * will be created in app/cache/metadata_cmp directory. replace '/' with '_'
     * for example, /module/demo/BOEvent.xml has cmp file as _module_demo_BOEvent.xml
     *
     * @param string $xmlFile
     * @return array
     **/
    public static function &getXmlArray($xmlFile)
    {
        if (isset(self::$_xmlArrayList[$xmlFile])) {
            return self::$_xmlArrayList[$xmlFile];
        }

        $objXmlFileName = $xmlFile;
        //echo "getXmlArray($xmlFile)\n";
        //$objCmpFileName = dirname($objXmlFileName) . "/__cmp/" . basename($objXmlFileName, "xml") . ".cmp";
        //$_crc32 = sprintf('%08X', crc32(dirname($objXmlFileName)));
        $_hash = strtoupper(md5(dirname($objXmlFileName)));
        $objCmpFileName = OPENBIZ_CACHE_METADATA_PATH . '/' . $_hash . '_'
                . basename($objXmlFileName, "xml") . "cmp";

        $xmlArr = null;
        //$cacheKey = substr($objXmlFileName, strlen(META_PATH)+1);
        $cacheKey = $objXmlFileName;
        $findInCache = false;
        if (file_exists($objCmpFileName) && (filemtime($objCmpFileName) > filemtime($objXmlFileName))) {
            // search in cache first
            if (!$xmlArr && extension_loaded('apc')) {
                if (($xmlArr = apc_fetch($cacheKey)) != null) {
                    $findInCache = true;
                }
            }
            if (!$xmlArr) {
                $content_array = file($objCmpFileName);
                $xmlArr = unserialize(implode("", $content_array));
            }
        } else {
            $parser = new XMLParser($objXmlFileName, 'file', 1);
            $xmlArr = $parser->getTree();
            //echo var_dump($xmlArr);
            // simple validate the xml array
            $root_keys = array_keys($xmlArr);
            $root_key = $root_keys[0];
            if (!$root_key || $root_key == "") {
                trigger_error("Metadata file parsing error for file $objXmlFileName. Please double check your metadata xml file again.", E_USER_ERROR);
            }
            $xmlArrStr = serialize($xmlArr);

            if (!file_exists(dirname($objCmpFileName))) {
                mkdir(dirname($objCmpFileName));
            }
            $cmp_file = fopen($objCmpFileName, 'w') or die("can't open cmp file to write");
            fwrite($cmp_file, $xmlArrStr) or die("can't write to the cmp file");
            fclose($cmp_file);
        }
        // save to cache to avoid file processing overhead
        if (!$findInCache && extension_loaded('apc')) {
            apc_store($cacheKey, $xmlArr);
        }
        self::$_xmlArrayList[$xmlFile] = $xmlArr;
        return $xmlArr;
    }

}


<?php

namespace Environaut\Cache;

use Environaut\Cache\ICache;
use Environaut\Report\Results\Settings\ISetting;

class Cache extends ReadOnlyCache implements ICache
{
    /**
     * Add the given setting to the cache. Remember it is not persistent without a call to save().
     *
     * @param \Environaut\Report\Results\Settings\ISetting $setting
     */
    public function add(ISetting $setting)
    {
        $this->settings[] = $setting;

        return $this;
    }

    /**
     * Adds the given ISetting instances to the cache. Remember that the settings are not persistent
     * without a call to save().
     *
     * @param array $settings array of ISetting implementing instances
     *
     * @return \Environaut\Cache\Cache this instance for fluent API support
     */
    public function addAll(array $settings)
    {
        foreach ($settings as $setting) {
            if ($setting instanceof ISetting) {
                $this->settings[] = $setting;
            }
        }

        return $this;
    }

    /**
     * Writes the current set of ISetting instances to the cache file location.
     *
     * @return boolean true when cache file writing succeeded
     *
     * @throws \Exception if content could not be encoded
     */
    public function save()
    {
        $location = $this->location;

        // no location given from commandline -> use config values or fallback to default location
        if (empty($location)) {
            $location = $this->parameters->get(
                'write_location',
                $this->parameters->get(
                    'location',
                    $this->getDefaultLocation()
                )
            );
        }

        $this->location = $location;

        $data = array();
        foreach ($this->settings as $setting) {
            $data[] = $setting->toArray();
        }

        $flags = 0;
        if ($this->parameters->get('pretty', true) && version_compare(PHP_VERSION, '5.4.0') >= 0) {
            $flags |= JSON_PRETTY_PRINT;
        }

        $content = json_encode($data, $flags);

        if (false === $content) {
            throw new \Exception('Could not json_encode cachable settings. Nothing written to cache.');
        }

        $success = (false !== file_put_contents($location, $content));

        $success &= chmod($location, 0600); // only current user should read/write potentially sensitive info

        return $success;
    }

    /**
     * Sets the file path to use as cache file location when saving settings.
     *
     * @param string $location cache file path
     *
     * @throws \InvalidArgumentException in case of non-writable cache file path location
     */
    public function setLocation($location)
    {
        if (!is_writable($location)) {
            throw new \InvalidArgumentException('Given cache location "' . $location . '" is not writable.');
        }

        $this->location = $location;
    }
}


<?php

namespace Openbizx\Easy;

/**
 * TabView class is internal class mapping to the metadata of View element in HTMLTabs
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @since 1.2
 * @access public
 */
class TabView
{

    public $objectName;
    public $view;
    public $viewSet;
    public $caption;
    public $url;
    public $target;
    public $icon;
    public $forms; //Forms for hide or show in a BizView

    /**
     * Get forms or the form to hide or show.
     * When It has one form It hasn't the ATTRIBUTES property
     *
     * @param array $forms
     * @return array
     * */

    private function _getForms($forms)
    {
        $recArr = array();
        if (count($forms) == 0)
            return $recArr;

        foreach ($forms as $form) {
            if (!is_null($form["ATTRIBUTES"]))
                $recArr[] = $form["ATTRIBUTES"];
            else
                $recArr[] = $form;
        }
        return $recArr;
    }

    /**
     * Initialize TabView with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->objectName = $xmlArr["ATTRIBUTES"]["NAME"];
        $this->view = $xmlArr["ATTRIBUTES"]["VIEW"];
        if (isset($xmlArr["ATTRIBUTES"]["VIEWSET"])) {
            $this->viewSet = $xmlArr["ATTRIBUTES"]["VIEWSET"];
        }
        $this->caption = $this->translate($xmlArr["ATTRIBUTES"]["CAPTION"]);
        if ($xmlArr["ATTRIBUTES"]["URL"]) {
            $this->url = $xmlArr["ATTRIBUTES"]["URL"];
        }
        if (isset($xmlArr["ATTRIBUTES"]["TARGET"])) {
            $this->target = $xmlArr["ATTRIBUTES"]["TARGET"];
        }
        if (isset($xmlArr["ATTRIBUTES"]["ICON"])) {
            $this->icon = $xmlArr["ATTRIBUTES"]["ICON"];
        }

        $this->forms = NULL;
        if (isset($xmlArr["FORM"])) {
            $this->forms = $this->_getForms($xmlArr["FORM"]);
        }
        //Get form or forms to hide or show
        //$this->forms = (!is_null($xmlArr["FORM"]))?$this->getForms($xmlArr["FORM"]):null;
    }

    /**
     * Return TRUE if the current tabView has forms related to it
     *
     * @return bool
     */
    function hasForms()
    {
        return (bool) $this->forms;
    }

    protected function translate($caption)
    {
        $module = $this->getModuleName($this->objectName);
        return I18n::t($caption, $this->getTransKey(caption), $module);
    }

    protected function getTransKey($name)
    {
        $shortFormName = substr($this->objectName, intval(strrpos($this->objectName, '.')) + 1);
        return strtoupper($shortFormName . '_' . $name);
    }

}


<?php
/*
 * This file is part of the RedKite CMS Application and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://redkite-labs.com
 *
 * @license    MIT License
 */

namespace RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json;

use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Json\Bundle\Bundle;
use RedKiteLabs\RedKiteCms\BootstrapBundle\Core\Exception\InvalidJsonFormatException;

/**
 * Parses a json autoloader and converts it into an object
 *
 * @author RedKite Labs <info@redkite-labs.com>
 */
class JsonAutoloader extends BaseJson
{
    private $bundleName;
    private $filename = null;
    private $bundles = array();
    private $routing = null;

    /**
     * Constructor
     *
     * @param string $bundleName The name of the bundle who the autoloader belongs
     * @param string $filename   The json filename
     */
    public function __construct($bundleName, $filename)
    {
        $this->bundleName = $bundleName;
        $this->filename = $filename;
        $this->setup();
    }

    /**
     * Returns the bundle name
     *
     * @return string
     */
    public function getBundleName()
    {
        return $this->bundleName;
    }

    /**
     * Return the json file name
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * Return the bundles declared in the json autoloader
     *
     * @return string
     */
    public function getBundles()
    {
        return $this->bundles;
    }

    /**
     * Returns the routing option when specified in the autoloader file or null
     *
     * return array|null
     */
    public function getRouting()
    {
        return $this->routing;
    }

    /**
     * Parses the json file and sets up the object
     */
    protected function setup()
    {
        $autoloader = $this->decode($this->filename);
        if (null === $autoloader) {
            throw new InvalidJsonFormatException(sprintf('The json file %s is malformed. Please check the file syntax to fix the problem', $this->filename));
        }

        if (empty($autoloader["bundles"])) {
            throw new InvalidJsonFormatException(sprintf('The json file %s requires the bundles section. Please add that section to fix the problem', $this->filename));
        }

        foreach ($autoloader["bundles"] as $bundleClass => $options) {
            $environments = (isset($options["environments"])) ? $options["environments"] : 'all';
            if (!is_array($environments)) $environments = array($environments);
            $overrides = (isset($options["overrides"])) ? $options["overrides"] : array();
            $bundle = new Bundle();
            $bundle
                ->setClass($bundleClass)
                ->setOverrides($overrides)
            ;
            foreach ($environments as $environment) {
                $this->bundles[$environment][] = $bundle;
            }
        }

        if (isset($autoloader["actionManager"])) {
            $this->actionManagerClass = $autoloader["actionManager"];
        }

        if (isset($autoloader["routing"])) {
            $this->routing = $autoloader["routing"];
        }
    }
}


<?php

namespace Interpro\QS\Executors;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Executor\ADestructor;
use Interpro\Core\Contracts\Mediator\DestructMediator;
use Interpro\Core\Contracts\Mediator\RefConsistMediator;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\QS\Exception\QSException;
use Interpro\QS\Model\Block;
use Interpro\QS\Model\Group;
use Interpro\QS\Model\Ref;

class Destructor implements ADestructor
{
    private $refConsistMediator;
    private $destructMediator;

    public function __construct(RefConsistMediator $refConsistMediator, DestructMediator $destructMediator)
    {
        $this->refConsistMediator = $refConsistMediator;
        $this->destructMediator = $destructMediator;
    }

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

    private function deleteOwns(ARef $ref)
    {
        $type = $ref->getType();

        //Внешние поля
        $families = [];
        $owns = $type->getOwns();

        foreach($owns as $ownField)
        {
            $own_f_f = $ownField->getFieldTypeFamily();

            if(in_array($own_f_f, $families))
            {
                continue;
            }

            $families[] = $own_f_f;

            if($ownField->getMode() === TypeMode::MODE_B)
            {
                $destructor = $this->destructMediator->getBDestructor($own_f_f);
                $destructor->delete($ref);
            }
            elseif($ownField->getMode() === TypeMode::MODE_C)
            {
                $destructor = $this->destructMediator->getCDestructor($own_f_f);
                $destructor->delete($ref);
            }
        }
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return void
     */
    public function delete(ARef $ref)
    {
        $type = $ref->getType();
        $type_name = $type->getName();

        $id = $ref->getId();

        $type_rank = $type->getRank();

        //[[[
        DB::beginTransaction();

        //Удаление собственных ссылок на другие сущности
        Ref::where('entity_name', '=', $type_name)->where('entity_id', '=', $id)->delete();

        //Удаление внешних собственных полей
        $this->deleteOwns($ref);

        //Сообщение ссылающимся, об удалении сущности
        $this->refConsistMediator->notify($ref);

        if($type_rank === TypeRank::BLOCK)
        {
            Block::where('name', '=', $type_name)->delete();
        }
        elseif($type_rank === TypeRank::GROUP)
        {
            Group::where('name', '=', $type_name)->where('id', '=', $id)->delete();
        }
        else
        {
            throw new QSException('В деструкторе qs возможно удаление только сущностей ранга блок или группа, передано: '.$type->getName().'('.$type_rank.').');
        }

        DB::commit();
        //]]]
    }
}


<?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: AutoSuggest.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
//include_once ("OptionElement.php");

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

    public function readMetaData (&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_text";
        $this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass . "_error";
        $this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass . "_focus";
    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render ()
    {
        if (defined('OPENBIZ_JSLIB_BASE') && OPENBIZ_JSLIB_BASE == 'JQUERY') {
			$inputName = $this->objectName;
			$style = $this->getStyle();
			$sHTML = "<input type=\"text\" id=\"$inputName\" name=\"$inputName\" value=\"$this->value\"/ $style>\n";
			$sHTML .= "";
			return $sHTML;
		}

		Openbizx::$app->getClientProxy()->appendScripts("scriptaculous", "scriptaculous.js");
        $selFrom = $this->selectFrom;
        $pos0 = strpos($selFrom, "[");
        $pos1 = strpos($selFrom, "]");
        $first_half = substr($selFrom, 0, $pos1);
        $inputName = $this->objectName;
        $inputChoice = $this->objectName . '_choices';
        $style = $this->getStyle();
        if ($formobj->errors[$this->objectName]) {
            $func .= "onchange=\"this.className='$this->cssClass'\"";
        } else {
            $func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
        }
        if (strpbrk($first_half, ':')) {
            $hInputName = $this->objectName . '_hidden';
            $inputChoice = $this->objectName . '_hidden_choices';
            $sHTML = "<input type=\"text\" id=\"$hInputName\" name=\"$hInputName\" value=\"$this->value\" $style $func/>\n";
            $sHTML .= "

\n";
            $sHTML .= "";
            $sHTML .= "<INPUT NAME=\"" . $inputName . "\" ID=\"" . $inputName . "\" VALUE=\"" . $this->value . "\" type=\"hidden\" >";
        } else {
            $sHTML = "<input type=\"text\" id=\"$inputName\" name=\"$inputName\" value=\"$this->value\" $style $func/>\n";
            $sHTML .= "

\n";
            $sHTML .= "";
        }
        return $sHTML;
    }

    public function matchRemoteMethod ($method)
    {
        return ($method == "autosuggest");
    }
}
?>


<?php

namespace Modules\Menu\Http\Controllers\Admin;

use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Modules\Menu\Entities\Menu;
use Modules\Menu\Entities\MenuContent;
use Modules\Menu\Http\Requests\MenuFormRequest;
use Vain\Http\Controllers\Controller;
use Vain\Http\Requests\Request;

class MenuController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:menu.item.show', ['only' => ['index', 'show']]);
        $this->middleware('permission:menu.item.create', ['only' => ['create', 'store']]);
        $this->middleware('permission:menu.item.edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:menu.item.destroy', ['only' => 'destroy']);
    }

    public function index()
    {
        $menus = Menu::paginate();

        return view('menu::admin.items.index')
            ->with(compact('menus'));
    }

    public function create(Router $router)
    {
        return view('menu::admin.items.create')
            ->with([
                'items'   => $this->prepareParentItems(),
                'types'   => $this->getTypes(),
                'routes'  => $this->prepareRoutes($router),
                'locales' => config('app.locales'),
            ]);
    }

    public function store(MenuFormRequest $request, Router $router)
    {
        /** @var Menu $menu */
        $menu = new Menu($this->processInput($request, $router));
        $menu->save();

        if (!empty($parent_id = $request->input('parent_id'))) {
            $parent = Menu::findOrFail($parent_id);
            $menu->makeChildOf($parent);
        } else {
            $menu->makeRoot();
        }

        foreach (config('app.locales') as $locale => $name) {
            $content = (new MenuContent())
                ->fillTranslated($locale, $request->all());

            $content->menu()->associate($menu);
            $content->save();
        }
    }

    public function edit($id, Router $router)
    {
        $menu = Menu::find($id);

        return view('menu::admin.items.edit')
            ->with([
                'menu'    => $menu,
                'items'   => $this->prepareParentItems(),
                'types'   => $this->getTypes(),
                'routes'  => $this->prepareRoutes($router),
                'locales' => config('app.locales'),
            ]);
    }

    public function update($id, MenuFormRequest $request, Router $router)
    {
        /** @var Menu $menu */
        $menu = Menu::find($id);
        $menu->fill($this->processInput($request, $router));
        $menu->save();

        if (!empty($parent_id = $request->input('parent_id'))) {
            $parent = Menu::findOrFail($parent_id);
            $menu->makeChildOf($parent);
        } else {
            $menu->makeRoot();
        }

        foreach (config('app.locales') as $locale => $name) {
            $content = $menu->contents()
                ->localeOrNew($locale)
                ->fillTranslated($locale, $request->all());

            $content->menu()->associate($menu);
            $content->save();
        }
    }

    public function destroy($id)
    {
        Menu::findOrFail($id)->delete();
    }

    /**
     * @return array
     */
    protected function getTypes()
    {
        return [
            Menu::TYPE_ROUTE => trans('menu::menu.type.route'),
            Menu::TYPE_URL   => trans('menu::menu.type.url'),
        ];
    }

    /**
     * @param Router $router
     *
     * @return array
     */
    protected function prepareRoutes(Router $router)
    {
        $routeCollection = $router->getRoutes();
        $routes = [];

        /** @var Route $route */
        foreach ($routeCollection->getRoutes() as $route) {
            // We mecessarily need a GET Route with a Name
            // other routes are generally unsave to use with
            // the menu module
            if (in_array('GET', $route->methods())
                && $name = $route->getName()) {
                // Store the route in our prepared array
                $routes[$name] = $route->parameterNames();
            }
        }

        return $routes;
    }

    /**
     * @param Request $request
     * @param Router  $router
     *
     * @return array
     */
    protected function processInput(Request $request, Router $router)
    {
        $type = $request->input('type');
        $target = $request->input('target.'.$type);
        $params = null;

        if ($type == Menu::TYPE_ROUTE) {
            // If we got a route type we have to do
            // some preprocessing with the input

            // TODO check the target select input so that we do not have to convert it back everytime
            $target = array_keys($this->prepareRoutes($router))[$target];
            if (array_key_exists($target, $parameter = $request->input('parameters'))) {
                // If we found a parameter map to the given route
                // we store them inside the database.
                $params = $parameter[$target];
            }
        }

        return $request->only(['visible', 'published_at', 'concealed_at']) + [
            'type'       => $type,
            'target'     => $target,
            'parameters' => $params,
        ];
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    protected function prepareParentItems()
    {
        $items = Menu::with('contents')->get()
            ->lists('depth_title', 'id')
            ->toArray();

        return [null => trans('menu::menu.root')] + $items;
    }
}


<?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.service
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: auditService.php 2553 2010-11-21 08:36:48Z mr_a_ton $
 */

namespace Openbizx\Service;

/**
 * auditService class is the plug-in service of handling audit trail of DataObj
 *
 * @package openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 */
class auditService
{

    public $auditDataObj = "system.obj.d_audit_log";

    /**
     * Initialize auditService with xml array metadata
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->auditDataObj = $xmlArr["PLUGINSERVICE"]["ATTRIBUTES"]["BIZDATAOBJ"];
    }

    /**
     * Audit DataObj
     *
     * @param string $dataObjName
     * @return boolean
     * @todo all return false? really?
     */
    public function audit($dataObjName)
    {
        // get audit dataobj
        $auditDataObj = Openbizx::getObject($this->auditDataObj);
        if (!$auditDataObj)
            return false;

        // get the source dataobj
        $srcDataObj = Openbizx::getObject($dataObjName);
        if (!$srcDataObj)
            return false;

        // for each onaudit field, add a record in audit dataobj
        $auditFields = $srcDataObj->getOnAuditFields();
        foreach ($auditFields as $field) {
            if ($field->oldValue == $field->value)
                continue;
            $recArr = $auditDataObj->newRecord();
            if ($recArr == false) {
                Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", $auditDataObj->getErrorMessage());
                return false;
            }

            $profile = Openbizx::$app->getUserProfile();
            $recArr['DataObjName'] = $dataObjName;
            $recArr['ObjectId'] = $srcDataObj->getFieldValue("Id");
            $recArr['FieldName'] = $field->objectName;
            $recArr['OldValue'] = $field->oldValue;
            $recArr['NewValue'] = $field->value;
            $recArr['ChangeTime'] = date("Y-m-d H:i:s");
            $recArr['ChangeBy'] = $profile["USERID"];
            $recArr['ChangeFrom'] = $_SERVER['REMOTE_ADDR'];
            $recArr['RequestURI'] = $_SERVER['REQUEST_URI'];
            $recArr['Timestamp'] = date("Y-m-d H:i:s");
            $ok = $auditDataObj->insertRecord($recArr);
            if ($ok == false) {
                Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", $auditDataObj->getErrorMessage());
                return false;
            }
        }
    }

}


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

/**
 * Application is the base class for all application classes.
 *
 * @author Agus Suhartono <agus.suhartono@gmail.com>
 */
class Application
{

	/**
	 * @var string the root directory of the module.
	 */
	private $_basePath = null;

	/**
	 * Returns the root directory of the application.
	 * It defaults to the directory containing the module class file.
	 * @return string the root directory of the module.
	 */
	public function getBasePath()
	{
		if ($this->_basePath === null) {
			$class = new \ReflectionClass($this);
			$this->_basePath = dirname($class->getFileName());
		}
		return $this->_basePath;
	}

	/**
	 * Sets the root directory of the application.
	 * NOTE: This method can only be invoked at the beginning of the constructor.
	 * @param string $path the root directory of the module. This can be either a directory name or a path alias.
	 * @throws InvalidParamException if the directory does not exist.
	 */
	public function setBasePath($path)
	{
		$path = Yii::getAlias($path);
		$p = realpath($path);
		if ($p !== false && is_dir($p)) {
			$this->_basePath = $p;
		} else {
			throw new InvalidParamException("The directory does not exist: $path");
		}
	}

}


<?php

namespace Modules\Menu\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\User\Entities\Permission;

class MandatoryDatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        Permission::where('name', 'LIKE', 'menu.item.%')->delete();

        Permission::create([
            'name'         => 'menu.item.show',
            'display_name' => 'Show menu',
            'description'  => 'Permission to access the menu component.',
        ]);

        Permission::create([
            'name'         => 'menu.item.create',
            'display_name' => 'Create menu item',
            'description'  => 'Permission to create a new menu item.',
        ]);

        Permission::create([
            'name'         => 'menu.item.edit',
            'display_name' => 'Edit menu item',
            'description'  => 'Permission to modify an existing menu item.',
        ]);

        Permission::create([
            'name'         => 'menu.item.destroy',
            'display_name' => 'Delete menu item',
            'description'  => 'Permission to delete an existing menu item.',
        ]);
    }
}