<?php

namespace Interpro\Entrance\Agents;

use Interpro\Core\Contracts\Mediator\InitMediator;
use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Entrance\Contracts\CommandAgent\InitAgent as InitAgentInterface;
use Interpro\Entrance\Contracts\Extract\ExtractAgent as ExtractAgentInterface;
use Interpro\Entrance\Exception\EntranceException;
use Interpro\Extractor\Collections\BlockCollection;

class InitAgent implements InitAgentInterface
{
    private $initMediator;
    private $taxonomy;
    private $extractAgent;

    public function __construct(
        InitMediator $initMediator,
        Taxonomy $taxonomy,
        ExtractAgentInterface $extractAgent
    )
    {
        $this->initMediator = $initMediator;
        $this->taxonomy     = $taxonomy;
        $this->extractAgent = $extractAgent;
    }

    private function initType(AType $type, array $defaults = [])
    {
        $typeMode = $type->getMode();

        if($typeMode !== TypeMode::MODE_A)
        {
            throw new EntranceException('Агент инициализации может инициализировать только тип (A) уровня, передан тип:'.$type->getName().'('.$typeMode.')!');
        }

        $family = $type->getFamily();

        $initializer = $this->initMediator->getAInitializer($family);

        $ref = $initializer->init($type, $defaults);

        return $ref;
    }

    /**
     * @param string $type_name
     * @param array $defaults
     *
     * @return \Interpro\Extractor\Contracts\Items\AItem
     */
    public function init($type_name, array $defaults = [])
    {
        if(!is_string($type_name))
        {
            throw new EntranceException('Имя типа должно быть задано строкой!');
        }

        $type = $this->taxonomy->getType($type_name);

        if($type->getMode() !== TypeMode::MODE_A)
        {
            throw new EntranceException('Тип '.$type_name.' может быть инициализирован только автоматически в составе (A) типа!');
        }

        $ref = $this->initType($type, $defaults);

        if($type->getRank() === TypeRank::BLOCK)
        {
            $item = $this->extractAgent->getBlock($type_name);
        }
        else
        {
            $item = $this->extractAgent->getGroupItem($type_name, $ref->getId());
        }

        return $item;
    }

    /**
     * @return \Interpro\Extractor\Contracts\Collections\BlockCollection
     */
    public function initBlocks()
    {
        $blocks = $this->taxonomy->getBlocks();

        $blocksCollection = new BlockCollection();

        foreach($blocks as $block)
        {
            $ref = $this->initType($block);
            $blockItem = $this->extractAgent->getBlock($block->getName());
            $blocksCollection->addBlock($blockItem);
        }

        return $blocksCollection;
    }
}


<?php
namespace T3v\T3vContent\ViewHelpers;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder;

use T3v\T3vCore\ViewHelpers\AbstractTagBasedViewHelper;

/**
 * The subheadline link view helper class.
 *
 * @package T3v\T3vContent\ViewHelpers
 */
class SubheadlineLinkViewHelper extends AbstractTagBasedViewHelper {
  /**
   * The tag name.
   *
   * @var string
   */
  protected $tagName = 'h2';

  /**
   * The view helper render function.
   *
   * @param string $content The content of the subheadline
   * @param int $layout The optional layout (UID) of the headline, defaults to `100`
   * @param string $cssClass The optional CSS class of the subheadline, defaults to `ce__subtitle`
   * @return string The rendered subheadline
   */
  public function render($content = null, $layout = 100, $cssClass = 'ce__subtitle') {
    $content  = (string) $content;
    $layout   = intval($layout);
    $cssClass = (string) $cssClass;

    if (empty($content)) {
      $content = $this->renderChildren();
    }

    if (!empty($content) && $layout != 0 && $layout != 100) {
      $layout  = $layout + 1;
      $tagName = "h{$layout}";

      $this->tag->setTagName($tagName);
      $this->tag->addAttribute('class', $cssClass);

      $link = $this->createLink($content);

      $this->tag->setContent($link->render());

      return $this->tag->render();
    }
  }

  /**
   * Creates a link.
   *
   * @param string $content The content of the link
   * @param string $href The optional href attribute of the link, defaults to `#`
   * @param string $title The optional title attribute of the link
   * @return \TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder The link
   */
  protected function createLink($content, $href = '#', $title = null) {
    $content = (string) $content;
    $href    = (string) $href;
    $title   = (string) $title;

    if (empty($title)) {
      $title = $content;
    }

    $link = GeneralUtility::makeInstance('TYPO3\CMS\Fluid\Core\ViewHelper\TagBuilder');
    $link->setTagName('a');
    $link->addAttribute('href', $href);
    $link->addAttribute('title', $title);
    $link->setContent($content);

    return $link;
  }
}


<?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: PickerForm.php 4016 2011-04-29 12:25:27Z jixian2003 $
 */

namespace Openbizx\Easy;

use Openbizx\Easy\EasyForm;

/**
 * PickerForm class - contains form object metadata functions for picker
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class PickerForm extends EasyForm
{
    /**
     *
     * @var string
     */
    public $parentFormElemName = "";

    /**
     *
     * @var string
     */
    public $pickerMap = "";

    public $parentFormRecord ;
    /**
     * Get/Retrieve Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function loadStatefullVars($sessionContext)
    {
        parent::loadStatefullVars($sessionContext);
        $sessionContext->loadObjVar($this->objectName, "ParentFormElemName", $this->parentFormElemName);
        $sessionContext->loadObjVar($this->objectName, "PickerMap", $this->pickerMap);
        $sessionContext->loadObjVar($this->objectName, "ParentFormRecord", $this->parentFormRecord);
    }

    /**
     * Save object variable to session context
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function saveStatefullVars($sessionContext)
    {
        parent::saveStatefullVars($sessionContext);
        $sessionContext->saveObjVar($this->objectName, "ParentFormElemName", $this->parentFormElemName);
        $sessionContext->saveObjVar($this->objectName, "PickerMap", $this->pickerMap);
        $sessionContext->saveObjVar($this->objectName, "ParentFormRecord", $this->parentFormRecord);
    }

    /**
     * Set parent form data/informations
     *
     * @param string $formName
     * @param string $elemName
     * @param string $pickerMap
     * @return void
     */
    public function setParentFormData($formName, $elemName=null, $pickerMap=null)
    {
        $this->parentFormName = $formName;
        $this->parentFormElemName = $elemName;
        $this->pickerMap = $pickerMap;
    }

    /**
     * Pick data to parent form
     *
     * @param <type> $recId
     * @return void
     * @access remote
     */
    public function pickToParent($recId=null)
    {
    	if ($recId==null || $recId=='')
            $recId = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');

        $selIds = Openbizx::$app->getClientProxy()->getFormInputs('row_selections', false);
        if ($selIds == null)
            $selIds[] = $recId;

        // if no parent elem or picker map, call AddToParent
        if (!$this->parentFormElemName)
        {
            $this->addToParent($selIds);
        }

        // if has parent elem and picker map, call JoinToParent
        if ($this->parentFormElemName && $this->pickerMap)
        {
            $this->joinToParent($selIds);
        }

    }

    public function insertToParent()
    {

		$recArr = $this->readInputRecord();
        $this->setActiveRecord($recArr);
        if (count($recArr) == 0)
            return;

        try
        {
            $this->ValidateForm();
        }
        catch (Openbizx\Validation\Exception $e)
        {
            $this->processFormObjError($e->errors);
            return;
        }

        if (!$this->parentFormElemName)
        {
        	//its only supports 1-m assoc now
	        $parentForm = Openbizx::getObject($this->parentFormName);
        	//$parentForm->getDataObj()->clearSearchRule();
	        $parentDo = $parentForm->getDataObj();

	        $column = $parentDo->association['Column'];
	    	$field = $parentDo->getFieldNameByColumn($column);
	    	$parentRefVal = $parentDo->association["FieldRefVal"];

			$recArr[$field] = $parentRefVal;
	    	if($parentDo->association['Relationship']=='1-M'){
		    	$cond_column = $parentDo->association['CondColumn'];
		    	$cond_value = $parentDo->association['CondValue'];
		    	if($cond_column)
		    	{
		    		$cond_field = $parentDo->getFieldNameByColumn($cond_column);
		    		$recArr[$cond_field] = $cond_value;
		    	}
		    	$recId = $parentDo->InsertRecord($recArr);
	    	}else{
	    		$recId = $this->getDataObj()->InsertRecord($recArr);
	    		$this->addToParent($recId);
	    	}
        }

        if ($this->parentFormElemName && $this->pickerMap)
        {
            return ; //not supported yet
        }

        $selIds[] = $recId;

        $this->close();
        if($parentForm->parentFormName){
        	$parentParentForm = Openbizx::getObject($parentForm->parentFormName);
        	$parentParentForm->rerender();
        }
        else
        {
        	$parentForm->rerender();
        }
    }

    /**
     * Join a record (popup) to parent form
     *
     * @param <type> $recId
     * @return void
     */
    public function joinToParent($recIds=null)
    {
    	if(!is_array($recIds))
    	{
    		$recIdArr = array();
    		$recIdArr[] = $recIds;
    	}else{
    		$recIdArr = $recIds;
    	}

    	$parentForm = Openbizx::getObject($this->parentFormName);
    	$updArray = array();
    	$updRec = $this->parentFormRecord;

    	foreach($recIdArr as $recId)
    	{
        	$rec = $this->getDataObj()->fetchById($recId);

	        // get the picker map of the control
	        if ($this->pickerMap)
	        {
	            $pickerList = $this->_parsePickerMap($this->pickerMap);
	            foreach ($pickerList as $ctrlPair)
	            {
	                $this_ctrl = $this->getElement($ctrlPair[1]);
	                if (!$this_ctrl)
	                    continue;

	                $this_ctrl_val = $rec[$this_ctrl->fieldName];
	                $other_ctrl = $parentForm->getElement($ctrlPair[0]);
	                if ($other_ctrl)
	                {
	                	if(!$updArray[$other_ctrl->objectName]){
	                		$updArray[$other_ctrl->objectName] = $this_ctrl_val;
	                		$updRec[$other_ctrl->fieldName] = $this_ctrl_val;
	                	}else{
	                		$updArray[$other_ctrl->objectName] .= ';'.$this_ctrl_val;
	                		$updRec[$other_ctrl->fieldName] .= ';'.$this_ctrl_val;
	                	}
	                }
	            }
	        }
	        else
	            return;
    	}

        $this->close();
        $elem = $parentForm->getElement($this->parentFormElemName);
        if($elem->updateForm=='Y'){
        	$parentForm->setActiveRecord($updRec);
        	$parentForm->rerender();
        }else{
        	Openbizx::$app->getClientProxy()->updateFormElements($parentForm->objectName, $updArray);
        	foreach($updArray as $elemName=>$value)
        	{
        		$elem = $parentForm->getElement($elemName);
        			$elemEvents = $elem->getEvents();
        			foreach($elemEvents as $event=>$function)
        			{
        				if(strtolower($event)=='onchange')
        				{

	        				if(is_array($function)){
								foreach($function as $f){
									$function_str.=$f.";";
								}
							}else{
								$function_str .= $function;
							}
        					Openbizx::$app->getClientProxy()->runClientScript("<script>$function_str</script>");
        				}
        			}
        	}
        }
    }

    /**
     * Add a record (popup) to the parent form if OK button clicked, (M-M or M-1/1-1)
     *
     * @return void
     */
    public function addToParent($recIds=null)
    {
    	if(!is_array($recIds))
    	{
    		$recIdArr = array();
    		$recIdArr[] = $recIds;
    	}else{
    		$recIdArr = $recIds;
    	}

    	/* @var $parentForm EasyForm */
    	$parentForm = Openbizx::getObject($this->parentFormName);
    	foreach($recIdArr as $recId)
    	{

	        //clear parent form search rules
	        $this->searchRule="";
	        $parentForm->getDataObj()->clearSearchRule();

	        $do = $this->getDataObj();
	        $baseSearchRule = $do->baseSearchRule;
	        $do->baseSearchRule = "";
	        $do->clearSearchRule();
	        $rec = $do->fetchById($recId);
			$do->baseSearchRule = $baseSearchRule;

			if(!$rec){
				$rec= Openbizx::getObject($do->objectName,1)->fetchById($recId);
			}

	        // add record to parent form's dataObj who is M-M or M-1/1-1 to its parent dataobj
	        $ok = $parentForm->getDataObj()->addRecord($rec, $bPrtObjUpdated);
	        if (!$ok){
	            return $parentForm->processDataObjError($ok);
	        }
    	}

        $this->close();

        $parentForm->rerender();
		if($parentForm->parentFormName){
			$parentForm->renderParent();
		}
    }

    /**
     * Parse Picker Map into an array
     *
     * @param string $pickerMap pickerMap defined in metadata
     * @return array picker map array
     */
    protected function _parsePickerMap($pickerMap)
    {
        $returnList = array();
        $pickerList = explode(",", $pickerMap);
        foreach ($pickerList as $pair)
        {
            $controlMap = explode(":", $pair);
            $controlMap[0] = trim($controlMap[0]);
            $controlMap[1] = trim($controlMap[1]);
            $returnList[] = $controlMap;
        }
        return $returnList;
    }
}
?>


<?php

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\TreeListbox;

class TreeLabelText extends TreeListbox
{
    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $fromList = array();
        $this->getFromList($fromList);
        $valueArray = explode(',', $this->value);

        $sHTML = "";
        if ($this->blankOption) // ADD a blank option
        {
            $entry = explode(",",$this->blankOption);
            $text = $entry[0];
            $value = ($entry[1]!= "") ? $entry[1] : null;
            $entryList = array(array("val" => $value, "txt" => $text ));
            $fromList = array_merge($entryList, $fromList);
        }

        $i=1;
        $fromListCount=count($fromList);
        foreach ($fromList as $option)
        {
        	//if($i<=($fromListCount-1)){
	            $test = array_search($option['val'], $valueArray);
	            //$sHTML .= "<OPTION VALUE=\"" . $option['val'] . "\" $selectedStr>" . $option['txt'] . "</OPTION>";
	            $sHTML .= "" . $option['txt'] . "
";
	            $i++;
        	//}
        }

        return $sHTML;
    }
}
?>


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Openbizx\Helpers;

use Openbizx\Object\Object;

/**
 * Description of XHProf
 * @property-write boolean $enable Set info is XHProf enable or disable.
 * @author agus
 */
class XHProf extends Object
{
    private static $_isEnabled;
    private static $_isStarted = false;

    /**
     * Location path of XHProf.
     * @var string
     */
    private static $_path = null;

    /**
     * Get location path of XHProf.
     * @return string
     */
    public static function getPath()
    {
        return self::$_path;
    }

    /**
     * Set location path of XHProf.
     * @param string $path Location path of XHProf.
     */
    public static function setPath($path)
    {
        self::$_path = $path;
    }

    /**
     * Url of XHProf
     * @var string
     */
    private static $_url = null;

    /**
     * Get URL of XHProf.
     * @return string
     */
    public static function getUrl()
    {
        return self::$_url;
    }

    /**
     * Set location path of XHProf.
     * @param string $url Location path of XHProf.
     */
    public static function setUrl($url)
    {
        self::$_url = $url;
    }

    /**
     * Set enable info
     * @param boolean $enable Status of enable, true or false.
     * @throws Exception
     */
    public static function setEnable($enable)
    {
        if (!self::$_isStarted) {
            self::$_isEnabled = $enable;
        } else {
            throw new Exception('XHProf is started, not can set enable property.');
        }
    }

    /**
     * Start XHProf
     */
    public static function start()
    {
        self::$_isStarted = true;
        if (self::$_isEnabled && function_exists("xhprof_enable")) {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        }
    }

    /**
     * Finish XHProf
     */
    public static function finish()
    {
        if (self::$_isEnabled && function_exists("xhprof_disable")) {
            $xhprof_data = xhprof_disable();
            include_once self::getPath() . "/xhprof_lib/utils/xhprof_lib.php";
            include_once self::getPath() . "/xhprof_lib/utils/xhprof_runs.php";
            $xhprof_runs = new \XHProfRuns_Default();
            $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_testing");
            echo "
xhprof id: $run_id
";
        }
        self::$_isEnabled=false;
    }

    //put your code here
}


<?php
/**
 * DetailForm class
 *
 * @package
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */

namespace Openbizx\View;

use Openbizx\View\BaseForm;

 /*
  * public methods: fetchData, deleteRecord
  */
class DetailForm extends BaseForm
{
	//list of method that can directly from browser
	protected $directMethodList = array('deleterecord','switchform');

	public $recordId;
	public $activeRecord;

	// get request parameters from the url
	protected function getUrlParameters()
	{
		if (isset($_REQUEST['fld:Id'])) {
			$this->recordId = $_REQUEST['fld:Id'];
		}
	}

	public function render()
	{
		$this->getUrlParameters();
		return parent::render();
	}

	/**
     * Fetch single record
     *
     * @return array one record array
     */
    public function fetchData()
    {
        // if has valid active record, return it, otherwise do a query
        if ($this->activeRecord != null)
            return $this->activeRecord;

        $dataObj = $this->getDataObj();
        if ($dataObj == null) return;

        // TODO: use getDataById to fetch one record
		$dataRec = $dataObj->fetchById($this->recordId);
		return $dataRec->toArray();
    }

	/**
     * Delete Record
     * NOTE: use redirectpage attr of eventhandler to redirect or redirect to previous page by default
     *
     * @param string $id
     * @return void
     */
    public function deleteRecord($id)
	{
		$dataRec = $this->getDataObj()->fetchById($id);
		//$this->getDataObj()->setActiveRecord($dataRec);

		// take care of exception
		try {
			$dataRec->delete();
		} catch (Openbizx\Data\Exception $e) {
			// call $this->processDataException($e);
			$this->processDataException($e);
			return;
		}

        //$this->runEventLog();
        $this->processPostAction();
	}
}
?>


<?php declare(strict_types=1);

namespace ts\Reflection;

/**
 * @SuppressWarnings(PHPMD)
 */
class ReflectionClass
{
    use SelfReflectionTrait;

    /**
     * @var \ReflectionClass
     */
    private $reflectionClass;

    /**
     * ReflectionClass constructor.
     *
     * @param string $fqn
     *
     * @throws \ReflectionException
     */
    public function __construct(string $fqn)
    {
        $this->reflectionClass = new \ReflectionClass($fqn);
    }

    /**
     * @param string $fqn
     *
     * @return string
     */
    public static function export(string $fqn): string
    {
        return (string)\ReflectionClass::export($fqn, true);
    }

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

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

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

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

    public function isInstantiable(): bool
    {
        return $this->reflectionClass->isInstantiable();
    }

    public function isCloneable(): bool
    {
        return $this->reflectionClass->isCloneable();
    }

    public function getFileName(): string
    {
        $filename = $this->reflectionClass->getFileName();
        if (false === $filename) {
            throw new \RuntimeException('the reflection class does not have a filename');
        }

        return $filename;
    }

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

        return $result;
    }

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

        return $result;
    }

    public function getDocComment(): string
    {
        return (string)$this->reflectionClass->getDocComment();
    }

    public function getConstructor(): ReflectionMethod
    {
        $constructor = $this->reflectionClass->getConstructor();
        if (null === $constructor) {
            throw new \RuntimeException('Failed getting constructor in ' . __METHOD__);
        }

        return ReflectionMethod::constructFromReflectionMethod($constructor);
    }

    public function hasMethod(string $name): bool
    {
        return $this->reflectionClass->hasMethod($name);
    }

    public function getMethod(string $name): ReflectionMethod
    {
        $method = $this->reflectionClass->getMethod($name);

        return ReflectionMethod::constructFromReflectionMethod($method);
    }

    /**
     * @param int|null $filter
     *
     * @return array|ReflectionMethod[]
     * @throws \ReflectionException
     */
    public function getMethods(?int $filter = null): array
    {
        $methods = (null === $filter)
            ? $this->reflectionClass->getMethods()
            : $this->reflectionClass->getMethods($filter);
        $return  = [];
        foreach ($methods as $key => $method) {
            $return[$key] = ReflectionMethod::constructFromReflectionMethod($method);
        }

        return $return;
    }

    public function hasProperty(string $name): bool
    {
        return $this->reflectionClass->hasProperty($name);
    }

    public function getProperty(string $name): \ReflectionProperty
    {
        return $this->reflectionClass->getProperty($name);
    }

    /**
     * @param int|null $filter
     *
     * @return array|\ReflectionProperty[]
     */
    public function getProperties(?int $filter = null): array
    {
        return (null === $filter) ?
            $this->reflectionClass->getProperties()
            : $this->reflectionClass->getProperties($filter);
    }

    public function getReflectionConstant(string $name): \ReflectionClassConstant
    {
        $result = $this->reflectionClass->getReflectionConstant($name);
        if (false === $result) {
            throw new \RuntimeException('Failed getting constant ' . $name);
        }

        return $result;
    }

    /**
     * @return array|\ReflectionClassConstant[]
     */
    public function getReflectionConstants(): array
    {
        return $this->reflectionClass->getReflectionConstants();
    }

    public function hasConstant(string $name): bool
    {
        return $this->reflectionClass->hasConstant($name);
    }

    /**
     * @return array|string[]
     */
    public function getConstants(): array
    {
        return $this->reflectionClass->getConstants();
    }

    /**
     * @param string $name
     *
     * @return mixed
     */
    public function getConstant(string $name)
    {
        return $this->reflectionClass->getConstant($name);
    }

    /**
     * @return array|self[]
     * @throws \ReflectionException
     */
    public function getInterfaces(): array
    {
        return $this->convertArrayOfReflectionToSelf($this->reflectionClass->getInterfaces());
    }

    /**
     * Take an array of raw \ReflectionClass objects and return an array of self
     *
     * @param array $reflectionClasses
     *
     * @return array|self[]
     * @throws \ReflectionException
     */
    private function convertArrayOfReflectionToSelf(array $reflectionClasses): array
    {
        $return = [];
        foreach ($reflectionClasses as $key => $reflectionClass) {
            $return[$key] = self::constructFromReflectionClass($reflectionClass);
        }

        return $return;
    }

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

        return $instance;
    }

    /**
     * @return array|string[]
     */
    public function getInterfaceNames(): array
    {
        return $this->reflectionClass->getInterfaceNames();
    }

    public function isAnonymous(): bool
    {
        return $this->reflectionClass->isAnonymous();
    }

    public function isInterface(): bool
    {
        return $this->reflectionClass->isInterface();
    }

    /**
     * @return array|self[]
     * @throws \ReflectionException
     */
    public function getTraits(): array
    {
        return $this->convertArrayOfReflectionToSelf($this->reflectionClass->getTraits());
    }

    /**
     * @return array|string[]
     */
    public function getTraitNames(): array
    {
        return $this->reflectionClass->getTraitNames();
    }

    public function getTraitAliases(): array
    {
        return $this->reflectionClass->getTraitAliases();
    }

    public function isTrait(): bool
    {
        return $this->reflectionClass->isTrait();
    }

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

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

    public function getModifiers(): int
    {
        return $this->reflectionClass->getModifiers();
    }

    /**
     * @param mixed $object
     *
     * @return bool
     */
    public function isInstance($object): bool
    {
        return $this->reflectionClass->isInstance($object);
    }

    /**
     * @param mixed ...$args
     *
     * @return object
     */
    public function newInstance(...$args): object
    {
        return $this->reflectionClass->newInstance(...$args);
    }

    /**
     * @return object
     */
    public function newInstanceWithoutConstructor()
    {
        return $this->reflectionClass->newInstanceWithoutConstructor();
    }

    /**
     * @param array|null $args
     *
     * @return object
     */
    public function newInstanceArgs(array $args = null)
    {
        return $this->reflectionClass->newInstanceArgs($args ?? []);
    }

    /**
     * @return self
     * @throws \ReflectionException
     */
    public function getParentClass(): self
    {
        $parent = $this->reflectionClass->getParentClass();
        if (false === $parent) {
            throw new \RuntimeException('reflection class does not have a parent');
        }

        return self::constructFromReflectionClass($parent);
    }

    public function isSubclassOf(string $class): bool
    {
        return $this->reflectionClass->isSubclassOf($class);
    }

    public function getStaticProperties(): array
    {
        return $this->reflectionClass->getStaticProperties();
    }

    /**
     * @param string $name
     * @param mixed  $default
     *
     * @return mixed
     */
    public function getStaticPropertyValue(string $name, $default = null)
    {
        return $this->reflectionClass->getStaticPropertyValue($name, $default);
    }

    /**
     * @param string $name
     * @param mixed  $value
     */
    public function setStaticPropertyValue(string $name, $value): void
    {
        $this->reflectionClass->setStaticPropertyValue($name, $value);
    }

    public function getDefaultProperties(): array
    {
        return $this->reflectionClass->getDefaultProperties();
    }

    public function isIterateable(): bool
    {
        return $this->reflectionClass->isIterateable();
    }

    public function isIterable(): bool
    {
        return $this->reflectionClass->isIterable();
    }

    public function implementsInterface(string $interface): bool
    {
        return $this->reflectionClass->implementsInterface($interface);
    }

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

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

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

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

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


<?php

namespace Interpro\Entrance\Agents;

use Illuminate\Support\Facades\App;
use Interpro\Core\Contracts\Mediator\SyncMediator;
use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Entrance\Contracts\CommandAgent\SyncAgent as SyncAgentInterface;
use Interpro\Entrance\Exception\EntranceException;
use Symfony\Component\Console\Output\ConsoleOutput;

class SyncAgent implements SyncAgentInterface
{
    private $syncMediator;
    private $taxonomy;
    private $consoleOutput;
    private $inConsole = false;

    public function __construct(
        SyncMediator $syncMediator,
        Taxonomy $taxonomy,
        ConsoleOutput $consoleOutput
    )
    {
        $this->syncMediator = $syncMediator;
        $this->taxonomy     = $taxonomy;
        $this->consoleOutput = $consoleOutput;

        $this->inConsole = App::runningInConsole();
    }

    private function syncType(AType $type)
    {
        $typeMode = $type->getMode();

        if($typeMode !== TypeMode::MODE_A)
        {
            throw new EntranceException('Агент синхронизации может синхронизировать только тип (A) уровня, передан тип:'.$type->getName().'('.$typeMode.')!');
        }

        $family = $type->getFamily();

        $synchronizer = $this->syncMediator->getASynchronizer($family);

        $synchronizer->sync($type);
    }

    /**
     * @param string $type_name
     *
     * @return void
     */
    public function sync($type_name)
    {
        if(!is_string($type_name))
        {
            throw new EntranceException('Имя типа должно быть задано строкой!');
        }

        $type = $this->taxonomy->getType($type_name);

        $this->syncType($type);
    }

    /**
     * @return void
     */
    public function syncPredefinedGroupItems()
    {
        $this->syncMediator->syncPredefinedGroupItems();
    }

    /**
     * @return void
     */
    public function syncAll()
    {
        $blocks = $this->taxonomy->getBlocks();

        foreach($blocks as $block)
        {
            $this->syncType($block);

            if($this->inConsole)
            {
                $this->consoleOutput->writeln('Синхронизирован тип '.$block->getName());
            }
        }

        $groups = $this->taxonomy->getGroups();

        foreach($groups as $group)
        {
            $this->syncType($group);

            if($this->inConsole)
            {
                $this->consoleOutput->writeln('Синхронизирован тип '.$group->getName());
            }
        }
    }

}


<?php

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

namespace Openbizx\Data\Tools;

use Openbizx\Openbizx;
use Openbizx\Object\MetaIterator;

/**
 * BizRecord class implements basic function of handling record
 *
 * @package openbiz.bin.data.private
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 */
class BizRecord extends MetaIterator
{

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

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

    /**
     *
     * @var array
     */
    public $inputFields;
    protected $ignoreInQuery = false;

    /**
     * Initialize BizRecord with xml array
     *
     * @param array $xmlArr array data from xml file
     * @param string $className name of the class of the object
     * @param object $parentObj parent object
     * @return void
     */
    function __construct(&$xmlArr, $className, $parentObj = null)
    {
        parent::__construct($xmlArr, $className, $parentObj);
        $this->_initSetup();
    }

    /**
     * Merge with another BizRecord object. Used in metedata inheritance.
     *
     * @param BizRecord $anotherMIObj to be merged BizRecord object
     * @return void
     */
    public function merge(&$anotherMIObj)
    {
        parent::merge($anotherMIObj);
        $this->_initSetup();
    }

    /**
     * Do some initial setup work
     *
     * @return void
     */
    private function _initSetup()
    {
        unset($this->columnFieldMap);
        $this->columnFieldMap = array();
        unset($this->keyFieldColumnMap);
        $this->keyFieldColumnMap = array();
        $i = 0;
        // generate column index if the column is one of the basetable (column!="")
        foreach ($this->varValue as $key => $field) {  // $key is fieldname, $field is fieldobj
            ////////////////////////////////////////////////////////////////////
            // TODO: join fields and nonjoin fields may have same column name
            ////////////////////////////////////////////////////////////////////
            if (isset($field->column) && !isset($field->join) ) {  // ignore the joined field column
                $this->columnFieldMap[$field->column] = $key;
            }
            if (isset($field->column) || isset($field->sqlExpression)) {
                $field->index = $i++;
            }
        }
        // create key field column map to support composite key
        if (isset($this->varValue["Id"]) && $this->varValue["Id"]->column) {
            $keycols = explode(",", $this->varValue["Id"]->column);
            foreach ($keycols as $col) {
                $field = $this->getFieldByColumn($col);  // main table
                $this->keyFieldColumnMap[$field] = $col;
            }
        }
    }

    /**
     * Get fielf by column name
     *
     * @param string $column column name
     * @param string $table table name
     * @return BizField instant of {@link BizField}
     */
    public function getFieldByColumn($column, $table = null)
    {
        // TODO: 2 columns can have the same name in case of joined fields
        if (isset($this->columnFieldMap[$column])) {
            return $this->columnFieldMap[$column];
        }
        return null;
    }

    /**
     * Get an empty record array. Called by {@link BizDataObj::newRecord()}
     *
     * @return array record array
     * */
    final public function getEmptyRecordArr()
    {
        $recArr = array();
        foreach ($this->varValue as $key => $field) {
            $recArr[$key] = $field->getDefaultValue();
        }
        return $recArr;
    }

    /**
     * Get key (Id) value.
     * If Id is defined as composite key, the returned key value
     * is the combination of key columns
     *
     * @param boolean $isUseOldValue
     * @return string key field string
     * */
    final public function getKeyValue($isUseOldValue = false)
    {
        $keyValue = "";
        foreach ($this->keyFieldColumnMap as $fieldName => $colName) {
            $val = $isUseOldValue ? $this->varValue[$fieldName]->oldValue : $this->varValue[$fieldName]->value;
            if ($keyValue == "")
                $keyValue .= $val;
            else
            // use base64 (a-zA-Z1-9+-) to encode the key and connect them with "#"
                $keyValue .= CK_CONNECTOR . $val;
        }
        return $keyValue;
    }

    /**
     * Get a list of fields (name) who are defined as keys columns
     *
     * @return array array of key fields
     * */
    final public function getKeyFields()
    {
        $keyFields = array();
        foreach ($this->keyFieldColumnMap as $fieldName => $colName) {
            $keyFields[$fieldName] = $this->varValue[$fieldName];
        }
        return $keyFields;
    }

    /**
     * Get key search rule.
     * The key search rule is used to find a single record by given key values
     *
     * @param boolean $isUseOldValue true if old key value is used in the search rule
     * @param boolean $isUseColumnName true if column name is used in the search rule, false if [field] is used
     * @return string search rule
     */
    public function getKeySearchRule($isUseOldValue = false, $isUseColumnName = false)
    {
        $keyFields = $this->getKeyFields();
        $retStr = "";
        foreach ($keyFields as $fieldName => $fieldObj) {
            if ($retStr != "")
                $retStr .= " AND ";
            $lhs = $isUseColumnName ? $fieldObj->column : "[$fieldName]";
            $rhs = $isUseOldValue ? $fieldObj->oldValue : $fieldObj->value;
            if ($rhs == "")
                $retStr .= "(" . $lhs . "='" . $rhs . "' or " . $lhs . " is null)";
            else
                $retStr .= $lhs . "='" . $rhs . "'";
        }
        return $retStr;
    }

    /**
     * Set record array to internal data structure
     *
     * @param array $recArr record array
     * @return void
     */
    public function setRecordArr($recArr)
    {
        if (!$recArr) {
            return;
        }
        foreach ($this->varValue as $key => $field) {
            if ( isset($recArr[$key]) ) {
                $recArr[$key] = $field->setValue($recArr[$key]);
            }
        }
    }

    /**
     * Assign a record array as the internal record of the {@link BizRecord}
     *
     * @param array $inpuArr
     * @return void
     */
    final public function setInputRecord(&$inputArr)
    {
        // unformat the inputs
        unset($this->inputFields);
        foreach ($inputArr as $key => $value) {
            // if allow changing key field, need to keep the old value which is also useful for audit trail
            // if (!$value)
            //    continue;
            $bizField = $this->varValue[$key];
            if (!$bizField) {
                continue;
            }

            $realVal = Openbizx::$app->getTypeManager()->formattedStringToValue($bizField->type, $bizField->format, $value);
            if (strtoupper($bizField->encrypted) == 'Y') {
                $svcobj = Openbizx::getService(CRYPT_SERVICE);
                $realVal = $svcobj->encrypt($realVal);
                $bizField->setValue($realVal);
            }
            // todo: need to optimize on lob column
            $bizField->setValue($realVal);

            $this->inputFields[] = $key;
        }
        //$this->varValue["Id"]->setValue($this->getKeyValue());
    }

    /**
     * Save old recrod,
     * used in update record when old record value is needed in the action
     *
     * @param array $inputArr old record array
     * @return avoid
     */
    final public function saveOldRecord(&$inputArr)
    {
        if (!$inputArr)
            return;
        foreach ($inputArr as $key => $value) {
            $bizField = $this->varValue[$key];
            if (!$bizField)
                continue;
            $bizField->saveOldValue($value);
        }
    }

    /**
     * Get record array by converting input indexed-Value array to Field-Value pairs
     *
     * @param array $sqlArr column value pair array
     * @return array record array
     * */
    final public function getRecordArr($sqlArr = null)
    {
        if ($sqlArr) {
            $this->_setSqlRecord($sqlArr);
        }
        $recArr = array();
        foreach ($this->varValue as $key => $field) {
            if ($field->encrypted == 'Y') {
                $svcobj = Openbizx::getService(CRYPT_SERVICE);
                $value = $svcobj->decrypt($field->getValue());
                $recArr[$key] = $value;
            } else {
                $recArr[$key] = $field->getValue();
            }
        }
        return $recArr;
    }

    /**
     * Conver sql array to record array
     *
     * @param array $sqlArr indexed-value pair array
     * @return array field-value record array
     */
    public function convertSqlArrToRecArr($sqlArr)
    {
        $recArr = array();
        /* @var $field BizField */
        foreach ($this->varValue as $key => $field) {
            if ($field->column || $field->sqlExpression) {
                $recArr[$key] = $sqlArr[$field->index];
            } else {
                $recArr[$key] = "";
            }
        }
        return $recArr;
    }

    /**
     * Set sql record array to internal data
     *
     * @param array $sqlArr indexed-value array from sql result
     * @return avoid
     */
    private function _setSqlRecord($sqlArr)
    {
        foreach ($this->varValue as $key => $field) {
            if ($field->column || $field->sqlExpression) {
                $field->setValue($sqlArr[$field->index]);
            }
        }
        if (isset($this->varValue["Id"]))
            $this->varValue["Id"]->setValue($this->getKeyValue());
    }

    /**
     * Get join input record
     *
     * @param <type> $join
     * @return array
     */
    public function getJoinInputRecord($join)
    {
        $inputFields = $this->inputFields;  // Added by Jixian on 2009-02-15 for implement onSaveDataObj
        $recArr = array();
        foreach ($this->varValue as $key => $value) {
            // do not consider joined columns
            // Added by Jixian on 2009-02-15 for implement onSaveDataObj
            /*
             * It's the time to consider about joined columns
             */

            $field = $value;

            if ($field->join == $join) {
                $recArr[$key] = $value;
            }
        }
        return $recArr;
    }

    /**
     * Get join search rule
     *
     * NOTE: Added by Jixian on 2009-02-16 for implement onSaveDataObj
     *
     * @param TableJoin $tableJoin
     * @param boolean $isUseOldValue
     * @return string
     */
    public function getJoinSearchRule($tableJoin, $isUseOldValue = false)
    {
        $joinFieldName = $this->getFieldByColumn($tableJoin->columnRef, $tableJoin->table);
        $joinField = $this->varValue[$joinFieldName];
        $rhs = $isUseOldValue ? $joinField->oldValue : $joinField->value;
        $retStr = $tableJoin->column . "='" . $rhs . "'";
        return $retStr;
    }

    /**
     * Get insert/update fields.
     * Ignore unchanged field in UPDATE case
     *
     * @return array field value pair array
     * */
    final public function getToSaveFields($type)
    {
        // TODO: if join != null, get columns only for the join
        $sqlFields = array();

        // expand input fields with oncreate or onupdate fields
        $inputFields = $this->inputFields;
        foreach ($this->varValue as $key => $field) {
            if (($type == 'UPDATE' && $field->valueOnUpdate != null) || ($type == 'CREATE' && $field->valueOnCreate != null)) {
                if (!in_array($key, $this->inputFields))
                    $inputFields[] = $key;
            }
        }

        foreach ($inputFields as $key) {
            // ignore the composite key Id field
            if ($key == "Id" && count($this->keyFieldColumnMap) > 1)
                continue;
            $field = $this->varValue[$key];
            // do not consider joined columns
            if ($field->column && !$field->join) {
                $sqlFields[] = $field;
            }
        }
        return $sqlFields;
    }

}

?>


<?php

namespace Interpro\QS\Executors;

use Interpro\Core\Contracts\Executor\RefConsistExecutor as RefConsistExecutorInterface;
use Interpro\Core\Contracts\Ref\ARef;
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 RefConsistExecutor implements RefConsistExecutorInterface
{
    /**
     * @return string
     */
    public function getFamily()
    {
        return 'qs';
    }

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

        $collection = Ref::where('ref_entity_name', '=', $type_name)->where('ref_entity_id', '=', $id)->get();

        foreach($collection as $refModel)
        {
            //Обнуляем все ссылки, для блока это смысла не имеет, но блок может быть без записей в бд, просто как опорная сущность, так что ссылаться на него можно
            $refModel->ref_entity_id = 0;
            $refModel->save();
        }
    }

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

        $id = $ref->getId();

        $type_rank = $type->getRank();

        if($type_rank === TypeRank::BLOCK)
        {
            $collection = Block::where('name', $type_name)->get();
        }
        elseif($type_rank === TypeRank::GROUP)
        {
            $collection = Group::where('name', $type_name)->where('id', $id)->get();
        }
        else
        {
            throw new QSException('Не корректный ранг типа '.$type_name.' ссылки!');
        }

        return !$collection->isEmpty();
    }
}


<?php

namespace SetBased\Abc\Request;

/**
 * Class providing information about an HTTP request.
 *
 * It provides an interface to retrieve request parameters from
 *

 *
$_SERVER resolving inconsistency among different web servers
 *
$_POST
 *
$_COOKIES
 *
REST parameters sent via other HTTP methods
 *

 */
class CoreRequest implements Request
{
  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns the method of the current request.
   *
   * @return string
   *
   * @api
   * @since 1.0.0
   */
  public function getMethod(): string
  {
    if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
    {
      return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
    }

    if (isset($_SERVER['REQUEST_METHOD']))
    {
      return strtoupper($_SERVER['REQUEST_METHOD']);
    }

    return 'GET';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns the remote IP (this is always the next hop, not necessarily the user's IP address).
   *
   * @return string|null
   *
   * @api
   * @since 1.0.0
   */
  public function getRemoteIp(): ?string
  {
    return $_SERVER['REMOTE_ADDR'] ?? null;
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns the requested relative URL after. It includes the query part if any.
   *
   * @return string
   *
   * @api
   * @since 1.0.0
   */
  public function getRequestUri(): string
  {
    if (isset($_SERVER['REQUEST_URI']))
    {
      $requestUri = $_SERVER['REQUEST_URI'];
      if ($requestUri!=='' && $requestUri[0]!=='/')
      {
        $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
      }

      return $requestUri;
    }

    throw new \LogicException('Unable to resolve requested URI');
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns the user agent.
   *
   * @return string|null
   *
   * @api
   * @since 1.0.0
   */
  public function getUserAgent(): ?string
  {
    return $_SERVER['HTTP_USER_AGENT'] ?? null;
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is an AJAX (XMLHttpRequest) request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isAjax(): bool
  {
    return (($_SERVER['HTTP_X_REQUESTED_WITH']) ?? '')==='XMLHttpRequest';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a DELETE request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isDelete(): bool
  {
    return $this->getMethod()==='DELETE';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if the current environment is a development environment.
   *
   * @return bool
   */
  public function isEnvDev(): bool
  {
    return ($_SERVER['ABC_ENV']==='dev');
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if the current environment is a production environment.
   *
   * @return bool
   */
  public function isEnvProd(): bool
  {
    return ($_SERVER['ABC_ENV']==='prod');
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a GET request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isGet(): bool
  {
    return $this->getMethod()==='GET';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a HEAD request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isHead(): bool
  {
    return $this->getMethod()==='HEAD';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a OPTIONS request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isOptions(): bool
  {
    return $this->getMethod()==='OPTIONS';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a PATCH request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isPatch(): bool
  {
    return $this->getMethod()==='PATCH';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a POST request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isPost(): bool
  {
    return $this->getMethod()==='POST';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Returns true if this is a PUT request. Otherwise returns false.
   *
   * @return bool
   *
   * @api
   * @since 1.0.0
   */
  public function isPut(): bool
  {
    return $this->getMethod()==='PUT';
  }

  //--------------------------------------------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------------------------------------------


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

namespace DoctrineModule\Service;

use RuntimeException;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Base ServiceManager factory to be extended
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @author  Kyle Spraggs <theman@spiffyjr.me>
 */
abstract class AbstractFactory implements FactoryInterface
{
    /**
     * Would normally be set to orm | odm
     *
     * @var string
     */
    protected $mappingType;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var \Zend\Stdlib\AbstractOptions
     */
    protected $options;

    /**
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

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

    /**
     * Would normally be set to orm | odm
     *
     * @return string
     */
    public function getMappingType()
    {
        return $this->mappingType;
    }

    /**
     * Gets options from configuration based on name.
     *
     * @param  ServiceLocatorInterface      $sl
     * @param  string                       $key
     * @param  null|string                  $name
     * @return \Zend\Stdlib\AbstractOptions
     * @throws \RuntimeException
     */
    public function getOptions(ServiceLocatorInterface $sl, $key, $name = null)
    {
        if ($name === null) {
            $name = $this->getName();
        }

        $options = $sl->get('Configuration');
        $options = $options['doctrine'];
        if ($mappingType = $this->getMappingType()) {
            $options = $options[$mappingType];
        }
        $options = isset($options[$key][$name]) ? $options[$key][$name] : null;

        if (null === $options) {
            throw new RuntimeException(
                sprintf(
                    'Options with name "%s" could not be found in "doctrine.%s".',
                    $name,
                    $key
                )
            );
        }

        $optionsClass = $this->getOptionsClass();

        return new $optionsClass($options);
    }

    /**
     * Get the class name of the options associated with this factory.
     *
     * @abstract
     * @return string
     */
    abstract public function getOptionsClass();
}


<?php

namespace Askedio\Laravelcp\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class VerifyRole
{
    /**
     * @var \Illuminate\Contracts\Auth\Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param \Illuminate\Contracts\Auth\Guard $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param int|string $role
     * @return view
     */
    public function handle($request, Closure $next, $role)
    {
        if ($this->auth->check() && $this->auth->user()->is($role)) {
            return $next($request);
        }

       return $this->auth->check() ?
         view('lcp::auth.errors.role')->withError($role) :
         view('lcp::auth.login');
    }
}


<?php
/**
 * OAuth 2.0 MAC Token Type
 *
 */

namespace OAuth2\Server\TokenType;

use OAuth2\Server\Util\SecureKey;
use OAuth2\Server\Request\HandlerInterface as RequestHandler;
/**
 * MAC Token Type
 */
class MAC extends AbstractTokenType implements TokenTypeInterface
{
    /**
     * {@inheritdoc}
     */
    public function generateResponse()
    {
        $macKey = SecureKey::generate();
        $this->server->getMacStorage()->create($macKey, $this->getParam('access_token'));

        $response = [
            'access_token'  =>  $this->getParam('access_token'),
            'token_type'    =>  'mac',
            'expires_in'    =>  $this->getParam('expires_in'),
            'mac_key'       =>  $macKey,
            'mac_algorithm' =>  'hmac-sha-256',
        ];

        return $response;
    }

    /**
     * {@inheritdoc}
     */
    public function determineAccessTokenInHeader(RequestHandler $requestHandler,$authHeader = 'Authorization')
    {
        $header = $requestHandler->getHeader($authHeader);

		if ($header === null){
			return;
		}

        if (substr($header, 0, 4) !== 'MAC ') {
            return;
        }

        // Find all the parameters expressed in the header
        $paramsRaw = explode(',', substr($header, 4));
        $params = array();

        array_map(function ($param) use (&$params) {
            $param = trim($param);

            preg_match_all('/([a-zA-Z]*)="([\w=]*)"/', $param, $matches);

            // @codeCoverageIgnoreStart
            if (count($matches) !== 3) {
                return;
            }
            // @codeCoverageIgnoreEnd

            $key = reset($matches[1]);
            $value = trim(reset($matches[2]));

            if (empty($value)) {
                return;
            }

            $params[$key] = $value;
        }, $paramsRaw);

        // Validate parameters
        if (array_key_exists('id',$params) === false || array_key_exists('ts',$params) === false || array_key_exists('nonce',$params) === false || array_key_exists('mac',$params) === false) {
            return;
        }

        if ((int) $params['ts'] !== time()) {
            return;
        }

        $accessToken = $params['id'];
        $timestamp = (int) $params['ts'];
        $nonce = $params['nonce'];
        $signature = $params['mac'];

        // Try to find the MAC key for the access token
        $macKey = $this->server->getMacStorage()->getByAccessToken($accessToken);

        if ($macKey === null) {
            return;
        }

        // Calculate and compare the signature
        $calculatedSignatureParts = [
            $timestamp,
            $nonce,
            strtoupper($requestHandler->getMethod()),
            $requestHandler->getUri(),
			$requestHandler->getHost(),
			$requestHandler->getPort(),
        ];

        if (array_key_exists('ext',$params)) {
            $calculatedSignatureParts[] = $params['ext'];
        }

        $calculatedSignature = base64_encode(hash_hmac('sha256', implode("\n", $calculatedSignatureParts), $macKey));

        // Return the access token if the signature matches
        return ($this->hash_equals($calculatedSignature, $signature)) ? $accessToken : null;
    }

    /**
     * Prevent timing attack
     * @param  string $knownString
     * @param  string $userString
     * @return bool
     */
    private function hash_equals($knownString, $userString)
    {
        if (function_exists('\hash_equals')) {
            return \hash_equals($knownString, $userString);
        }
        if (strlen($knownString) !== strlen($userString)) {
            return false;
        }
        $len = strlen($knownString);
        $result = 0;
        for ($i = 0; $i < $len; $i++) {
            $result |= (ord($knownString[$i]) ^ ord($userString[$i]));
        }
        // They are only identical strings if $result is exactly 0...
        return 0 === $result;
    }
}


<?php namespace Interpro\QuickStorage\Laravel\Handle;

use Illuminate\Support\Facades\DB;
use Interpro\ImageFileLogic\Concept\ImageLogicAgent;
use Interpro\QuickStorage\Concept\Command\CreateGroupItemCommand;
use Interpro\QuickStorage\Concept\StorageStructure;
use Interpro\QuickStorage\Laravel\Model\Block;
use Interpro\QuickStorage\Laravel\Model\Bool;
use Interpro\QuickStorage\Laravel\Model\Imageitem;
use Interpro\QuickStorage\Laravel\Model\Numb;
use Interpro\QuickStorage\Laravel\Model\Pdatetime;
use Interpro\QuickStorage\Laravel\Model\Stringfield;
use Interpro\QuickStorage\Laravel\Model\Textfield;

class CreateGroupItemCommandHandler {

    private $storageStructure;
    private $imageLogicAgent;

    /**
     * Create the command handler.
     *
     * @return void
     */
    public function __construct(StorageStructure $storageStructure, ImageLogicAgent $imageLogicAgent)
    {
        $this->storageStructure = $storageStructure;
        $this->imageLogicAgent = $imageLogicAgent;
    }

    /**
     * Handle the command.
     *
     * @param  CreateGroupItemCommand  $command
     * @return array
     */
    public function handle(CreateGroupItemCommand $command)
    {
        return $this->createGroupItem($command->block_name, $command->group_name, $command->owner_id);
    }

    public function createGroupItem($block_name, $group_name, $owner_id)
    {
        $block = Block::find($block_name);

        if($block)
        {
            $groupstruct_invert = $this->storageStructure->getGroupsSub9n($block_name);

            $dataArr = ['sorter' => 99,'show' => true];

            $groupstruct = config('qstorage')[$block_name]['groups'][$group_name];

            $newGroupItem = new \Interpro\QuickStorage\Laravel\Model\Group();
            $newGroupItem->block_name = $block_name;
            $newGroupItem->group_name = $group_name;
            $newGroupItem->owner_id   = $owner_id;
            $newGroupItem->save();

            $dataArr['id']         = $newGroupItem->id;
            $dataArr['owner_id']   = $newGroupItem->owner_id;
            $dataArr['block_name'] = $block_name;
            $dataArr['group_name'] = $group_name;

            //По умолчанию предлагаем заполнять слаг этим:
            $dataArr['slug'] = '';

            if(array_key_exists('stringfields', $groupstruct))
            {
                foreach($groupstruct['stringfields'] as $fieldname)
                {
                    $stringfield = Stringfield::create(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                    $stringfield->value = '';
                    $newGroupItem->stringfields()->save($stringfield);
                    $dataArr[$fieldname] = $stringfield->value;
                }
            }

            if(array_key_exists('textfields', $groupstruct))
            {
                foreach($groupstruct['textfields'] as $fieldname)
                {
                    $textfield = Textfield::firstOrNew(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                    $textfield->value = '';
                    $newGroupItem->textfields()->save($textfield);
                    $dataArr[$fieldname] = $textfield->value;
                }
            }

            if(array_key_exists('numbs', $groupstruct))
            {
                foreach($groupstruct['numbs'] as $fieldname)
                {
                    $numb = Numb::firstOrNew(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                    $newGroupItem->numbs()->save($numb);
                    $dataArr[$fieldname] = 0;
                }
            }

            if(array_key_exists('bools', $groupstruct))
            {
                foreach($groupstruct['bools'] as $fieldname)
                {
                    $boolitem = Bool::firstOrNew(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                    $newGroupItem->bools()->save($boolitem);
                    $dataArr[$fieldname] = false;
                }
            }

            if(array_key_exists('pdatetimes', $groupstruct))
            {
                foreach($groupstruct['pdatetimes'] as $fieldname)
                {
                    $dtitem = Pdatetime::firstOrNew(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);
                    $dtitem->value = new \DateTime();
                    $newGroupItem->pdatetimes()->save($dtitem);
                    $dataArr[$fieldname]= $dtitem->value->format('d.m.Y H:i:s');
                }
            }

            if(array_key_exists('images', $groupstruct))
            {
                foreach($groupstruct['images'] as $fieldname)
                {
                    $image = Imageitem::firstOrNew(['block_name'=>$block_name, 'group_name'=>$group_name, 'name'=>$fieldname, 'group_id'=>$newGroupItem->id]);

                    $image_name = $group_name.'_'.$fieldname;

                    $image->preview_link   = $this->imageLogicAgent->getPlaceholder($image_name, 'preview');
                    $image->primary_link   = $this->imageLogicAgent->getPlaceholder($image_name, 'primary');
                    $image->original_link  = $this->imageLogicAgent->getPlaceholder($image_name, 'primary');
                    $image->secondary_link = $this->imageLogicAgent->getPlaceholder($image_name, 'secondary');
                    $image->icon_link      = $this->imageLogicAgent->getPlaceholder($image_name, 'icon');

                    $newGroupItem->images()->save($image);
                    $dataArr[$fieldname]='';
                }
            }
            $newGroupItem->save();

            //Присваеваем полю сортировщика +1
            $query = \Interpro\QuickStorage\Laravel\Model\Group::query();
            $query->where('id', '=', $newGroupItem->id);
            $query->where('owner_id', '=', $owner_id);
            $query->where('group_name', '=', $group_name);

            $sorter_query = \Interpro\QuickStorage\Laravel\Model\Group::selectRaw('MAX(sorter)+1 AS next_sorter, owner_id as o_id')
                ->whereRaw('owner_id = '.$owner_id)->whereRaw('group_name = "'.$group_name.'"');

            $query->leftJoin(DB::raw('('.$sorter_query->toSql().') AS srt'), function($join)
            {
                $join->on('srt.o_id', '=', 'owner_id');
            });

            $query->update(['sorter' => DB::raw('srt.next_sorter')]);
            //--------------------------------------------------------------

            $dataArr['groups'] = array_fill_keys($groupstruct_invert[$group_name], []);

            return $dataArr;

        }else{

            throw new \Exception('Не нашел блок по имени '.$block_name);
        }
    }

}


<?php

namespace Limber\Container;

class Singleton extends ContainerBuilder
{
    /**
     * Singleton instance.
     *
     * @var mixed
     */
    protected $instance;

    /**
     * Get or make the singleton instance.
     *
     * @return mixed
     */
    public function make()
    {
        if( !$this->instance ){
            $this->instance = call_user_func($this->builder);
        }

        return $this->instance;
    }
}


<?php
/**
 * OAuth 2.0 Authorization Server
 *
 */

namespace OAuth2\Server;

use OAuth2\Server\Grant\GrantTypeInterface;

/**
 * OAuth 2.0 authorization server class
 */
class AuthorizationServer extends AbstractServer
{
    /**
     * The delimiter between scopes specified in the scope query string parameter
     * The OAuth 2 specification states it should be a space but most use a comma
     *
     * @var string
     */
    protected $scopeDelimiter = ',';

    /**
     * The TTL (time to live) of an access token in seconds (default: 3600)
     *
     * @var integer
     */
    protected $accessTokenTTL = 3600;

    /**
     * The registered grant response types
     *
     * @var array
     */
    protected $responseTypes = [];

    /**
     * The registered grant types
     *
     * @var array
     */
    protected $grantTypes = [];

    /**
     * Require the "scope" parameter to be in checkAuthoriseParams()
     *
     * @var boolean
     */
    protected $requireScopeParam = false;

    /**
     * Default scope(s) to be used if none is provided
     *
     * @var string|array
     */
    protected $defaultScope;

    /**
     * Require the "state" parameter to be in checkAuthoriseParams()
     *
     * @var boolean
     */
    protected $requireStateParam = false;

    /**
     * Enable support for a grant
     *
     * @param GrantTypeInterface $grantType  A grant class which conforms to Interface/GrantTypeInterface
     * @param null|string        $identifier An identifier for the grant (autodetected if not passed)
     *
     * @return self
     */
    public function addGrantType(GrantTypeInterface $grantType, $identifier = null)
    {
        if (is_null($identifier)) {
            $identifier = $grantType->getIdentifier();
        }

        // Inject server into grant
        $grantType->setAuthorizationServer($this);

        $this->grantTypes[$identifier] = $grantType;

        if (!is_null($grantType->getResponseType())) {
            $this->responseTypes[] = $grantType->getResponseType();
        }

        return $this;
    }

    /**
     * Check if a grant type has been enabled
     *
     * @param string $identifier The grant type identifier
     *
     * @return boolean Returns "true" if enabled, "false" if not
     */
    public function hasGrantType($identifier)
    {
        return (array_key_exists($identifier, $this->grantTypes));
    }

    /**
     * Returns response types
     *
     * @return array
     */
    public function getResponseTypes()
    {
        return $this->responseTypes;
    }

    /**
     * Require the "scope" parameter in checkAuthoriseParams()
     *
     * @param boolean $require
     *
     * @return self
     */
    public function requireScopeParam($require = true)
    {
        $this->requireScopeParam = $require;

        return $this;
    }

    /**
     * Is the scope parameter required?
     *
     * @return bool
     */
    public function scopeParamRequired()
    {
        return $this->requireScopeParam;
    }

    /**
     * Default scope to be used if none is provided and requireScopeParam() is false
     *
     * @param string $default Name of the default scope
     *
     * @return self
     */
    public function setDefaultScope($default = null)
    {
        $this->defaultScope = $default;

        return $this;
    }

    /**
     * Default scope to be used if none is provided and requireScopeParam is false
     *
     * @return string|null
     */
    public function getDefaultScope()
    {
        return $this->defaultScope;
    }

    /**
     * Require the "state" parameter in checkAuthoriseParams()
     *
     * @return bool
     */
    public function stateParamRequired()
    {
        return $this->requireStateParam;
    }

    /**
     * Require the "state" parameter in checkAuthoriseParams()
     *
     * @param boolean $require
     *
     * @return self
     */
    public function requireStateParam($require = true)
    {
        $this->requireStateParam = $require;

        return $this;
    }

    /**
     * Get the scope delimiter
     *
     * @return string The scope delimiter (default: ",")
     */
    public function getScopeDelimiter()
    {
        return $this->scopeDelimiter;
    }

    /**
     * Set the scope delimiter
     *
     * @param string $scopeDelimiter
     *
     * @return self
     */
    public function setScopeDelimiter($scopeDelimiter = ' ')
    {
        $this->scopeDelimiter = $scopeDelimiter;

        return $this;
    }

    /**
     * Get the TTL for an access token
     *
     * @return int The TTL
     */
    public function getAccessTokenTTL()
    {
        return $this->accessTokenTTL;
    }

    /**
     * Set the TTL for an access token
     *
     * @param int $accessTokenTTL The new TTL
     *
     * @return self
     */
    public function setAccessTokenTTL($accessTokenTTL = 3600)
    {
        $this->accessTokenTTL = $accessTokenTTL;

        return $this;
    }

    /**
     * Issue an access token
     *
     * @return array Authorise request parameters
     *
     * @throws
     */
    public function issueAccessToken()
    {
        $grantType = $this->requestHandler->getParam('grant_type');
        if (is_null($grantType)) {
            throw new Exception\InvalidRequestException('grant_type');
        }

        // Ensure grant type is one that is recognised and is enabled
        if (!in_array($grantType, array_keys($this->grantTypes))) {
            throw new Exception\UnsupportedGrantTypeException($grantType);
        }

        // Complete the flow
        return $this->getGrantType($grantType)->grant();
    }

    /**
     * Return a grant type class
     *
     * @param string $grantType The grant type identifier
     *
     * @return Grant\GrantTypeInterface
     *
     * @throws
     */
    public function getGrantType($grantType)
    {
        if (isset($this->grantTypes[$grantType])) {
            return $this->grantTypes[$grantType];
        }

        throw new Exception\InvalidGrantException($grantType);
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Modules\Assets;

use Nameless\Core\Container;
use Nameless\Utilities\PathHelper;

/**
 * AssetsDispatcher class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
//TODO: don`t compress .min. files
class AssetsDispatcher
{
    /**
     * @var Container
     */
    protected $container;

    /**
     * @var array
     */
    protected $templates = [
        'css'  => '<link href="%s" rel="stylesheet" type="text/css" />',
        'less' => '<link href="%s" rel="stylesheet/less" type="text/css" />',
        'js'   => '<script src="%s" type="text/javascript"></script>',
    ];

    /**
     * @param Container $container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * @param array $assets
     *
     * @return array
     */
    protected function createAssets(array $assets)
    {
        foreach ($assets as &$asset) {
            $asset = new Asset($asset);
        }
        unset($asset);
        return $assets;
    }

    /**
     * @param string $name
     * @param array $assets
     * @param bool $debug
     * @param bool $compress
     *
     * @return string
     * @throws \RuntimeException
     */
    //TODO: check amount of files
    public function getAssets($name, array $assets, $debug = false, $compress = true)
    {
        $assets = $this->createAssets($assets);
        $assets_collection = new AssetsCollection($assets);

        $compress_postfix = $compress ? 'min.' : '';
        $version = $assets_collection->getLastModified();

        $config = $this->container['assets'];
        $compiled_path = $config['path'] . $name . '.' . $compress_postfix . $assets_collection->getMetaType();

        if
        (
            $this->container['environment'] === 'debug' ||
            $debug ||
            (
                !file_exists($compiled_path) &&
                $this->container['environment'] === 'production'
            )
        ) {
            return $this->generateAssetsDebug($assets_collection);
        } elseif ($this->container['environment'] === 'test') {
            $this->generateAssetsTest($assets_collection, $compiled_path, $compress);
        }
        return sprintf(
            $this->templates[$assets_collection->getMetaType()],
            PathHelper::toURL($compiled_path, PUBLIC_PATH) . '?v=' . $version
        );
    }

    protected function generateAssetsDebug(AssetsCollection $assets_collection)
    {
        $config = $this->container['assets'];
        $result_assets = '';
        if ($assets_collection->getMetaType() === 'js' && $config['less']) {
            $assets_collection->addAsset(new Asset($config['lessjs_url']));
        }

        $assets = $assets_collection->getAssets();
        foreach ($assets as $asset) {
            if (file_exists($asset->getPath())) {
                $result_assets .= sprintf($this->templates[$asset->getType()], $asset->getURL());
            }
        }
        return $result_assets;
    }

    /**
     * @param AssetsCollection $assets_collection
     * @param string $compiled_path
     * @param bool $compress
     *
     * @return string
     * @throws \RuntimeException
     */
    //TODO: Remove every time generation, check changes
    protected function generateAssetsTest(AssetsCollection $assets_collection, $compiled_path, $compress = true)
    {
        $config = $this->container['assets'];
        if ($compress) {
            $dump = $assets_collection->dumpCompress($config['path']);
        } else {
            $dump = $assets_collection->dump($config['path']);
        }

        if (false === @file_put_contents($compiled_path, $dump)) {
            throw new \RuntimeException('Unable to write file ' . $compiled_path);
        }
        return PathHelper::toURL($compiled_path, PUBLIC_PATH);
    }
}


<?php

namespace Environaut\Export\Formatter;

use Environaut\Report\IReport;
use Environaut\Export\Formatter\BaseFormatter;
use Environaut\Checks\ICheck;

/**
 * Writes all or specific groups of settings as SHELL variables to a file.
 *
 * Supported parameters include:
 * - "location": Path and filename to write (defaults to 'environaut-config.sh').
 * - "groups": Array of group names. Only settings with those groups are written.
 *             By default all settings regardless of their group are written.
 * - "template": Content of file to write with placeholder '%settings$s' where
 *               settings will be put as shell variables (separated by newlines).
 * - "use_group_as_prefix": Defines if the group name of the setting should be
 *                          used as a prefix (defaults to false).
 * - "capitalize_names": Whether to convert variable names to all uppercase or
 *                       not (defaults to false).
 */
class ShellSettingsWriter extends BaseFormatter
{
    /**
     * Writes all or specific groups of settings as a shell file and
     * returns a message with some information about that.
     *
     * @param IReport $report report to take results (and settings) from
     *
     * @return string messages for CLI output
     */
    public function format(IReport $report)
    {
        $output = '';
        $params = $this->getParameters();

        $file = $params->get('location', 'environaut-config.sh');
        $groups = $params->get('groups');

        if (is_writable($file)) {
            $output .= '<comment>Overwriting</comment> ';
        } else {
            $output .= 'Writing ';
        }

        if (empty($groups)) {
            $output .= 'all groups ';
        } else {
            $output .= 'group(s) "' . implode(', ', $groups) . '" ';
        }

        $output .= 'to file "<comment>' . $file . '</comment>"...';

        $default_template = <<<EOT
%settings\$s
EOT;

        $template = $params->get('template', $default_template);

        $all_settings = $report->getSettingsAsArray($groups);

        $grouped_settings = array();
        $content = '';

        foreach ($all_settings as $setting) {
            $name = $this->makeShellVariableName($setting['name'], $setting['group']);
            $value = $this->mapValue($setting['value']);

            $content .= $name . "='" . $value ."'\n";
        }

        $content = self::vksprintf($template, array('settings' => $content));

        $ok = file_put_contents($file, $content, LOCK_EX);

        if ($ok !== false) {
            $output .= '<info>ok</info>.';
        } else {
            $output .= '<error>FAILED</error>.';
        }

        return $output;
    }

    protected function mapValue($value)
    {
        switch (gettype($value)) {
            case "boolean":
                return $value ? "1" : "";
            case "array":
                return $this->transformArrayValue($value);
            default:
                return $value;
        }
    }

    protected function transformArrayValue(array $value)
    {
        return implode("\n", $value);
    }

    protected function makeShellVariableName($setting_name, $group)
    {
        $params = $this->getParameters();

        $use_group_as_prefix = $params->get('use_group_as_prefix', false);
        $capitalize_names = $params->get('capitalize_names', false);
        $valid_name_regex = '/^[A-z_][A-z0-9_]*$/';

        if ($use_group_as_prefix && $group && $group !== ICheck::DEFAULT_GROUP_NAME) {
            $prefix = $group . '_';
        } else {
            $prefix = '';
        }

        $name = $prefix . $setting_name;

        if (!preg_match($valid_name_regex, $name)) {
            throw new \Exception('"'.$name.'" is not a valid shell variable identifier.');
        }

        if ($capitalize_names) {
            $name = strtoupper($name);
        }

        return $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;

/**
 * Implemens some basic functions to manage the json format
 *
 * @author RedKite Labs <info@redkite-labs.com>
 */
class BaseJson
{
    /**
     * Returns filename contents when exists or an empty string
     *
     * @param  string $file
     * @return string
     */
    public function getFileContents($file)
    {
        $contents = "";
        if (file_exists($file)) {
            $contents = file_get_contents($file);
        }

        return  $contents;
    }

    /**
     * Decodes the json contents readed from the given file, into an array
     *
     * @param  string $file
     * @return array
     */
    public function decode($file)
    {
        $contents = $this->getFileContents($file);

        $result = array();
        if ($contents != "") {
            $result = json_decode($contents, true);
        }

        return $result;
    }

    /**
     * Encodes the given values into a json file
     *
     * @param string $file
     * @param array  $values
     */
    public function encode($file, array $values)
    {
        if ( ! empty($values)) {
            file_put_contents($file, json_encode($values));
        }
    }
}


<?php

/**
 * Nameless framework
 *
 * @package Nameless framework
 * @author  Corpsee <poisoncorpsee@gmail.com>
 * @license https://github.com/corpsee/nameless-source/blob/master/LICENSE
 * @link    https://github.com/corpsee/nameless-source
 */

namespace Nameless\Modules\Assets;

use Assetic\Filter\LessphpFilter;
use Assetic\Asset\FileAsset;
use Nameless\Utilities\PathHelper;
use Nameless\Utilities\UrlHelper;

/**
 * Asset class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class Asset
{
    /**
     * @var string
     */
    protected $url;

    /**
     * @var string
     */
    protected $path = null;

    /**
     * @var string
     */
    protected $temp_path = null;

    /**
     * @var string
     */
    protected $type = null;

    /**
     * @var string
     */
    protected $meta_type = null;

    /**
     * @var FileAsset
     */
    protected $file_asset = null;

    /**
     * @param string $url
     */
    public function __construct($url)
    {
        $this->url = $url;
    }

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

    /**
     * @return string
     */
    public function getPath()
    {
        if (!is_null($this->path)) {
            return $this->path;
        }

        $this->path = UrlHelper::toPath($this->url, PUBLIC_PATH);
        return $this->path;
    }

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

    /**
     * @return string
     *
     * @throws \LogicException
     */
    public function getType()
    {
        if (!is_null($this->type)) {
            return $this->type;
        }

        $type = pathinfo($this->url, PATHINFO_EXTENSION);

        switch ($type) {
            case 'css':
            case 'less':
            case 'js':
                $this->type = $type;
                break;
            default:
                throw new \LogicException("Invalid asset type: '$type'");
        }
        return $this->type;
    }

    /**
     * @return string
     */
    public function getMetaType()
    {
        if (!is_null($this->meta_type)) {
            return $this->meta_type;
        }

        $this->getType();
        if ($this->type === 'less') {
            $this->meta_type = 'css';
        } else {
            $this->meta_type = $this->type;
        }
        return $this->meta_type;
    }

    /**
     * @param string $assets_dir
     *
     * @return FileAsset
     */
    public function getFileAsset($assets_dir)
    {
        if (!is_null($this->file_asset)) {
            return $this->file_asset;
        }

        $filters = [];
        if ($this->getType() === 'js') {
            $this->file_asset = new FileAsset($this->getPath(), $filters);
            return $this->file_asset;
        }

        $asset_path_temp = $this->replaceRelativeLinks($assets_dir);

        if ($this->getType() === 'less') {
            $filters[] = new LessphpFilter();
        }
        $this->file_asset = new FileAsset($asset_path_temp, $filters);
        return $this->file_asset;
    }

    /**
     * @param string $assets_dir
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    protected function replaceRelativeLinks($assets_dir)
    {
        $file = fopen($this->getPath(), 'rb');
        $asset_text = fread($file, filesize($this->getPath()));
        fclose($file);

        chdir(dirname($this->getPath()));

        $urls_old = [];
        $urls_new = [];

        preg_match_all('#url\(([\'"]?[^/\'"][^\'"]*[\'"]?)\)#imU', $asset_text, $urls_old);
        $urls = array_unique($urls_old[1]);

        foreach ($urls as $url) {
            $urls_new[] = "'" . PathHelper::toURL(realpath(trim($url, '"\'')), PUBLIC_PATH) . "'";
        }

        $asset_text = str_replace($urls, $urls_new, $asset_text);

        $this->temp_path = $assets_dir . basename($this->getPath());

        if (false === @file_put_contents($this->temp_path, $asset_text)) {
            throw new \RuntimeException('Unable to write file ' . $this->temp_path);
        }
        return $this->temp_path;
    }
}


<?php

/*
 * This file is part of the Security package.
 *
 * (c) EXSyst
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace EXSyst\Component\Security\TOTP;

/**
 * TOTP code validator.
 */
class TOTPValidator
{
    const DEFAULT_STAMP_WINDOW = 1;

    /**
     * @var TOTPTimeManager
     */
    private $timeManager;
    /**
     * @var int|null
     */
    private $window;

    /**
     * @param TOTPTimeManager|int|null $stampLength Stamp length in seconds
     * @param int|null                 $window      accepted stamps before and after the current stamp
     */
    public function __construct($stampLength = null, $window = null)
    {
        // stamp length definition
        if (!($stampLength instanceof TOTPTimeManager)) {
            $this->timeManager = new TOTPTimeManager(intval($stampLength));
        } else {
            $this->timeManager = $stampLength;
        }

        // Window definition
        if ($window === null) {
            $this->window = self::DEFAULT_STAMP_WINDOW;
        } else {
            $this->window = intval($window);
        }
    }

    /**
     * Check if a totp corresponds to a key and a stamp.
     *
     * @param string $key
     * @param int    $totp
     *
     * @return bool Return true if the totp corresponds to the key and the stamp provided
     */
    public function validate($totp, $key, $stamp = null)
    {
        if ($stamp === null) {
            $stamp = $this->timeManager->getCurrentStamp();
        }

        if (!preg_match('/^[0-9]{6}$/', $totp)) {
            return false;
        }
        $totp = intval($totp);

        // Search the stamp corresponding to the totp provided
        for ($st = $stamp - $this->window; $st <= $stamp + $this->window; ++$st) {
            if (($res = TOTPGenerator::generate($st, $key)) == $totp) {
                return $st;
            }
        }

        return false;
    }

    /**
     * @return TOTPTimeManager
     */
    public function getTimeManager()
    {
        return $this->timeManager;
    }
}


<?php

namespace Interpro\Entrance;

use Illuminate\Bus\Dispatcher;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Extractor\Contracts\Selection\Tuner;

class EntranceServiceProvider extends ServiceProvider {

    /**
     * @return void
     */
    public function boot(Dispatcher $dispatcher, Taxonomy $taxonomy, Tuner $tuner)
    {
        //Log::info('Загрузка EntranceServiceProvider');

        $this->initDefaultSelectionUnits($taxonomy, $tuner);
    }

    private function initDefaultSelectionUnits(Taxonomy $taxonomy, Tuner $tuner)
    {
        $groups = $taxonomy->getGroups();

        foreach($groups as $group)
        {
            $tuner->initSelection($group, 'group');
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //Log::info('Регистрация EntranceServiceProvider');

        $this->app->singleton(
            'Interpro\Entrance\Contracts\Extract\ExtractAgent',
            'Interpro\Entrance\Agents\ExtractAgent'
        );

        $this->app->singleton(
            'Interpro\Entrance\Contracts\CommandAgent\InitAgent',
            'Interpro\Entrance\Agents\InitAgent'
        );

        $this->app->singleton(
            'Interpro\Entrance\Contracts\CommandAgent\SyncAgent',
            'Interpro\Entrance\Agents\SyncAgent'
        );

        $this->app->singleton(
            'Interpro\Entrance\Contracts\CommandAgent\UpdateAgent',
            'Interpro\Entrance\Agents\UpdateAgent'
        );

        $this->app->singleton(
            'Interpro\Entrance\Contracts\CommandAgent\DestructAgent',
            'Interpro\Entrance\Agents\DestructAgent'
        );

    }

}