<?php
/*
This is part of Wedeto, the WEb DEvelopment TOolkit.
It is published under the MIT Open Source License.

Copyright 2017, Egbert van der Wal

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Wedeto\Resolve;

use Wedeto\Util\LoggerAwareStaticTrait;
use Wedeto\Util\Cache\Cache;

/**
 * Resolve templates assets from registered modules / locations
 */
class SubResolver
{
    use LoggerAwareStaticTrait;

    /** The name to identify the type of files resolved. Also used in the cache as identifier key */
    protected $name;

    /** A mandatory suffix - if this is not present on resolved files it will be added */
    protected $ext;

    /** The paths to search when resolving */
    protected $search_path = array();

    /** If the list has been sorted. Initally empty, so initially sorted */
    protected $sorted = true;

    /** The cache of templates, assets */
    protected $cache = null;

    /** The authorativeness of the cache */
    protected $authorative = false;

    /**
     * Set up the resolve cache.
     *
     * @param string $name The name of the resolver (Eg type of files resolved)
     */
    public function __construct(string $name, string $ext = null)
    {
        self::getLogger();
        $this->name = $name;
        $this->ext = $ext;
    }

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

    /**
     * Set a cache used to store located files
     */
    public function setCache(Cache $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Get the cache instance in use
     */
    public function getCache()
    {
        return $this->cache;
    }

    /**
     * Set the authorative state. When authorative is enabled, and a file
     * failed to resolve according to the cache, no attempt is made to resolve
     * it. This increases performance in production, but can be inconvenient
     * during development.
     *
     * @param bool $authorative The authorative state
     * @return SubResolver Provides fluent interface
     */
    public function setAuthorative(bool $authorative)
    {
        $this->authorative = $authorative;
        return $this;
    }

    /**
     * @return bool The Authorative state.
     * @seealso SubResolver::setAuthorative
     */
    public function getAuthorative()
    {
        return $this->authorative;
    }

    /**
     * Add a module to the search path of the SubResolver.
     *
     * @param string $name The name of the module. Just for logging purposes.
     * @param string $path The path of the module.
     * @param int $precedence The order in which the modules are searched.
     *                        Lower means searched earlier.
     * @return SubResolver Provides fluent interface
     */
    public function addToSearchPath(string $name, string $path, int $precedence)
    {
        if (!is_dir($path))
            throw new \InvalidArgumentException("Path does not exist: " . $path);

        $this->search_path[$name] = array('path' => $path, 'precedence' => $precedence);
        $this->sorted = false;

        return $this;
    }

    protected function sortModules()
    {
        // Sort the paths so that the highest priority comes first
        uasort($this->search_path, function ($l, $r) {
            if ($l['precedence'] !== $r['precedence'])
                return $l['precedence'] - $r['precedence'];
            return strcmp($l['path'], $r['path']);
        });

        $this->sorted = true;
    }

    /**
     * Set the precedence value of a module
     * @param string $name The name of the module
     * @param int $precedence The precedence value to set
     * @return SubResolver Provides fluent interface
     */
    public function setPrecedence(string $name, int $precedence)
    {
        if (!isset($this->search_path[$name]))
            throw new \InvalidArgumentException("Unknown module: " . $name);

        if ($this->search_path[$name]['precedence'] !== $precedence)
        {
            $this->search_path[$name]['precedence'] = $precedence;
            $this->sorted = false;
        }
        return $this;
    }

    /**
     * Get the precedence value of a module
     * @param string $name The name of the module
     * @return int The precedence value
     */
    public function getPrecedence(string $name)
    {
        if (!isset($this->search_path[$name]))
            throw new \InvalidArgumentException("Unknown module: " . $name);

        return $this->search_path[$name]['precedence'];
    }

    /**
     * @return array A list of found modules
     */
    public function getSearchPath()
    {
        if (!$this->sorted)
            $this->sortModules();

        $sp = array();
        foreach ($this->search_path as $name => $info)
            $sp[$name] = $info['path'];
        return $sp;
    }

    /**
     * Clear the search path
     * @return SubResolver Provides fluent interface
     */
    public function clearSearchPath()
    {
        $this->search_path = array();
        $this->sorted = false;
    }

    /**
     * Clear the cached resolved files
     * @return SubResolver Provides fluent interface
     */
    public function clearCache()
    {
        if ($this->cache !== null)
            $this->cache->set('resolve', $this->name, array('data' => [], 'search_path' => $this->search_path));
        return $this;
    }

    /**
     * Obtain the cached data. The cache is cleared when the sort order does not match
     * the cache.
     *
     * @return The cached data
     */
    protected function getCachedData()
    {
        if ($this->cache === null)
            return null;

        $sp = $this->cache->get('resolve', $this->name, 'search_path');
        if ($sp !== null)
            $sp = $sp->toArray();

        if ($this->search_path !== $sp)
            $this->clearCache();

        return $this->cache->get('resolve', $this->name);
    }

    /**
     * Helper method that searches the core and modules for a specific type of file.
     * The files are evaluated in alphabetical order, and core always comes first.
     *
     * @param $type string The type to find, template or asset
     * @param $file string The file to locate
     * @return string A matching file. Null is returned if nothing was found.
     */
    public function resolve(string $file)
    {
        if (!$this->sorted)
            $this->sortModules();

        $file = ltrim($file, '/');
        if ($this->ext !== null && substr($file, -strlen($this->ext)) !== $this->ext)
            $file .= $this->ext;

        $cache = $this->getCachedData();
        $cached = $cache !== null ? $cache->get('data', $file) : null;

        if ($cached === false && $this->authorative)
            return null;

        if (!empty($cached))
        {
            if (file_exists($cached['path']) && is_readable($cached['path']))
            {
                self::$logger->debug(
                    "Resolved {0} {1} to path {2} (module: {3}) (cached)",
                    [$this->name, $file, $cached['path'], $cached['module']]
                );
                return $cached['path'];
            }
            else
            {
                self::$logger->error(
                    "Cached path for {0} {1} from module {2} cannot be read: {3}",
                    [$this->name, $file, $cached['module'], $cached['path']]
                );
            }
        }

        $path = null;
        $found_module = null;
        $mods = $this->search_path;

        foreach ($mods as $module => $info)
        {
            $location = $info['path'];
            self::$logger->debug("Trying {0} path: {1}/{2}", [$location, $this->name, $file]);
            $path = $location . '/' . $file;

            if (file_exists($path) && is_readable($path))
            {
                $found_module = $module;
                break;
            }
        }

        if ($found_module !== null)
        {
            self::$logger->debug("Resolved {0} {1} to path {2} (module: {3})", [$this->name, $file, $path, $found_module]);
            if ($cache !== null)
            {
                $cache->set(
                    'data',
                    $file,
                    array("module" => $found_module, "path" => $path)
                );
            }
            return $path;
        }
        elseif ($cache !== null)
        {
            $cache->set('data', $file, false);
        }

        return null;
    }
}


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

use Openbizx\Web\Request;

/**
 * Description of UrlManager
 *
 * @author agus
 */
class UrlManager
{

    private $_request;

    public function __construct($request)
    {
        $this->_request = $request;
    }

    function getViewName($urlArr)
    {
        $url_path = $urlArr[1];
        if (!$url_path) {
            return gotoDefaultView($urlArr[0]);
        }
        if (preg_match_all("/([a-z]*)_?/si", $url_path, $match)) {
            $view_name = "";
            $match = $match[1];
            foreach ($match as $part) {
                if ($part) {
                    $part = ucwords($part); //ucwords(strtolower($part));
                    $view_name .= $part;
                }
            }
            $view_name.="View";
        }
        return $view_name;
    }

    /**
     * Parser Uri request
     * @param Request $request
     */
    public function parserRequestUri($request)
    {
        $url = $request->getPathUri();
        if ($url) {
            $urlArr = preg_split("/\//si", $url);
            if (preg_match("/^[a-z_]*$/si", $urlArr[1])) {
                // http://localhost/?/ModuleName/ViewName/
                $module_name = $urlArr[0];
                $view_name = $request->pathNameToViewName($urlArr, 1);
                $uriParams = $request->getUriParameters($urlArr, 1);
            } elseif (preg_match("/^[a-z_]*$/si", $urlArr[0])) {
                // http://localhost/?/ViewName/
                $module_name = '';
                $view_name = $request->pathNameToViewName($urlArr, 0);
                $uriParams = $request->getUriParameters($urlArr, 0);
            } else {
                throw new Exception();/** @todo Change Exception class more specific. */
            }
        } else {
                $module_name = '';
                $view_name = '';
                $uriParams = [];
        }
        return array(
            'module' => $module_name,
            'shortView' => $view_name,
            'uriParams' => $uriParams,
        );
    }
}


<?PHP

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Checkbox.php 3780 2011-04-18 18:26:11Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Core\Expression;

//include_once("OptionElement.php");

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

    protected $defaultChecked;

    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->defaultChecked = isset($xmlArr["ATTRIBUTES"]["DEFAULTCHECKED"]) ? $xmlArr["ATTRIBUTES"]["DEFAULTCHECKED"] : "N";
    }

    public function getDefaultChecked()
    {
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->defaultChecked, $formObj);
    }

    /**
     * Get value of element
     *
     * @return mixed
     */
    public function getValue()
    {

        if (strtoupper($this->getDefaultChecked()) == 'Y' && !isset($_GET['F'])) {
            $this->value = $this->getSelectFrom();
            return $this->value;
        }

        if ($this->value != null) {
            return $this->value;
        } else {
            return $this->defaultValue;
        }
    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $boolValue = $this->getSelectFrom();
        $disabledStr = ($this->getEnabled() == "N") ? "DISABLED=\"true\"" : "";

        if (strtoupper($this->getDefaultChecked()) == 'Y' && !isset($_GET['F'])) {
            $checkedStr = "CHECKED";
        } else {
            $checkedStr = ($boolValue == $this->getValue()) ? "CHECKED" : "";
        }
        $defaultValue = $this->defaultValue;
        $style = $this->getStyle();
        $text = $this->getText();
        $func = $this->getFunction();
        $sHTML = '';
        $fromList = array();
        $this->getFromList($fromList);

        if (count($fromList) > 1) {
            $valueArr = explode(',', $this->getValue());

            foreach ($fromList as $opt) {
                $test = array_search($opt['val'], $valueArr);
                if ($test === false) {
                    $checkedStr = '';
                } else {
                    $checkedStr = "CHECKED";
                }
                $sHTML .= "<INPUT TYPE=CHECKBOX NAME='" . $this->objectName . "[]' ID=\"" . $this->objectName . "\" DefaultValue=\"$defaultValue\" VALUE=\"" . $opt['val'] . "\" $checkedStr $disabledStr $this->htmlAttr $func /> " . $opt['txt'] . "";
            }
        } else {
            $sHTML = "<INPUT TYPE=\"CHECKBOX\" NAME=\"" . $this->objectName . "\" ID=\"" . $this->objectName . "\" DefaultValue=\"$DefaultValue\" VALUE='$boolValue' $checkedStr $disabledStr $this->htmlAttr $style $func /> " . $text . "";
        }

        return $sHTML;
    }

}

?>


<?PHP
/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.easy.element
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: FileUploader.php 3086 2011-01-22 20:06:43Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Easy\Element\FileInput;

/**
 * File class is the element for Upload File
 *
 * @package openbiz.bin.easy.element
 * @author jixian2003
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class FileUploader extends FileInput
{
    public $uploadRoot ;
    public $uploadRootURL ;
    public $uploadFolder ;
    public $uploadFileType ;
    public $uploaded =false;
    public $deleteable;
    public $useRawName=false;

    /**
     * Initialize Element with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr, $formObj)
    {
        parent::__construct($xmlArr, $formObj);
        $this->readMetaData($xmlArr);
        if(defined("OPENBIZ_PUBLIC_UPLOAD_PATH")){
        	$this->uploadRoot= constant("OPENBIZ_PUBLIC_UPLOAD_PATH");
        }else{
        	$this->uploadRoot= OPENBIZ_APP_PATH."/files/upload";
        }
        if(defined("OPENBIZ_PUBLIC_UPLOAD_URL")){
        	$this->uploadRootURL = str_replace(OPENBIZ_APP_URL,"",constant("OPENBIZ_PUBLIC_UPLOAD_URL"));
        }else{
        	$this->uploadRootURL = "/files/upload";
        }
    }

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->uploadFolder = isset($xmlArr["ATTRIBUTES"]["UPLOADFOLDER"]) ? $xmlArr["ATTRIBUTES"]["UPLOADFOLDER"] : null;
        $this->uploadFileType = isset($xmlArr["ATTRIBUTES"]["FILETYPE"]) ? $xmlArr["ATTRIBUTES"]["FILETYPE"] : null;
        $this->deleteable = isset($xmlArr["ATTRIBUTES"]["DELETEABLE"]) ? $xmlArr["ATTRIBUTES"]["DELETEABLE"] : "N";
        $this->useRawName = isset($xmlArr["ATTRIBUTES"]["USERAWNAME"]) ? $xmlArr["ATTRIBUTES"]["USERAWNAME"] : false;
    }

    /**
     * Set value of element
     *
     * @param mixed $value
     * @return string
     */
    function setValue($value)
    {
        if($this->deleteable=='N')
    	{

    	}
    	else
    	{
    		$delete_user_opt= Openbizx::$app->getClientProxy()->getFormInputs($this->objectName."_DELETE");
    		if($delete_user_opt)
    		{
    			$this->value="";
    			return;
    		}
    		else
    		{
    			if(count($_FILES)>0){

    			}else{
    				$this->value = $value;
    			}
    		}
    	}
    	if(count($_FILES)>0)
		{
			if(!$this->uploaded && $_FILES[$this->objectName]["size"] > 0)
			{
				$file = $_FILES[$this->objectName];

				if(!is_dir($this->uploadRoot.$this->uploadFolder))
				{
					mkdir($this->uploadRoot.$this->uploadFolder ,0777,true);
				}
				if($this->useRawName){
					$uploadFile = $this->uploadFolder."/".$file['name'];
				}else{
					$uploadFile = $this->uploadFolder."/".date("YmdHis")."-".md5($file['name']);
				}
				if($this->uploadFileType){
					$pattern = "/".$this->uploadFileType."$/si";
					if(!preg_match($pattern,$file['name'])){
						return;
					}
				}
				if(move_uploaded_file($file['tmp_name'], $this->uploadRoot.$uploadFile))
				{
					$this->value = $this->uploadRootURL.$uploadFile;
					$this->uploaded=true;
				}
				return $uploadFile;
			}
		}
    }

    public function render()
    {
    	if($this->deleteable=="Y"){
        	$delete_opt="<input type=\"checkbox\" name=\"" . $this->objectName . "_DELETE\" id=\"" . $this->objectName ."_DELETE\" >Delete";
        } else{
        	$delete_opt="";
        }
        $disabledStr = ($this->getEnabled() == "N") ? "disabled=\"true\"" : "";
        $style = $this->getStyle();
        $func = $this->getFunction();
        $sHTML .= "<input type=\"file\" name='$this->objectName' id=\"" . $this->objectName ."\" value='$this->value' $disabledStr $this->htmlAttr $style $func />
        			$delete_opt";
        return $sHTML;
    }

}
?>


<?php

namespace Interpro\QuickStorage\Laravel;

use Interpro\QuickStorage\Concept\StorageStructure as StorageStructureInterface;

class StorageStructure implements StorageStructureInterface
{

    private $types;

    private function getTypes()
    {
        if (!isset($this->types))
        {
            $this->types = ['stringfields' => 'Interpro\QuickStorage\Laravel\Model\Stringfield',
                'textfields' => 'Interpro\QuickStorage\Laravel\Model\Textfield',
                'numbs' => 'Interpro\QuickStorage\Laravel\Model\Numb',
                'bools' => 'Interpro\QuickStorage\Laravel\Model\Bool',
                'pdatetimes' => 'Interpro\QuickStorage\Laravel\Model\Pdatetime',
                'images' => 'Interpro\QuickStorage\Laravel\Model\Imageitem'];
        }

        return $this->types;
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    public function getBlockImagesFlat($blockName)
    {
        $struct = $this->getBlockConfig($blockName);

        $images_flat = [];

        if(array_key_exists('images', $struct))
        {
            foreach($struct['images'] as $image_name)
            {
                $images_flat[] = $image_name;
            }
        }

        return $images_flat;
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return array
     */
    public function getGroupImagesFlat($blockName, $groupName)
    {
        $struct = $this->getGroupConfig($blockName, $groupName);

        $images_flat = [];

        if(array_key_exists('images', $struct))
        {
            foreach($struct['images'] as $image_name)
            {
                $images_flat[] = $image_name;
            }
        }

        return $images_flat;
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    public function getBlockFieldsFlat($blockName)
    {
        $struct = $this->getBlockConfig($blockName);

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

        $types = ['stringfields', 'textfields', 'numbs', 'bools', 'pdatetimes', 'images'];
        foreach($types as $type)
        {
            if(array_key_exists($type, $struct))
            {
                foreach($struct[$type] as $fieldname)
                {
                    $fields_flat[] = $fieldname;
                }
            }
        }

        return $fields_flat;
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return array
     */
    public function getGroupFieldsFlat($blockName, $groupName)
    {
        $struct = $this->getGroupConfig($blockName, $groupName);

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

        $types = ['stringfields', 'textfields', 'numbs', 'bools', 'pdatetimes', 'images'];
        foreach($types as $type)
        {
            if(array_key_exists($type, $struct))
            {
                foreach($struct[$type] as $fieldname)
                {
                    $fields_flat[] = $fieldname;
                }
            }
        }

        return $fields_flat;
    }

    /**
     * @param string $blockName
     *
     * @return int
     */
    public function getMainGroupsDepth($blockName)
    {
        $depth = 0;
        $groupstruct_0 = $this->getGroupsFlatConfig($blockName);

        foreach ($groupstruct_0 as $groupname => $groupstruct)
        {
            if(!array_key_exists('owner', $groupstruct))
            {
                $dataArr[$groupname] = [];

                $currdepth = $this->getGroupsDepth($groupstruct_0, $groupname, 0);

                $depth = $currdepth > $depth ? $currdepth : $depth;
            }
        }

        return $depth;
    }

    private function getGroupsDepth(&$groupstruct_0, $groupname_x, $depth)
    {

        $depth++;
        $maxdepth = $depth;

        foreach ($groupstruct_0 as $groupname => $groupstruct)
        {
            if(array_key_exists('owner', $groupstruct) and $groupstruct['owner'] == $groupname_x)
            {
                $currdepth = $this->getGroupsDepth($groupstruct_0, $groupname, $depth);

                $maxdepth = $currdepth > $maxdepth ? $currdepth : $maxdepth;
            }
        }

        return $maxdepth;
    }

    /**
     * @param string $type
     *
     * @return bool
     */
    public function getModelName($type)
    {
        return $this->getTypes()[$type];
    }

    public function getModelNameByFieldBlock($blockName, $fieldName)
    {
        return $this->getBlockFieldsModels($blockName)[$fieldName];
    }

    public function getModelNameByFieldGroup($blockName, $groupName, $fieldName)
    {
        return $this->getGroupFieldsModels($blockName, $groupName)[$fieldName];
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return bool
     */
    public function getGroupFieldsModels($blockName, $groupName)
    {
        $struct = $this->getGroupConfig($blockName, $groupName);

        $fields_flat = [];

        $types = $this->getTypes();

        foreach($types as $type=>$model)
        {
            if(array_key_exists($type, $struct))
            {
                foreach($struct[$type] as $fieldname)
                {
                    $fields_flat[$fieldname] = $model;
                }
            }
        }

        return $fields_flat;
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return bool
     */
    public function getBlockFieldsModels($blockName)
    {
        $struct = $this->getBlockConfig($blockName);

        $fields_flat = [];

        $types = $this->getTypes();

        foreach($types as $type=>$model)
        {
            if(array_key_exists($type, $struct))
            {
                foreach($struct[$type] as $fieldname)
                {
                    $fields_flat[$fieldname] = $model;
                }
            }
        }

        return $fields_flat;
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    public function getGroupsSub9n($blockName) //getGroupsStruct
    {

        $groups_conf = $this->getGroupsFlatConfig($blockName);
        $groupstruct_invert = [];

        foreach ($groups_conf as $groupname => $_conf)
        {
            if(!array_key_exists($groupname, $groupstruct_invert))
            {
                $groupstruct_invert[$groupname] = [];
            }

            if(array_key_exists('owner', $_conf))
            {
                if(!array_key_exists($_conf['owner'], $groupstruct_invert))
                {
                    $groupstruct_invert[$_conf['owner']] = [];
                }

                $groupstruct_invert[$_conf['owner']][] = $groupname;
            }
        }

        return $groupstruct_invert;
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    private function getGroups0level($blockName)
    {

        $groups_conf = $this->getGroupsFlatConfig($blockName);
        $groupstruct_0l = [];

        foreach ($groups_conf as $groupname => $_conf)
        {
            if(!array_key_exists('owner', $_conf))
            {
                $groupstruct_0l[$groupname] = [];
            }
        }

        return $groupstruct_0l;
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    public function getGroupsFlatConfig($blockName)
    {
        return config('qstorage.'.$blockName)['groups'];
    }

    /**
     * @param string $blockName
     *
     * @return bool
     */
    public function blockExist($blockName)
    {
        return !!config('qstorage.'.$blockName);
    }

    /**
     * @param string $blockName
     *
     * @return array
     */
    public function getBlockConfig($blockName)
    {
        return config('qstorage.'.$blockName);
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return array
     */
    public function getGroupConfig($blockName, $groupName)
    {
        return config('qstorage.'.$blockName)['groups'][$groupName];
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return bool
     */
    public function groupExist($blockName, $groupName)
    {
        $groups_conf = $this->getGroups0level($blockName);

        return array_key_exists($groupName, $groups_conf);
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @return bool
     */
    public function groupInBlockExist($blockName, $groupName)
    {
        $groups_conf = $this->getGroupsFlatConfig($blockName);

        return array_key_exists($groupName, $groups_conf);
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @param string $subGroupName
     *
     * @return bool
     */
    public function subGroupExist($blockName, $groupName, $subGroupName)
    {
        $groups_conf = $this->getGroupsSub9n($blockName);

        if (array_key_exists($groupName, $groups_conf))
        {
            return in_array($subGroupName, $groups_conf[$groupName]);

        }else{

            return false;
        }
    }

    /**
     * @param string $blockName
     *
     * @param string $fieldName
     *
     * @return bool
     */
    public function blockFieldExist($blockName, $fieldName)
    {
        $fields = $this->getBlockFieldsFlat($blockName);

        return in_array($fieldName, $fields);
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @param string $fieldName
     *
     * @return bool
     */
    public function groupFieldExist($blockName, $groupName, $fieldName)
    {
        $groups_conf = $this->getGroupsFlatConfig($blockName);

        if(!array_key_exists($groupName, $groups_conf))
        {
            return false;
        }else{
            $struct = $this->getGroupFieldsFlat($blockName, $groupName);

            return in_array($fieldName, $struct);
        }
    }

    /**
     * @param string $blockName
     *
     * @param string $fieldName
     *
     * @return bool
     */
    public function blockImageExist($blockName, $fieldName)
    {
        $fields = $this->getBlockFieldsFlat($blockName);

        return in_array($fieldName, $fields);
    }

    /**
     * @param string $blockName
     *
     * @param string $groupName
     *
     * @param string $fieldName
     *
     * @return bool
     */
    public function groupImageExist($blockName, $groupName, $imageName)
    {
        $groups_conf = $this->getGroupsFlatConfig($blockName);

        if(!array_key_exists($groupName, $groups_conf))
        {
            return false;
        }else{
            $struct = $this->getGroupImagesFlat($blockName, $groupName);

            return in_array($imageName, $struct);
        }
    }

}


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

namespace Openbizx\Easy;

use Openbizx\Easy\WebPage;

/**
 * WebPageWizard is the class that controls the wizard forms
 *
 * @package openbiz.bin.easy
 * @author rocky swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class WebPageWizard extends WebPage
{
    protected $currentStep;
    protected $formStates;    // (formname, visited, committed)
    protected $dropSession = false;
    protected $naviMethod = 'SwitchPage';

    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->naviMethod = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["NAVIMETHOD"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["NAVIMETHOD"] :'SwitchPage';
    }
    /**
     * Get/Retrieve Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function loadStatefullVars($sessionContext)
    {
        $sessionContext->loadObjVar($this->objectName, "FormStates", $this->formStates, true);
        $sessionContext->loadObjVar($this->objectName, "CurrentStep", $this->currentStep, true);
    }

    /**
     * Save Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function saveStatefullVars($sessionContext)
    {
        if ($this->dropSession){
            $sessionContext->cleanObj($this->objectName, true);
        }else{
            $sessionContext->saveObjVar($this->objectName, "FormStates", $this->formStates, true);
            $sessionContext->saveObjVar($this->objectName, "CurrentStep", $this->currentStep, true);
        }

    }

    /**
     * Initialize all form objects.
     * NOTE: Do not initiate the all forms
     *
     * @return void
     */
    protected function initAllForms()
    {
    }

    /**
     * Process request
     *
     * @return void
     */
    protected function processRequest()
    {
        parent::processRequest();

        $step = $this->getCurrentStep();

        // only display given step form
        $i = 1;
        foreach ($this->formRefs as $formRef)
        {
            if ($i == $step)
                $formRef->display = true;
            else
                $formRef->display = false;
            $i++;
        }
    }

    protected function getStepName($step)
    {
		$i = 1;
        foreach ($this->formRefs as $formRef){
            if($i == $step){
            	return $formRef->objectName;
            }
            $i++;
        }
        return "";
    }

    /**
     * Get current step
     *
     * @return number
     */
    public function getCurrentStep()
    {  	if($_GET['step'])
	    {
	    	$this->currentStep=$_GET['step'];
	    	return $this->currentStep;
	    }
    	elseif($this->currentStep)
    	{
    		if($this->currentStep > $this->formRefs->count()){
    			return $this->formRefs->count();
    		}else{
    			return $this->currentStep;
    		}
    	}
    	else
    	{
	        $step = isset($_GET['step']) ? $_GET['step'] : 1;
	        $numForms = 0;
	        foreach ($this->formRefs as $formRef)
	            $numForms++;

	        if ($step < 1)
	            $step = 1;
	        if ($step > $numForms)
	            $step = $numForms;
	        $this->currentStep = $step;
	        return $step;
    	}
    }

    /**
     * Render step
     *
     * @param number $step
     * @return void
     */
    public function renderStep($step)
    {
    	if($this->currentStep){
    		$currentStep = $this->currentStep;
    	}else{
        	$currentStep = $this->getCurrentStep();
    	}
        if ($currentStep == $step)
            return;
		switch(strtoupper($this->naviMethod)){
			case "SWITCHFORM":
				$targetForm = $this->getStepName($step);
				$currentForm = $this->getStepName($currentStep);
				$this->currentStep = $step;
				$formObj = Openbizx::getObject($currentForm);
				$formObj->switchForm($targetForm);
				break;

			case "SWITCHPAGE":
			default:
				$currentURL = Openbizx::getService(OPENBIZ_UTIL_SERVICE)->getViewURL($this->objectName);
		        $url = OPENBIZ_APP_INDEX_URL.'/'.$currentURL.'/step_'.$step;
				Openbizx::$app->getClientProxy()->ReDirectPage($url);
				break;

		}
    }

    /**
     * Get form inputs
     *
     * @param string $formName
     * @return array
     */
    public function getFormInputs($formName)
    {
        $formObj = Openbizx::getObject($formName);
        $rec = $formObj->getActiveRecord();
        return $rec;
    }

    /**
     * Set form state
     *
     * @param string $formName form name
     * @param mixed $state state key
     * @param mixed $value
     * @return void
     */
    public function setFormState($formName, $state, $value)
    {
        $this->formStates[$formName][$state] = $value;
    }

    /**
     * Save wizard data of current+previous pages into database or other storage
     *
     * @return void
     */
    public function commit()
    {
        // call all step forms Commit method
        foreach ($this->formStates as $formName=>$state)
        {
            if ($state['visited'])
            {
                $r = Openbizx::getObject($formName)->commit();
                if (!$r)
                {
                	return false;
                }
            }
        }
        foreach ($this->formStates as $formName=>$state)
        {
            if ($state['visited'])
            {
                $r = Openbizx::getObject($formName)->dropSession();
                if (!$r)
                {
                    return false;
                }
            }
        }
        $this->dropSession = true;
        return true;
    }

    /**
     * Cancel, clean up the sessions of view and all forms
     *
     * @return void
     */
    public function cancel()
    {
        // call all step forms Cancel method
        if(is_array($this->formStates)){
	        foreach ($this->formStates as $formName=>$state)
	        {
	            if ($state['visited'])
	                Openbizx::getObject($formName)->cancel();
	        }
        }
        $this->dropSession = true;
    }

    /**
     * Get output attributs
     *
     * @return array
     * @todo need to raname to getOutputAttributs() or getAttributes
     */
    public function outputAttrs()
    {
        $out = parent::outputAttrs();
        $out['step'] = $this->currentStep;
        $out['forms'] = $this->formRefs;
        return $out;
    }

}

?>


<?php
declare(strict_types=1);

namespace Doctrineum\Scalar;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrineum\SelfRegisteringType\AbstractSelfRegisteringType;
use Granam\Scalar\Tools\ToScalar;
use Granam\ScalarEnum\Exceptions\CanNotCreateInstanceOfAbstractEnum;
use Granam\ScalarEnum\ScalarEnum;
use Granam\ScalarEnum\ScalarEnumInterface;
use Granam\Tools\ValueDescriber;

/**
 * @method static ScalarEnumType getType($name),
 */
class ScalarEnumType extends AbstractSelfRegisteringType
{

    public const SCALAR_ENUM = 'scalar_enum';

    /** @var string[][] */
    private static $enumSubTypesMap = [];

    /**
     * You can register a class just once.
     *
     * @param string $subTypeEnumClass
     * @param string $subTypeEnumValueRegexp
     * @return bool
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumIsAlreadyRegistered
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumClassNotFound
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumHasToBeEnum
     * @throws \Doctrineum\Scalar\Exceptions\InvalidRegexpFormat
     */
    public static function registerSubTypeEnum(string $subTypeEnumClass, string $subTypeEnumValueRegexp): bool
    {
        if (!static::hasSubTypeEnum($subTypeEnumClass, $subTypeEnumValueRegexp)) {
            // registering same subtype enum class but with different regexp cause exception in following method
            return static::addSubTypeEnum($subTypeEnumClass, $subTypeEnumValueRegexp);
        }

        return false;
    }

    /**
     * @param $subTypeClassName
     * @param string|null $subTypeEnumValueRegexp
     * @return bool
     * @throws \Doctrineum\Scalar\Exceptions\InvalidRegexpFormat
     */
    public static function hasSubTypeEnum(string $subTypeClassName, string $subTypeEnumValueRegexp = null): bool
    {
        return
            (self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()][$subTypeClassName] ?? null) !== null
            && (
                $subTypeEnumValueRegexp === null
                || (self::guardRegexpValid($subTypeEnumValueRegexp)
                    && self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()][$subTypeClassName] === $subTypeEnumValueRegexp
                )
            );
    }

    /**
     * @return string
     */
    protected static function getSubTypeEnumInnerNamespace(): string
    {
        return static::class;
    }

    /**
     * Warning: Behave of registering more classes on same regexp (or simply matching same string) is undefined.
     *
     * @param string $subTypeEnumClass
     * @param string $subTypeEnumValueRegexp
     * @return bool
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumIsAlreadyRegistered
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumClassNotFound
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumHasToBeEnum
     * @throws \Doctrineum\Scalar\Exceptions\InvalidRegexpFormat
     */
    public static function addSubTypeEnum(string $subTypeEnumClass, string $subTypeEnumValueRegexp): bool
    {
        if (static::hasSubTypeEnum($subTypeEnumClass)) {
            throw new Exceptions\SubTypeEnumIsAlreadyRegistered(
                'SubType enum ' . ValueDescriber::describe($subTypeEnumClass) . ' is already registered with regexp '
                . self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()][$subTypeEnumClass]
                . ' (requested to register with regexp ' . ValueDescriber::describe($subTypeEnumValueRegexp) . ')'
            );
        }
        /** The class has to be self-registering to by-pass enum and enum type bindings, @see ScalarEnum::createEnum */
        static::checkIfKnownEnum($subTypeEnumClass);
        static::guardRegexpValid($subTypeEnumValueRegexp);
        self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()][$subTypeEnumClass] = $subTypeEnumValueRegexp;

        return true;
    }

    /**
     * @param string $subTypeClassName
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumClassNotFound
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumHasToBeEnum
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumHasToHaveFactoryMethod
     */
    protected static function checkIfKnownEnum(string $subTypeClassName): void
    {
        if (!\class_exists($subTypeClassName)) {
            throw new Exceptions\SubTypeEnumClassNotFound(
                'Sub-type class ' . ValueDescriber::describe($subTypeClassName) . ' has not been found'
            );
        }
        if (!\is_a($subTypeClassName, ScalarEnumInterface::class, true)) {
            throw new Exceptions\SubTypeEnumHasToBeEnum(
                'Sub-type class ' . ValueDescriber::describe($subTypeClassName) . ' has to be child of ' . ScalarEnumInterface::class
            );
        }
        if (!\method_exists($subTypeClassName, 'getEnum')) {
            throw new Exceptions\SubTypeEnumHasToHaveFactoryMethod(
                'Sub-type class ' . ValueDescriber::describe($subTypeClassName) . ' has to have public static method getEnum($enumValue)'
            );
        }
    }

    /**
     * @param string $regexp
     * @return bool
     * @throws \Doctrineum\Scalar\Exceptions\InvalidRegexpFormat
     */
    private static function guardRegexpValid(string $regexp): bool
    {
        if (!\preg_match('~^(.).*\1$~', $regexp)) {
            // the regexp does not start and end with same characters
            throw new Exceptions\InvalidRegexpFormat(
                'The given regexp is not enclosed by same delimiters and therefore is not valid: '
                . ValueDescriber::describe($regexp)
            );
        }

        return true;
    }

    /**
     * @param string $subTypeEnumClass
     * @return bool
     * @throws \Doctrineum\Scalar\Exceptions\SubTypeEnumIsNotRegistered
     */
    public static function removeSubTypeEnum(string $subTypeEnumClass): bool
    {
        if (!static::hasSubTypeEnum($subTypeEnumClass)) {
            throw new Exceptions\SubTypeEnumIsNotRegistered(
                'Sub-type ' . ValueDescriber::describe($subTypeEnumClass) . ' is not registered'
            );
        }
        unset(self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()][$subTypeEnumClass]);

        return true;
    }

    /**
     * Gets the strongly recommended name of this type.
     * Its used at @see \Doctrine\DBAL\Platforms\AbstractPlatform::getDoctrineTypeComment
     * Note: also PhpStorm use it for click-through via @Column(type="foo-bar") notation,
     * if and only if is the value a constant (direct return of a string or constant).
     *
     * @return string
     */
    public function getName(): string
    {
        return self::SCALAR_ENUM;
    }

    /**
     * Gets the SQL declaration snippet for a field of this type.
     *
     * @param array $fieldDeclaration The field declaration.
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform The currently used database platform.
     * @return string
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string
    {
        return 'VARCHAR(' . $this->getDefaultLength($platform) . ')';
    }

    /**
     * @param AbstractPlatform $platform
     * @return int
     * @deprecated Rely on information provided by the platform instead.
     */
    public function getDefaultLength(AbstractPlatform $platform): int
    {
        return 64;
    }

    /**
     * Convert enum instance to database string (or null) value
     *
     * @param ScalarEnumInterface $value
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
     * @throws Exceptions\UnexpectedValueToDatabaseValue
     * @return string|int|float|bool|null
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }
        if (!\is_object($value) || !\is_a($value, ScalarEnumInterface::class)) {
            throw new Exceptions\UnexpectedValueToDatabaseValue(
                'Expected NULL or instance of ' . ScalarEnumInterface::class . ', got ' . ValueDescriber::describe($value)
            );
        }

        return $value->getValue();
    }

    /**
     * Convert database string value to Enum instance
     * This does NOT cast non-string scalars into string (integers, floats etc).
     * Even null remains null in returned Enum.
     * (But saving the value into database and pulling it back probably will do the to-string conversion)
     *
     * @param string|int|float|bool|null $value
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
     * @return ScalarEnum|null
     * @throws \Doctrineum\Scalar\Exceptions\UnexpectedValueToEnum
     * @throws \Doctrineum\Scalar\Exceptions\CouldNotDetermineEnumClass
     * @throws \Doctrineum\Scalar\Exceptions\EnumClassNotFound
     * @throws \Granam\ScalarEnum\Exceptions\CanNotCreateInstanceOfAbstractEnum
     */
    public function convertToPHPValue($value, AbstractPlatform $platform): ?ScalarEnumInterface
    {
        return $value === null
            ? null
            : $this->convertToEnum($value);
    }

    /**
     * @param string|int|float|bool $enumValue
     * @return ScalarEnum|ScalarEnumInterface
     * @throws \Doctrineum\Scalar\Exceptions\UnexpectedValueToEnum
     * @throws \Doctrineum\Scalar\Exceptions\CouldNotDetermineEnumClass
     * @throws \Doctrineum\Scalar\Exceptions\EnumClassNotFound
     * @throws \Granam\ScalarEnum\Exceptions\CanNotCreateInstanceOfAbstractEnum
     */
    protected function convertToEnum($enumValue): ScalarEnumInterface
    {
        $enumValue = $this->sanitizeValueForEnumClass($enumValue);
        // class of main enum or its registered sub-type, according to enum type and current value
        $enumClass = static::getEnumClass($enumValue);
        $enumValue = $this->prepareValueForEnum($enumValue);

        try {
            return $enumClass::getEnum($enumValue);
        } catch (CanNotCreateInstanceOfAbstractEnum $canNotCreateInstanceOfAbstractEnum) {
            throw new CanNotCreateInstanceOfAbstractEnum(
                'Enum value ' . ValueDescriber::describe($enumValue) . ' is paired with enum class ' . $enumClass
                . ', but creating an enum by it causes: ' . $canNotCreateInstanceOfAbstractEnum->getMessage()
                . "\nRegistered sub-types are " . (self::$enumSubTypesMap ? \var_export(self::$enumSubTypesMap, true) : "'none'")
                . ' and default enum class for given value ' . ValueDescriber::describe($enumValue)
                . ' is ' . static::getDefaultEnumClass($enumValue)
            );
        }
    }

    /**
     * @param $valueForEnum
     * @return float|int|string|bool
     * @throws \Doctrineum\Scalar\Exceptions\UnexpectedValueToEnum
     */
    protected function sanitizeValueForEnumClass($valueForEnum)
    {
        try {
            return ToScalar::toScalar($valueForEnum, true /* strict, without null */);
        } catch (\Granam\Scalar\Tools\Exceptions\WrongParameterType $exception) {
            throw new Exceptions\UnexpectedValueToEnum(
                'Unexpected value to convert. Expected scalar or null, got '
                . ValueDescriber::describe($valueForEnum),
                $exception->getCode(),
                $exception
            );
        }
    }

    /**
     * @param float|int|string|bool $valueForEnum
     * @return float|int|string|bool
     */
    protected function prepareValueForEnum($valueForEnum)
    {
        return $valueForEnum; // nothing to change here - intentioned for overload
    }

    /**
     * @param int|float|string|bool $enumValue
     * @return string|ScalarEnum Enum class absolute name
     * @throws \Doctrineum\Scalar\Exceptions\CouldNotDetermineEnumClass
     * @throws \Doctrineum\Scalar\Exceptions\EnumClassNotFound
     */
    protected static function getEnumClass($enumValue): string
    {
        if (!\array_key_exists(static::getSubTypeEnumInnerNamespace(), self::$enumSubTypesMap)
            || \count(self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()]) === 0
        ) {
            // no subtype is registered at all
            return static::getDefaultEnumClass($enumValue);
        }

        foreach (self::$enumSubTypesMap[static::getSubTypeEnumInnerNamespace()] as $subTypeEnumClass => $subTypeEnumValueRegexp) {
            if (\preg_match($subTypeEnumValueRegexp, (string)$enumValue)) {
                return $subTypeEnumClass;
            }
        }

        // no subtype matched
        return static::getDefaultEnumClass($enumValue);
    }

    /**
     * @param int|float|string|bool $enumValue
     * @return string
     * @throws \Doctrineum\Scalar\Exceptions\CouldNotDetermineEnumClass
     * @throws \Doctrineum\Scalar\Exceptions\EnumClassNotFound
     */
    protected static function getDefaultEnumClass($enumValue): string
    {
        $enumTypeClass = static::class;
        $enumInSameNamespace = \preg_replace('~Type$~', '', $enumTypeClass);
        if ($enumInSameNamespace === $enumTypeClass) {
            throw new Exceptions\CouldNotDetermineEnumClass('Enum class could not be parsed from enum type class ' . $enumTypeClass);
        }
        if (\class_exists($enumInSameNamespace)) {
            return $enumInSameNamespace;
        }

        $inParentNamespace = \preg_replace('~\\\(\w+)\\\(\w+)$~', '\\\$2', $enumInSameNamespace);
        if (\class_exists($inParentNamespace)) {
            return $inParentNamespace;
        }

        throw new Exceptions\EnumClassNotFound(
            'Default enum class not found for enum type ' . static::class
            . ' (potential sub-types have not matched enum value ' . ValueDescriber::describe($enumValue) . ')'
        );
    }

    /**
     * If this Doctrine Type maps to an already mapped database type,
     * reverse schema engineering can't take them apart. You need to mark
     * one of those types as commented, which will have Doctrine use an SQL
     * comment to type-hint the actual Doctrine Type.
     *
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
     * @return boolean
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}


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

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\DropDownList;

/**
 * InputText class is element for input text
 *
 * @package openbiz.bin.easy.element
 * @author Jixian W.
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class PageSelector extends DropDownList
{

	//protected $formPrefix = true;
    public function getList(){
    	$formobj=$this->getFormObj();
    	$list=array();
    	for($i=1;$i<=$formobj->totalPages;$i++){
    		array_push($list,array("val"=>$i,"txt"=>$i));
    	}
    	return $list;
    }

}

?>


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

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolver as BaseControllerResolver;

/**
 * Controller resolver
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class ControllerResolver extends BaseControllerResolver
{
    /**
     * @var Container
     */
    protected $container;

    /**
     * @param Container $container
     * @param LoggerInterface $logger
     */
    public function __construct(Container $container, LoggerInterface $logger = null)
    {
        $this->container = $container;
        parent::__construct($logger);
    }

    /**
     * @param string $controller
     *
     * @return array
     *
     * @throws \InvalidArgumentException
     */
    protected function createController($controller)
    {
        list($class, $method) = explode('::', $controller, 2);

        if (!class_exists($class)) {
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
        }

        $controller = new $class();
        if ($controller instanceof ControllerInterface) {
            $controller->setContainer($this->container);
        }

        return [
            $controller,
            $method
        ];
    }
}


<?php

namespace CatLab\Charon\Laravel\Middleware;

use Illuminate\Http\Request;

/**
 * Class AbstractMiddleware
 * @package CatLab\Charon\Laravel\Middleware
 */
abstract class AbstractMiddleware
{
    /**
     * Get input value from a specific container.
     * @param Request $request
     * @param string $in
     * @param string $name
     * @return mixed
     */
    protected function getInput($request, $in, $name)
    {
        switch ($in)
        {
            case 'header':
                return $request->header($name);

            case 'query':
                return $request->query($name);

            case 'path':
                return $request->route($name);

            default:
                throw new \InvalidArgumentException(
                    get_class($this) . " doesn't know how to handle '" . $in . "' parameters"
                );
        }
    }

    /**
     * @param Request $request
     * @param string $in
     * @param string $name
     * @param mixed $value
     * @return void
     */
    protected function setInput($request, $in, $name, $value)
    {
        switch ($in)
        {
            case 'header':
                $request->headers->set($name, $value);
                break;

            case 'query':
                $request->query->set($name, $value);
                break;

            case 'path':
                $route = call_user_func($request->getRouteResolver());
                $route->parameter($name, $value);
                break;

            default:
                throw new \InvalidArgumentException(
                    get_class($this) . " doesn't know how to handle " . $in . " parameters"
                );
        }
    }
}


<?php

namespace MisterPaladin\Cleaner\Commands;

use Illuminate\Console\Command;
use File;
use Carbon\Carbon;

class Cleaner extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cleaner:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run garbage cleaner';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->config = config('cleaner');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        foreach ($this->config as $file) {
            $seconds = $this->convertToSeconds($file['expires']);

            if (!is_array($file['path'])) {
                $file['path'] = [$file['path']];
            }

            foreach ($file['path'] as $key => $filepath) {
                if (ends_with($filepath, '*')) {
                    $glob = glob($filepath);
                    unset($file['path'][$key]);
                    $file['path'] = array_merge($file['path'], $glob);
                }
            }

            $this->delete($file, $seconds);
        }
    }

    /**
     * Delete file or directory at given path
     *
     * @param  array $file [Config item]
     * @param  int $expires [Expiration in seconds]
     * @return void
     */
    protected function delete($file, $expires)
    {
        if (!is_array($file['path'])) {
            $file['path'] = [$file['path']];
        }

        foreach ($file['path'] as $path) {
            if (File::exists($path)) {
                if ((time() - File::lastModified($path)) >= $expires) {
                    if (!empty($file['before']) && is_callable($file['before'])) {
                        $file['before']($path);
                    }
                    if (File::isDirectory($path)) {
                        File::deleteDirectory($path);
                    } else {
                        File::delete($path);
                    }
                    if (!empty($file['after']) && is_callable($file['after'])) {
                        $file['after']($path);
                    }
                }
            }
        }
    }

    /**
     * Convert config to seconds
     *
     * @param  array $expires  [Config item expires value]
     * @return int
     */
    protected function convertToSeconds($expires)
    {
        $seconds = 0;

        if (isset($expires['seconds'])) {
            $seconds += $expires['seconds'];
        }

        if (isset($expires['minutes'])) {
            $seconds += $expires['minutes'] * 60;
        }

        if (isset($expires['hours'])) {
            $seconds += $expires['hours'] * 60 * 60;
        }

        if (isset($expires['days'])) {
            $seconds += $expires['days'] * 24 * 60 * 60;
        }

        if (isset($expires['weeks'])) {
            $seconds += $expires['weeks'] * 7 * 24 * 60 * 60;
        }

        if (isset($expires['months'])) {
            $seconds += $expires['months'] * 30 * 7 * 24 * 60 * 60;
        }

        if (isset($expires['years'])) {
            $seconds += $expires['years'] * 365 * 30 * 7 * 24 * 60 * 60;
        }

        return $seconds;
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

/**
 * Pomocna trida pro retezce
 *
 * @author Attreid <attreid@gmail.com>
 */
class Strings extends \Nette\Utils\Strings
{

	/**
	 * Vrati klicova slova z textu
	 * @param string $text
	 * @param int $maxLen
	 * @return string
	 */
	public static function getKeyWords(string $text, int $maxLen = 60): string
	{
		$keyWords = [];
		// nalezeni vsech linku v textu
		preg_match_all('/<a[^>]*>[^<]+<\/a>/i', $text, $found);
		if (isset($found[0])) {
			foreach ($found[0] as $kw) {
				$keyWords[] = self::lower(self::trim(strip_tags($kw)));
			}
		}

		// h2 a strong
		preg_match_all('/<(h2|strong)[^>]*>[^<]+<\/(h2|strong)>/i', $text, $found);
		if (isset($found[0])) {
			foreach ($found[0] as $kw) {
				$keyWords[] = self::lower(self::trim(strip_tags($kw)));
			}
		}

		$result = implode(', ', array_unique($keyWords));

		return self::truncate($result, $maxLen, '');
	}

	/**
	 * Vrati email z textu
	 * @param string $text
	 * @return string[]
	 */
	public static function findEmails(string $text): array
	{
		$result = [];
		preg_match_all('/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i', $text, $result);
		return isset($result[0]) ? $result[0] : [];
	}

	/**
	 * @param string $haystack
	 * @param string|string[] $needle
	 * @return bool
	 */
	public static function contains($haystack, $needle): bool
	{
		if (!is_array($needle)) {
			$needle = [$needle];
		}
		return self::containsArray($haystack, $needle) !== null;
	}

	/**
	 * Vrati retezec, ktery se v textu vyskytuje
	 * @param string $haystack
	 * @param string[] $needle
	 * @return string|null
	 */
	public static function containsArray(string $haystack, array $needle): ?string
	{
		foreach ($needle as $query) {
			if (parent::contains($haystack, $query)) {
				return $query;
			}
		}
		return null;
	}

	/**
	 * @param string $ip IP ve formatu IPV4 napr. 127.0.0.1
	 * @param string $range IP/CIDR maska napr. 127.0.0.0/24, take 127.0.0.1 je akceptovano jako /32
	 * @return bool
	 */
	public static function ipInRange(string $ip, string $range): bool
	{
		if (strpos($range, '/') == false) {
			$range .= '/32';
		}
		// $range je v IP/CIDR formatu (127.0.0.1/24)
		list($range, $netmask) = explode('/', $range, 2);
		$range_decimal = ip2long($range);
		$ip_decimal = ip2long($ip);
		$wildcard_decimal = pow(2, (32 - $netmask)) - 1;
		$netmask_decimal = ~$wildcard_decimal;
		return (($ip_decimal & $netmask_decimal) == ($range_decimal & $netmask_decimal));
	}
}


<?php

namespace Gwsn\HttpRequest;

use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;

class BaseProxyConnector extends BaseConnector {

	private $endpointsConfig;

	private $endpointRequiredKeys = [ 'name', 'endpoint', 'auth', 'auth_type', 'auth_user', 'auth_pass', 'proxy' ];

	public function __construct() {
		parent::__construct();
		$this->proxy = true;

		// Define the default statuscodes
		$this->setValidStatusCodes( [
			                            200,
			                            201,
			                            202,
			                            203,
			                            204,
			                            205,
			                            206,
			                            400,
			                            401,
			                            402,
			                            403,
			                            404,
			                            405,
			                            406,
			                            407,
			                            408,
			                            410,
			                            501,
		                            ] );
	}

	/**
	 * Fetch the endpoints from config.
	 *
	 * @return array
	 *
	 * @throws \Exception
	 */
	protected function getEndpoints() {
		// Get Endpoint Configs

		try {
			$endpoints = ApiEndPoints::getEndpoints();

			return $this->setEndpoints( $endpoints );

		}
		catch ( \Exception $exception ) {
			throw $exception;
		}
	}

	/**
	 * Fetch the endpoints from config.
	 *
	 * @param array $endpoints
	 *
	 * @return array
	 * @throws \Exception
	 */
	public function setEndpoints( array $endpoints = [] ) {
		if ( empty( $endpoints ) ) {
			throw new \Exception( 'Endpoints variable is empty.' );
		}

		foreach ( $endpoints as $endpoint ) {
			// Check if required configurations are set
			foreach ( $this->endpointRequiredKeys as $key ) {
				if ( ! isset( $endpoint[ $key ] ) ) {
					throw new \Exception( 'Endpoint (' . $endpoint . ') is not defined correctly, the config key (' . $key . ') is not defined' );
				}
			}
		}

		$this->endpointsConfig = $endpoints;
	}

	/**
	 * @param null $endpoint
	 *
	 * @return array
	 * @throws \Exception
	 */
	protected function getEndpointConfig( $endpoint = null ) {
		if ( $endpoint === null ) {
			throw new \Exception( 'Endpoint is null' );
		}

		if ( ! isset( $this->endpointsConfig[ $endpoint ] ) ) {
			throw new \Exception( 'Endpoint is not defined in the config.' );
		}

		if ( ! is_array( $this->endpointsConfig ) || $this->endpointsConfig === [] ) {
			throw new \Exception( 'There are not Endpoints configurations set, please define the endpoints first.' );
		}

		return $this->endpointsConfig[ $endpoint ];
	}

	/**
	 * Redirect the API call to the micro service
	 *
	 * @param Request $request
	 * @param string  $endpoint
	 * @param string  $path
	 * @param string  $responseType
	 *
	 * @return mixed
	 * @throws \Exception
	 */
	public function redirect( Request $request, $endpoint, $path, $responseType = 'json' ) {
		// Set the Endpoints
		$this->getEndpoints();

		// Get Endpoint config.
		$this->setBaseUri( $this->getEndpointConfig( $endpoint )['endpoint'] );

		// Get Endpoint AUTH
		// $this->setAuthHeaders();

		// Get Required variables for the endpoint.
		// void

		// Add Proxy to request
		$request->attributes->add( [
			                           'proxy' => [
				                           'host'          => $this->getBaseUri(),
				                           'path'          => $path,
				                           'response_type' => $responseType,
			                           ],
		                           ] );

		// Create a call to the endpoint
		$this->prepareCall( null );

		// Prepare headers:
		$headers = $request->headers->all();
		if ( isset( $headers['host'] ) ) {
			unset( $headers['host'] );
		}

		// Set proxy headers
		$headers['bizhost-request-identifier'] = [ $request->get( 'bizhost-request-identifier' , null) ];
		$headers['bizhost-session-identifier'] = [ $request->get( 'bizhost-session-identifier' , null) ];

		// Prepare data
		$data = $request->all();

		// Execute call
		$this->execute( $request->getMethod(), $path, $data, $headers );

		// Catch the results
		return $this->getResponse( $responseType );
	}

	/**
	 * @param Request $request
	 * @param null    $method
	 * @param null    $endpoint
	 * @param null    $path
	 * @param array   $data
	 * @param array   $headers
	 * @param string  $responseType
	 *
	 * @return mixed
	 * @throws \Exception
	 */
	public function call( Request $request = null, $method = null, $endpoint = null, $path = null, $data = [], $headers = [], $responseType = 'json' ) {
		// Set the Endpoints
		$this->getEndpoints();

		// Get Endpoint config.
		$this->setBaseUri( $this->getEndpointConfig( $endpoint )['endpoint'] );

		// Add Proxy to request
		$request->attributes->add( [
			                           'proxy' => [
				                           'host'          => $this->getBaseUri(),
				                           'path'          => $path,
				                           'response_type' => $responseType,
			                           ],
		                           ] );

		// Create a call to the endpoint
		$this->prepareCall( null );

		// Prepare headers:
		$headers = array_merge($request->headers->all(), $headers);
		if ( isset( $headers['host'] ) ) {
			unset( $headers['host'] );
		}

		if($responseType === 'json') {
			$headers['content-type'] = 'application/json';
		}
		// Set proxy headers
		$headers['bizhost-request-identifier'] = [ $request->get( 'bizhost-request-identifier' , null) ];
		$headers['bizhost-session-identifier'] = [ $request->get( 'bizhost-session-identifier' , null) ];

		// Execute call
		$this->execute( $method, $path, $data, $headers );

		// Catch the results
		return $this->getResponse( $responseType );
	}

	/**
	 * Set the Guzzle Response
	 *
	 * @param Response $response
	 *
	 * @return $this;
	 */
	protected function setResponse( Response $response ) {
		$this->response = ( new BaseProxyResponse )->setResponse( $response );

		return $this;
	}

}


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

namespace DdvPhp\DdvUtil\Laravel;

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

class EloquentCollection extends \Illuminate\Database\Eloquent\Collection
{
    /**
     * 小写下滑杠转驼峰
     * @param true|false $isConversionOriginal [是否强制转换源]
     * @return Model|static|$this [请求对象]
     */
    public function toHump($isConversionOriginal = false){
        $this->map(function ($model){
            if (empty($model)){
                return;
            }
            is_object($model) && method_exists($model, 'toHump') && $model->toHump();
        });
        return $this;
    }

    /**
     * @param $fn
     * @return Model|static|$this [请求对象]
     */
    public function mapLists($fn){
        if ($fn instanceof Closure){
            if(is_array($this) || is_object($this)){
                foreach ($this as $key => $item){
                    $fn($item, $key);
                    $this[$key] = $item;
                }
            }
        }
        return $this;
    }

}


<?php
/**
 * OAuth 2.0 Abstract token
 *
 */

namespace OAuth2\Server\Entity;

use OAuth2\Server\AbstractServer;
use OAuth2\Server\Util\SecureKey;

/**
 * Abstract token class
 */
abstract class AbstractTokenEntity
{
    /**
     * Token identifier
     *
     * @var string
     */
    protected $id;

    /**
     * Associated session
     *
     * @var \OAuth2\Server\Entity\SessionEntity
     */
    protected $session;

    /**
     * Session scopes
     *
     * @var \OAuth2\Server\Entity\ScopeEntity[]
     */
    protected $scopes;

    /**
     * Token expire time
     *
     * @var int
     */
    protected $expireTime = 0;

    /**
     * Authorization or resource server
     *
     * @var \OAuth2\Server\AbstractServer
     */
    protected $server;

	/**
	 * Is new Token or Not
	 *
	 * @var Boolean
	 */
	protected $isNew = true;

    /**
     * __construct
     *
     * @param \OAuth2\Server\AbstractServer $server
     *
     * @return self
     */
    public function __construct(AbstractServer $server)
    {
        $this->server = $server;

        return $this;
    }

    /**
     * Set session
     *
     * @param \OAuth2\Server\Entity\SessionEntity $session
     *
     * @return self
     */
    public function setSession(SessionEntity $session)
    {
        $this->session = $session;

        return $this;
    }

    /**
     * Set the expire time of the token
     *
     * @param integer $expireTime Unix time stamp
     *
     * @return self
     */
    public function setExpireTime($expireTime)
    {
        $this->expireTime = $expireTime;

        return $this;
    }

    /**
     * Return token expire time
     *
     * @return int
     */
    public function getExpireTime()
    {
        return $this->expireTime;
    }

    /**
     * Is the token expired?
     *
     * @return bool
     */
    public function isExpired()
    {
        return ((time() - $this->expireTime) > 0);
    }

    /**
     * Set token ID
     *
     * @param string $id Token ID
     *
     * @return self
     */
    public function setId($id = null)
    {
		if ($id != null){
			$this->isNew = false;
			$this->id = $id;
		}else{
			$this->id = SecureKey::generate();
		}
        return $this;
    }

    /**
     * Get the token ID
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Associate a scope
     *
     * @param \OAuth2\Server\Entity\ScopeEntity $scope
     *
     * @return self
     */
    public function associateScope(ScopeEntity $scope)
    {
        if (!isset($this->scopes[$scope->getId()])) {
            $this->scopes[$scope->getId()] = $scope;
        }

        return $this;
    }

    /**
     * Format the local scopes array
     *
     * @param  \OAuth2\Server\Entity\ScopeEntity[]
     *
     * @return array
     */
    protected function formatScopes($unformatted = [])
    {
        if (is_null($unformatted)) {
            return [];
        }

        $scopes = [];
        foreach ($unformatted as $scope) {
            if ($scope instanceof ScopeEntity) {
                $scopes[$scope->getId()] = $scope;
            }
        }

        return $scopes;
    }

    /**
     * Returns the token as a string if the object is cast as a string
     *
     * @return string
     */
    public function __toString()
    {
        if ($this->id === null) {
            return '';
        }

        return $this->id;
    }

    /**
     * Expire the token
     *
     * @return void
     */
    abstract public function expire();

    /**
     * Save the token
     *
     * @return void
     */
    abstract public function save();
}


<?php

namespace Tree6bee\Queue;

use Tree6bee\Queue\Drivers\Jobs\JobInterface;

class Worker
{
    /**
     * @var Queue
     */
    protected $queue;

    /**
     * @var string 需要处理的 queue
     */
    protected $queueTube;

    /**
     * Create a new queue worker.
     *
     * @param Queue $queue
     * @param string $queueTube
     */
    public function __construct(Queue $queue, $queueTube = '')
    {
        $this->queue = $queue;
        $this->queueTube = $queueTube;
    }

    /**
     * Listen to the given queue in a loop.
     *
     * @param int $sleep 没有新的有效任务产生时的休眠时间 (单位: 秒)
     * @param int $memoryLimit worker 内存限制 (单位: mb)
     */
    public function daemon($sleep = 60, $memoryLimit = 128)
    {
        $memoryLimit = $memoryLimit * 1024 * 1024;
        $startTime = time();
        while (true) {
            $ret = $this->runNextJob();

            if (! $ret) { //没有获取到job
                sleep($sleep);
            }

            ($this->memoryExceeded($memoryLimit) || $this->queueShouldRestart($startTime)) &&
                $this->stop();
        }
    }

    public function runNextJob()
    {
        $job = $this->queue->pop($this->queueTube);

        if ($job) {
            $payload = json_decode($job->getRawBody(), true);

            if (JSON_ERROR_NONE !== json_last_error()) {
                throw new \InvalidArgumentException('Unable to create payload: '.json_last_error_msg());
            }

            if (isset($payload['type']) && $payload['type'] === Queue::TYPE) {
                $obj = unserialize($payload['job']);

                if ($obj instanceof Job) {
                    $this->process($job, $obj);

                    return true;
                }
            }

            throw new \Exception('不能识别的 job 类型, jobId: ' . $job->getJobId());
        } else {
            return false;
        }
    }

    /**
     * !!! 对 队列的 bury 增加监控，防止失败未处理的 job 过多
     * @param JobInterface $job 队列里的每个 job 对象
     * @param Job $obj job 中反序列化后具体的实例对象 应用开发者定义的 job
     */
    protected function process(JobInterface $job, Job $obj)
    {
        try {
            $obj->setJob($job);

            $this->handleWithObj($obj);

            $job->delete();
        } catch (\Exception $e) {
            if ($job->attempts() < $obj->tries) { //小于最大尝试次数 release
                $job->release();
            } else { //超过了放到失败中
                $job->bury();

                $this->logProcessError($e);
            }
        }
    }

    /**
     * 记录 job 执行失败的日志
     * !!! 此处根据具体的框架应用进行重载来记录符合业务的日志格式
     * !!! you can override this method to log the job processing error, etc...
     * @param \Exception $e
     *
     * @return void
     */
    protected function logProcessError(\Exception $e)
    {
        echo (string) $e;

        return ;
    }

    /**
     * !!! 此处根据具体的框架应用进行重载，方便注入框架的服务对象等
     * !!! you can override this method, so that the application job can init with more obj, etc...
     *
     * @param Job $obj job 中反序列化后具体的实例对象 应用开发者定义的 application job
     */
    protected function handleWithObj(Job $obj)
    {
        //override like: $obj->setApp($app);
        $obj->handle();
    }

    /**
     * Determine if the memory limit has been exceeded.
     * @param  int   $memoryLimit
     *
     * @return bool
     */
    protected function memoryExceeded($memoryLimit)
    {
        return memory_get_usage() >= $memoryLimit;
    }

    /**
     * !!! override 采用cache存储 重启命令执行时间 和 worker $startTime 比较
     * @param $startTime
     * @return bool
     */
    protected function queueShouldRestart($startTime)
    {
        return false;
    }

    protected function stop()
    {
        throw new \Exception('队列 worker 内存超过设定阈值, queue: ' . $this->queueTube);
    }
}


<?php

namespace Environaut\Config;

/**
 * Class that wraps an associative array for
 * more convenient access of keys and values.
 */
class Parameters
{
    /**
     * @var array
     */
    protected $parameters = array();

    /**
     * Create a new instance with the given parameters as
     * initial value set.
     *
     * @param array $parameters
     */
    public function __construct(array $parameters = array())
    {
        $this->parameters = $parameters;
    }

    /**
     * Returns the value for the given key.
     *
     * @param string $key name of key
     * @param mixed $default value to return if key doesn't exist
     *
     * @return mixed value for that key or default given
     */
    public function get($key, $default = null)
    {
        if (isset($this->parameters[$key]) || array_key_exists($key, $this->parameters)) {
            return $this->parameters[$key];
        }

        return $default;
    }

    /**
     * Sets a given value for the specified key.
     *
     * @param string $key name of entry
     * @param mixed $value value to set for the given key
     *
     * @return mixed the value set
     */
    public function set($key, $value)
    {
        return $this->parameters[$key] = $value;
    }

    /**
     * Returns whether the key exists or not.
     *
     * @param string $key name of key to check
     *
     * @return bool true, if key exists; false otherwise
     */
    public function has($key)
    {
        if (isset($this->parameters[$key]) || array_key_exists($key, $this->parameters)) {
            return true;
        }

        return false;
    }

    /**
     * Returns all first level key names.
     *
     * @return array of keys
     */
    public function getKeys()
    {
        return array_keys($this->parameters);
    }

    /**
     * Returns the data as an associative array.
     *
     * @return array with all data
     */
    public function toArray()
    {
        return $this->parameters;
    }

    /**
     * Delete all key/value pairs.
     */
    public function clear()
    {
        $this->parameters = array();
    }
}


<?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\Auth\Providers;

use Nameless\Modules\Database;
use Nameless\Utilities\StringHelper;

/**
 * DBUserProvider class
 *
 * @author Corpsee <poisoncorpsee@gmail.com>
 */
class DBUserProvider implements UserProviderInterface
{
    /**
     * @var Database
     */
    private $database;

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

    /**
     * @param string $user_name
     *
     * @return array|false
     */
    public function getUserByName($user_name)
    {
        return $this->database->selectOne("SELECT `id`, `password` FROM `users` WHERE `username` = ?", [$user_name]);
    }

    /**
     * @param string $user_name
     *
     * @return array|false
     */
    public function getUserGroups($user_name)
    {
        $groups = $this->database->selectOne("SELECT `groups` FROM `users` WHERE `username` = ?", [$user_name]);

        if ($groups) {
            return StringHelper::toArray($groups['groups']);
        }
        return false;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: tamaskovacs
 * Date: 2017. 01. 22.
 * Time: 17:14
 */

namespace Callisto;

class Oauth
{
	/**
	 * OAuth2 access token.
	 *
	 * @var string
	 */
	private $accessToken;

	/**
	 * OAuth2 access token secret.
	 *
	 * @var string
	 */
	private $accessTokenSecret;

	/**
	 * Twitter app consumer key.
	 *
	 * @var string
	 */
	private $consumerKey;

	/**
	 * Twitter app consumer secret.
	 *
	 * @var string
	 */
	private $consumerSecret;

	/**
	 * Oauth constructor.
	 *
	 * @param string $consumerKey
	 * @param string $consumerSecret
	 * @param string $accessToken
	 * @param string $accessTokenSecret
	 */
	public function __construct(string $consumerKey, string $consumerSecret, string $accessToken, string $accessTokenSecret)
	{
		$this->consumerKey = $consumerKey;
		$this->consumerSecret = $consumerSecret;
		$this->accessToken = $accessToken;
		$this->accessTokenSecret = $accessTokenSecret;
	}

	/**
	 * Returns the parameters for an OAuth request.
	 *
	 * @return array
	 */
	private function getOauthParams() : array
	{
		return [
			'oauth_consumer_key' => $this->consumerKey,
			'oauth_nonce' => md5(time() . rand()),
			'oauth_signature_method' => 'HMAC-SHA1',
			'oauth_timestamp' => time(),
			'oauth_token' => $this->accessToken,
			'oauth_version' => '1.0',
		];
	}

	/**
	 * Generates the HTTP request string.
	 *
	 * @param array $params
	 * @param $httpMethod
	 * @param $baseUrl
	 * @param $endPoint
	 * @return string
	 */
	public function getOauthRequest(array $params, $httpMethod, $baseUrl, $endPoint) : string
	{
		$signatureParams = array_merge($params, $this->getOauthParams());
		$signatureParams['oauth_signature'] = $this->getOauthSignature($signatureParams, $httpMethod, $baseUrl . $endPoint);

		$contentParams = [];
		foreach ($params as $key => $param) {
			$contentParams[] = $key . '=' . rawurlencode($param);
		}

		$content = implode('&', $contentParams);

		return $httpMethod . " " . $endPoint . " HTTP/1.1\r\n"
		."Accept: */*\r\n"
		."Connection: close\r\n"
		."User-Agent: Callisto API\r\n"
		."Content-Type: application/x-www-form-urlencoded\r\n"
		."Authorization: OAuth realm=\"\",oauth_consumer_key=\"" . $signatureParams['oauth_consumer_key'] . "\","
		."oauth_nonce=\"" . $signatureParams['oauth_nonce'] . "\","
		."oauth_signature_method=\"" . $signatureParams['oauth_signature_method'] . "\","
		."oauth_timestamp=\"" . $signatureParams['oauth_timestamp'] . "\","
		."oauth_version=\"" . $signatureParams['oauth_version'] . "\","
		."oauth_token=\"" . $signatureParams['oauth_token'] . "\","
		."oauth_signature=\"" . rawurlencode($signatureParams['oauth_signature']) . "\"\r\n"
		."Content-Length: " . strlen($content) . "\r\n"
		."Host: stream.twitter.com:443\r\n\r\n"
		.$content;
	}

	/**
	 * Generates an OAuth signature.
	 *
	 * @param array $params
	 * @param $httpMethod
	 * @param $url
	 * @return string
	 */
	private function getOauthSignature(array $params, $httpMethod, $url) : string
	{
		$urlParams = [];
		foreach ($params as $key => $value) {
			$params[$key] = rawurlencode($value);
			$urlParams[$key] = $key . '=' . $params[$key];
		}

		ksort($urlParams);
		$parameterString = implode('&', $urlParams);
		$signatureBaseString = strtoupper($httpMethod) .
			'&' . rawurlencode($url) .
			'&' . rawurlencode($parameterString);

		$signingKey = rawurlencode($this->consumerSecret) . '&' . rawurlencode($this->accessTokenSecret);
		$oauthSignature = base64_encode(hash_hmac('sha1', $signatureBaseString, $signingKey, true));

		return $oauthSignature;
	}
}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Server\Capabilities;

use Innmind\Rest\Client\{
    Server\Capabilities as CapabilitiesInterface,
    Definition\HttpResource,
};
use Innmind\Immutable\{
    SetInterface,
    MapInterface,
};

final class RefreshLimitedCapabilities implements CapabilitiesInterface
{
    private $capabilities;
    private $isFresh = false;

    public function __construct(CapabilitiesInterface $capabilities)
    {
        $this->capabilities = $capabilities;
    }

    /**
     * {@inheritdoc}
     */
    public function names(): SetInterface
    {
        return $this->capabilities->names();
    }

    public function get(string $name): HttpResource
    {
        return $this->capabilities->get($name);
    }

    /**
     * {@inheritdoc}
     */
    public function definitions(): MapInterface
    {
        return $this->capabilities->definitions();
    }

    /**
     * {@inheritdoc}
     */
    public function refresh(): CapabilitiesInterface
    {
        if ($this->isFresh) {
            return $this;
        }

        $this->capabilities->refresh();
        $this->isFresh = true;

        return $this;
    }
}


<?php

namespace Environaut\Report\Results;

use Environaut\Checks\ICheck;
use Environaut\Report\Results\IResult;
use Environaut\Report\Results\Messages\IMessage;
use Environaut\Report\Results\Settings\ISetting;

/**
 * Result that checks provide for a report.
 */
class Result implements IResult
{
    /**
     * Check this result belongs to.
     *
     * @var ICheck check instance
     */
    protected $check;

    /**
     * Messages from the check.
     *
     * @var array of IMessage instances
     */
    protected $messages = array();

    /**
     * Settings from the check.
     *
     * @var array of ISetting instances
     */
    protected $settings = array();

    /**
     * Settings from the check that should be available from cache on re-execution of the check.
     *
     * @var array of ISetting instances
     */
    protected $cachable_settings = array();

    /**
     * Status of the result. See available constants on IResult.
     *
     * @var string status of this result
     */
    protected $status = self::UNEXECUTED;

    /**
     * Create a new Result instance.
     */
    public function __construct()
    {
        $this->check = null;
        $this->messages = array();
        $this->settings = array();
        $this->cachable_settings = array();
        $this->status = self::UNEXECUTED;
    }

    /**
     * Adds the given message to the internal list of messages.
     *
     * @param \Environaut\Report\Results\Messages\IMessage $message
     *
     * @return Result this instance for fluent API support
     */
    public function addMessage(IMessage $message)
    {
        $this->messages[] = $message;
        return $this;
    }

    /**
     * Adds the given setting to the internal lists of settings.
     *
     * @param ISetting $setting setting to add to internal lists of settings
     * @param bool $cachable whether or not the setting may be put into a cache for reuse on re-execution of the check
     *
     * @return Result this instance for fluent API support
     */
    public function addSetting(ISetting $setting, $cachable = true)
    {
        $this->settings[] = $setting;

        if (true === $cachable) {
            $this->cachable_settings[] = $setting;
        }

        return $this;
    }

    /**
     * Adds the given setting to the internal list of settings.
     *
     * @param array $settings array with ISetting implementing instances to add
     * @param bool $cachable whether or not the setting may be put into a cache for reuse on re-execution of the check
     *
     * @return Result this instance for fluent API support
     */
    public function addSettings(array $settings, $cachable = true)
    {
        foreach ($settings as $setting) {
            if ($setting instanceof ISetting) {
                $this->addSetting($setting);
            }
        }

        return $this;
    }

    /**
     * Replaces the internal list of messages with the given list.
     *
     * @param array $messages array with IMessage implementing instances
     *
     * @return Result this instance for fluent API support
     */
    public function setMessages(array $messages)
    {
        $this->messages = $messages;

        return $this;
    }

    /**
     * Returns the internal list of messages emitted by the processed check.
     *
     * @return array of IMessage implementing instances
     */
    public function getMessages()
    {
        return $this->messages;
    }

    /**
     * Returns the internal list of settings emitted by the processed check.
     *
     * @param string $groups group names of settings to return
     * @param integer $flag flag value the settings should belong to
     *
     * @return array of ISetting implementing instances matching the arguments
     */
    public function getSettings($groups = null, $flag = null)
    {
        return $this->getFiltered($this->settings, $groups, $flag);
    }

    /**
     * Returns the internal list of cachable settings emitted by the processed check.
     *
     * @param string $groups group names of settings to return
     * @param integer $flag flag value the settings should belong to
     *
     * @return array of ISetting implementing instances matching the arguments
     */
    public function getCachableSettings($groups = null, $flag = null)
    {
        return $this->getFiltered($this->cachable_settings, $groups, $flag);
    }

    /**
     * Return all settings or the settings of the specified groups as an array.
     *
     * @param string $groups group names of settings to return
     * @param integer $flag flag value the settings should belong to
     *
     * @return array all settings (for the specified groups); empty array if groups don't exist.
     */
    public function getSettingsAsArray($groups = null, $flag = null)
    {
        return $this->getFilteredAsArray($this->settings, $groups, $flag);
    }

    /**
     * Return all cachable settings or the cachable settings of the specified groups as an array.
     *
     * @param string $groups group names of cachable settings to return
     * @param integer $flag flag value the settings should belong to
     *
     * @return array all cachable settings (for the specified groups); empty array if groups don't exist.
     */
    public function getCachableSettingsAsArray($groups = null, $flag = null)
    {
        return $this->getFilteredAsArray($this->cachable_settings, $groups, $flag);
    }

    /**
     * Sets the status of the current result (which may be of interest for the later export and cache writing).
     *
     * @param string $status one of the constants from IResult (like IResult::SUCCESS or IResult::FAIL)
     *
     * @return Result this instance for fluent API support
     */
    public function setStatus($status = self::INVALID)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Returns the current status of this result (usually one of the IResult::SUCCESS or IResult::FAIL constants).
     *
     * @return string status of this result instance
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Sets the check instance this result belongs to.
     *
     * @param \Environaut\Checks\ICheck $check check this result belongs to
     *
     * @return Result this instance for fluent API support
     */
    public function setCheck(ICheck $check)
    {
        $this->check = $check;

        return $this;
    }

    /**
     * Returns the check instance this result belongs to.
     *
     * @return \Environaut\Checks\ICheck check instance this result belongs to
     */
    public function getCheck()
    {
        return $this->check;
    }

    /**
     * Returns all settings from the given array that match the groups and flag.
     *
     * @param array $all_settings array of ISetting implementing classes
     * @param string $groups group names of settings to return
     * @param integer $flag flag value the settings should belong to
     *
     * @return array of entries from all_settings that match the given groups and flag
     */
    protected function getFiltered(array $all_settings = array(), $groups = null, $flag = null)
    {
        $settings = array();

        foreach ($all_settings as $setting) {
            if ($setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                $settings[] = $setting;
            }
        }

        return $settings;
    }

    /**
     * Returns all or just the matching settings of the given groups as an associative array.
     *
     * @param array $all_settings array of ISetting implementing setting instances
     * @param string $group name of group to filter given settings for
     * @param integer $flag flag value the setting must be matching
     *
     * @return array with associative arrays (for each setting)
     */
    protected function getFilteredAsArray(array $all_settings, $groups = null, $flag = null)
    {
        $settings = array();

        foreach ($all_settings as $setting) {
            if ($setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                $settings[] = $setting->toArray();
            }
        }

        return $settings;
    }
}


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

namespace Openbizx\Easy;

use Openbizx\Object\MetaObject;
use Openbizx\Object\UIControlInterface;

/**
 * HTMLTree class is the base class of HTML tree
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @since 1.2
 * @access public
 */
class HTMLTree extends MetaObject implements UIControlInterface
{
    protected $nodesXml = null;

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

    /**
     * Read Metadata from xml array
     *
     * @param array $xmlArr
     */
    protected function readMetadata(&$xmlArr)
    {
        $this->objectName = $xmlArr["TREE"]["ATTRIBUTES"]["NAME"];
        $this->package = $xmlArr["TREE"]["ATTRIBUTES"]["PACKAGE"];
        $this->className = $xmlArr["TREE"]["ATTRIBUTES"]["CLASS"];

        $this->nodesXml = $xmlArr["TREE"]["NODE"];
    }

    /**
     * Render HTML Tree
     *
     * @return string html content of the tree
     */
    public function render()
    {
        // preload images
        $sHTML = "\n";

        // list all views and highlight the current view
        $sHTML .= "
\n";
        $sHTML .= $this->renderNodeItems($this->nodesXml);
        $sHTML .= "
";
        return $sHTML;
    }

    /**
     * Render the html tree
     *
     * @return string html content of the tree
     */
    protected function renderNodeItems(&$nodeItemArray)
    {
        $sHTML = "";
        if (isset($nodeItemArray["ATTRIBUTES"]))
        {
            $sHTML .= $this->renderSingleNodeItem($nodeItemArray);
        }
        else
        {
            foreach ($nodeItemArray as $nodeItem)
            {
                $sHTML .= $this->renderSingleNodeItem($nodeItem);
            }
        }
        return $sHTML;
    }

    /**
     * Render single node item
     *
     * @param array $nodeItem
     * @return <type>
     */
    protected function renderSingleNodeItem(&$nodeItem)
    {
        $url = $nodeItem["ATTRIBUTES"]["URL"];
        $caption = $this->translate($nodeItem["ATTRIBUTES"]["CAPTION"]);
        $target = $nodeItem["ATTRIBUTES"]["TARGET"];
        //$img = $nodeItem["ATTRIBUTES"]["IMAGE"];
        if ($nodeItem["NODE"]) {
            $image = "getImageUrl() . "/plus.gif' class='collapsed' onclick='mouseClickHandler(this)'>";
        } else {
            $image = "getImageUrl() . "/topic.gif'>";
        }

        if ($target) {
            if ($url) {
                $sHTML .= "
$image " . $caption . "";
            } else {
                $sHTML .= "
$image $caption";
            }
        } elseif ($url) {
            $sHTML .= "
$image " . $caption . "";
        } else {
            $sHTML .= "
$image $caption";
        }
        if ($nodeItem["NODE"])
        {
            $sHTML .= "\n
\n";
            $sHTML .= $this->renderNodeItems($nodeItem["NODE"]);
            $sHTML .= "
";
        }
        $sHTML .= "
\n";
        return $sHTML;
    }

    /**
     * Rerender the menu
     *
     * @return string html content of the menu
     */
    public function rerender()
    {
        return $this->render();
    }

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

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


<?php

namespace Interpro\QuickStorage\Laravel\Param;
use Interpro\QuickStorage\Concept\Exception\WrongParamException;
use Interpro\QuickStorage\Concept\Param\GroupParam as GroupParamInterface;

class GroupParam implements GroupParamInterface
{
    private $params;
    private $permitted_params;

    public function __construct()
    {
        //В перспективе добавить возможность насыпать из сессии
        $this->params = [];

        //разрешенные параметры, если запрос к параметру не из этого списка, выбр. исключение
        $this->permitted_params = ['take', 'skip'];
    }

    public function reset($group_name)
    {
        $this->params[$group_name] = ['take'=>0, 'skip'=>0];
    }

    private function createIfNotExist($group_name)
    {
        if(!array_key_exists($group_name, $this->params))
        {
            $this->params[$group_name] = ['take'=>0, 'skip'=>0];
        }
    }

    private function checkParam($param_name)
    {
        if(!in_array($param_name, $this->permitted_params))
        {
            throw new WrongParamException('Обращение к неразрешенному параметру - '.$param_name);
        }
    }

    /**
     * @param string $group_name
     * @param string $param_name
     * @param $value
     *
     * @return void
     */
    public function set($group_name, $param_name, $value)
    {
        $this->createIfNotExist($group_name);

        $this->checkParam($param_name);

        $this->params[$group_name][$param_name] = $value;
    }

    /**
     * @param string $group_name
     * @param string $param_name
     *
     * @return mixed
     */
    public function get($group_name, $param_name)
    {
        $this->createIfNotExist($group_name);

        $this->checkParam($param_name);

        return $this->params[$group_name][$param_name];
    }

    /**
     * @param string $group_name
     * @param $group_q
     *
     * @return void
     */
    public function apply($group_name, $group_q)
    {
        $portion = $this->get($group_name, 'take');
        $start = $this->get($group_name, 'skip');

        if($portion != 0){
            $group_q->take($portion);
        }
        if($start != 0){
            $group_q->skip($start);
        }
    }

}