<?php

namespace Environaut\Export;

use Environaut\Command\Command;
use Environaut\Config\Parameters;
use Environaut\Export\IExport;
use Environaut\Export\Formatter\IReportFormatter;
use Environaut\Export\Formatter\ConsoleMessageFormatter;
use Environaut\Report\IReport;

/**
 * Default export that is used for reports after checks are run.
 * Outputs messages to the CLI and exports accumulated settings
 * as JSON.
 */
class Export implements IExport
{
    /**
     * Default filename to be used when no export file locations are specified.
     */
    const DEFAULT_EXPORT_LOCATION = 'environaut-config.json';

    /**
     * @var Command
     */
    protected $command;

    /**
     * @var IReport
     */
    protected $report;

    /**
     * @var Parameters
     */
    protected $parameters;

    /**
     * Export current report as follows:
     *
     * 1. Display messages on CLI
     * 2. Run all formatters and display their text results on CLI
     *
     * If no formatter has been specified a default writer will be used depending
     * on the file extension given. Without a file extension a plain text writer
     * will be used.
     */
    public function run()
    {
        $output = $this->command->getOutput();

        $output->writeln('');
        $output->writeln('---------------------');
        $output->writeln('-- Report follows: --');
        $output->writeln('---------------------');
        $output->writeln('');

        $formatter = new ConsoleMessageFormatter();
        $console_report_text = $formatter->format($this->report);
        $output->writeln($console_report_text);

        $output->writeln('');
        $output->writeln('---------------------');
        $output->writeln('-- Export follows: --');
        $output->writeln('---------------------');
        $output->writeln('');

        $default_formatter = array('location' => self::DEFAULT_EXPORT_LOCATION);
        $formatter_definitions = $this->parameters->get('formatters', array($default_formatter));
        foreach ($formatter_definitions as $formatter_definition) {
            $params = new Parameters($formatter_definition);

            $location = $params->get('location', self::DEFAULT_EXPORT_LOCATION);

            if ($params->has('__class')) {
                $formatter_class = $params->get('__class');
            } else {
                $formatter_class = $this->getFormatterByExtension($location);
            }

            $formatter = new $formatter_class();
            $formatter->setParameters($params);

            $output->writeln('Starting export via "' . $formatter_class . '".');

            $export_text = $formatter->format($this->report);
            $output->writeln($export_text);
        }

        $output->writeln('');
    }

    /**
     * Returns a specific formatter instance depending on the file
     * extension of the given export file location.
     *
     * @param string $location
     *
     * @return IReportFormatter
     *
     * @throws \InvalidArgumentException in case of unsupported file extensions
     */
    protected function getFormatterByExtension($location)
    {
        $ext = pathinfo($location, PATHINFO_EXTENSION);

        $formatter = null;

        switch ($ext) {
            case 'json':
                $formatter = 'Environaut\Export\Formatter\JsonSettingsWriter';
                break;
            case 'xml':
                $formatter = 'Environaut\Export\Formatter\XmlSettingsWriter';
                break;
            case 'php':
                $formatter = 'Environaut\Export\Formatter\PhpSettingsWriter';
                break;
            case 'sh':
                $formatter = 'Environaut\Export\Formatter\ShellSettingsWriter';
                break;
            case 'txt':
            default:
                $formatter = 'Environaut\Export\Formatter\PlainTextSettingsWriter';
        }

        return $formatter;
    }

    /**
     * Set report to be handled by this exporter.
     *
     * @param IReport $report
     */
    public function setReport(IReport $report)
    {
        $this->report = $report;
    }

    /**
     * Environaut command for access to input and output.
     *
     * @param Command $command
     */
    public function setCommand(Command $command)
    {
        $this->command = $command;
    }

    /**
     * Runtime parameters to configure the export operations.
     *
     * @param Parameters $parameters runtime parameters
     */
    public function setParameters(Parameters $parameters)
    {
        $this->parameters = $parameters;
    }
}


<?php
/**
 * @author    Antoine Hedgecock <antoine.hedgecock@gmail.com>
 *
 * @copyright Interactive Solutions
 */

declare(strict_types = 1);

namespace InteractiveSolutions\Bernard\Router;

use Bernard\Envelope;
use Bernard\Exception\ReceiverNotFoundException;
use Bernard\Router;
use InteractiveSolutions\Bernard\Router\ConsumerTaskManager;

class PluginManagerRouter implements Router
{
    /**
     * @var ConsumerTaskManager
     */
    private $consumerPluginManager;

    /**
     * PluginManagerRouter constructor.
     *
     * @param ConsumerTaskManager $consumerPluginManager
     */
    public function __construct(ConsumerTaskManager $consumerPluginManager)
    {
        $this->consumerPluginManager = $consumerPluginManager;
    }

    /**
     * {@inheritdoc}
     */
    public function map(Envelope $envelope)
    {
        if (!$this->consumerPluginManager->has($envelope->getName())) {
            throw new ReceiverNotFoundException(sprintf('Could not find the received for %s ', $envelope->getName()));
        }

        return $this->consumerPluginManager->get($envelope->getName());
    }
}


<?php

namespace WobbleCode\ManagerBundle\Traits\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

trait Taggeable
{
    /**
     * @ODM\Collection
     * @Serializer\Expose
     * @Serializer\Groups({"ui"})
     */
    protected $tags = [];

    /**
     * Set tags
     *
     * @param collection $tags
     *
     * @return self
     */
    public function setTags($tags)
    {
        $this->tags = $tags;
        return $this;
    }

    /**
     * Get tags
     *
     * @return collection $tags
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Add tag
     *
     * @return collection $tags
     *
     * @return self
     */
    public function addTag($item)
    {
        if (!in_array($item, $this->tags)) {
            $this->tags[] = $item;
        }

        return $this;
    }

    /**
     * Remove tag
     *
     * @return collection $tags
     *
     * @return self
     */
    public function removeTag($item)
    {
        if (($key = array_search($item, $this->tags)) !== false) {
            unset($this->tags[$key]);
        }

        return $this;
    }
}


<?php

namespace Environaut\Export\Formatter;

use Environaut\Config\Parameters;
use Environaut\Export\Formatter\IReportFormatter;
use RuntimeException;

/**
 * Simple formatter that takes messages from the results
 * of the given report and enhances them according to their
 * severity etc.
 */
abstract class BaseFormatter implements IReportFormatter
{
    /**
     * @var Parameters options for formatting
     */
    protected $parameters;

    /**
     * Create new instance of the formatter.
     *
     * @param array $options options string $format sprintf compatible format for the result messages
     */
    public function __construct(array $options = array())
    {
        $this->parameters = new Parameters($options);
    }

    /**
     * Sets the given runtime parameters on the formatter.
     *
     * @param Parameters $parameters associative array with options understood by this formatter
     *
     * @return $this for fluent API support
     */
    public function setParameters(Parameters $parameters)
    {
        $this->parameters = $parameters;
    }

    /**
     * Returns all runtime parameters for this formatter from the config.
     *
     * @return Parameters
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * Like vsprintf, but accepts keys instead of an order index.
     * The allowed format of named arguments is: /[a-zA-Z0-9_\-\.]+/
     *
     * For the base version of this method by Josef Kufner see:
     * @see http://www.php.net/manual/de/function.vsprintf.php#110666
     *
     * @example vskprintf(
     *      '%param$s must be between %min$03d and %max$03d.',
     *      array('param' => 'Value', 'min' => 3, 'max' => 99)
     *  ) // gives: 'Value must be between 003 and 099.'
     *
     * '%s' without argument name and positional directives like '%1$s' do work.
     * Everything vsprintf() can do is still supported.
     *
     * @param string $format input string with formatting directives
     * @param array $args arguments to use for formatting directives
     *
     * @return formatted string according to given format and arguments
     *
     * @throws RuntimeException in case of non-string format string
     *
     * @author Josef Kufner <jkufner(at)gmail.com>
     * @author Steffen Gransow <agavi@mivesto.de>
     */
    public static function vksprintf($format, array $args)
    {
        if (!is_string($format)) {
            throw new RuntimeException('Only strings are acceptable as input format.');
        }

        if (empty($args)) {
            return $format;
        }

        $map = array_flip(array_keys($args));

        $str = preg_replace_callback(
            '/(^|[^%])%([a-zA-Z0-9_\-\.]+)\$/',
            function ($m) use ($map) {
                $key = $m[2];
                if (!is_numeric($key) && array_key_exists($key, $map)) {
                    return $m[1] . '%' . ($map[$key] + 1) . '$';
                }
                return $m[1] . '%' . $key . '$';
            },
            $format
        );

        return vsprintf($str, $args);
    }
}


<?php

namespace WobbleCode\ManagerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use JMS\SecurityExtraBundle\Annotation\Secure;
use WobbleCode\RestBundle\Configuration\Rest;

class DefaultController extends Controller
{
    /**
     * Get the generic manager for this Controller
     *
     * @return DocumentManager
     */
    protected function getManager()
    {
        $gdm = $this->get('wobblecode_manager.document_manager')
                    ->setDocument('WobbleCodeUserBundle:Organization')
                    ->setKey('organization')
                    ->setAcceptFromRequest(['page', 'query', 'itemsPerPage'])
                    ->setItemsPerPage(2)
                    ->setQueryFields(['name', 'type']);

        return $gdm;
    }

    /**
     * @Route("/test/manager", name="test_manager")
     * @Template()
     * @Rest(output={"entities", "groups", "metadata"})
     */
    public function indexAction()
    {
        $gdm = $this->getManager();

        return [
            'entities' => $gdm->getDocuments(),
            'groups'   => $gdm->countByGroup('type')
        ];
    }
}


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

namespace Openbizx\Service;

/**
 * pdfService class is the plug-in service of printing bizform to pdf
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class pdfService
{
    /**
     * Initialize pdfService
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Render the pdf output
     *
     * @global BizSystem $g_BizSystem
     * @param string $viewName name of view object
     * @return void
     */
    public function renderView($viewName)
    {
        $viewObj = Openbizx::getObject($viewName);
        if($viewObj)
        {
            $viewObj->setConsoleOutput(false);
            $sHTML = $viewObj->render();
            //$sHTML = "Test";
            //require_once("dompdf/dompdf_config.inc.php");
            $domPdf = new DOMPDF();
            $domPdf->load_html($sHTML);
            //$dompdf->set_paper($_POST["paper"], $_POST["orientation"]);
            $domPdf->render();
            $this->output($domPdf);
            //$dompdf->stream("dompdf_out.pdf");
        }
    }

    /**
     * Save PDF to file and inform download link to client
     *
     * @param DOMPDF $domPdf
     */
    public function output($domPdf)
    {
        //$tmpfile = getcwd()."/tmpfiles";
        $tmpDir = OPENBIZ_APP_PATH."/tmpfiles";
        //echo $tmpfile;
        $this->cleanFiles($tmpDir, 100);
        //Determine a temporary file name in the current directory
        $tmpFile = tempnam($tmpDir,'tmp');
        $fileName = $tmpFile.'.pdf';
        $fileName = str_replace("\\","/",$fileName);
        unlink($tmpFile);
        //Save PDF to file
        $pdfText = $domPdf->output();
        $fileHandle = fopen($fileName, 'w') or die("can't open pdf file to write");
        fwrite($fileHandle, $pdfText) or die("can't write to the pdf file");
        fclose($fileHandle);
        //JavaScript redirection
        $path_parts = pathinfo($fileName);
        $file_download = "tmpfiles/".$path_parts['basename'];
        echo "<BODY onload=\"window.location.href='../$file_download';\"";
    }

    /**
     * Delete (temporary) files on specified directory
     *
     * @param string $dir filly directori name
     * @param number $seconds
     */
    public function cleanFiles($dir, $seconds)
    {
        $currentTime = time();
        $dirHandle=opendir($dir);
        while($file = readdir($dirHandle))
        {
            if(substr($file,0,3) == 'tmp' && substr($file,-4) == '.pdf')
            {
                $path = $dir.'/'.$file;
                if($currentTime - filemtime($path) > $seconds)
                    unlink($path);
            }
        }
        closedir($dirHandle);
    }
}
?>


<?php

namespace Tree6bee\Queue;

use Tree6bee\Queue\Drivers\QueueInterface;

class Queue
{
    const TYPE = 'tree6bee';

    /**
     * @var QueueInterface
     */
    protected $driver;

    /**
     * @var string
     */
    protected $defaultQueue = 'default';

    public function __construct(QueueInterface $driver)
    {
        $this->driver = $driver;
    }

    /**
     * Push a new job onto the queue.
     *
     * @param  Job  $job
     *
     * @return mixed
     */
    public function push(Job $job)
    {
        return $this->driver->push(
            $job->queue,
            $this->createPayload($job),
            $job->retry_after
        );
    }

    /**
     * Push a new job onto the queue after a delay.
     *
     * @param  \DateTime|int  $delay
     * @param  Job  $job
     * @return mixed
     */
    public function later($delay, Job $job)
    {
        return $this->driver->later(
            $delay,
            $job->queue,
            $this->createPayload($job),
            $job->retry_after
        );
    }

    /**
     * @param string $queue
     *
     * @return null|\Tree6bee\Queue\Drivers\Jobs\JobInterface
     */
    public function pop($queue = '')
    {
        return $this->driver->pop($this->getQueue($queue));
    }

    /**
     * Get the queue or return the default.
     *
     * @param  string|null  $queue
     * @return string
     */
    protected function getQueue($queue)
    {
        return $queue ? $queue : $this->defaultQueue;
    }

    /**
     * Create a payload string from the given job and data.
     *
     * @param  Job $job
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    protected function createPayload(Job $job)
    {
        $payload = json_encode([
            'type'  => self::TYPE, //只有 type 为 tree6bee 才会自动处理，其他的不处理
            'job'   => serialize(clone $job),
        ]);

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

        return $payload;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: hua
 * Date: 2018/9/13
 * Time: 下午7:12
 */

namespace DdvPhp\DdvUtil\Laravel\Proxy\Traits;

use DdvPhp\DdvUtil\Laravel\Exceptions\ProxyExceptions;
use Illuminate\Http\Request as HttpRequest;

trait Prototype
{
    /**
     * 获取一个属性
     * @param null $key
     * @throws ProxyExceptions
     * @return mixed
     */
    public function getPrototype($key = null, $defaultValue = null)
    {
        if (empty($key)) {
            throw new ProxyExceptions('key must not empty', 'MUST_INPUT_KEY');
        }
        /**
         * @var HttpRequest $request
         */
        $request = $this->getRequest();
        if ($request->has($key)) {
            return $request->input($key);
        } else {
            if (func_num_args() > 1) {
                return $defaultValue;
            } else {
                throw new ProxyExceptions('prototype [' . $key . '] not defined', 'PROTOTYPE_NOT_DEFINED');
            }
        }
    }

    /**
     * 设置一个属性
     * @param $key
     * @param $value
     * @return $this
     */
    public function setPrototype($key, $value)
    {
        /**
         * @var HttpRequest $request
         */
        $this->loadPrototype(array($key => $value));
        return $this;
    }

    /**
     * 复制属性
     * @param $key
     * @param $newKey
     * @throws ProxyExceptions
     */
    public function copyPrototype($key, $newKey){
        $this->setPrototype($newKey, $this->getPrototype($key));
    }

    /**
     * @param $key
     * @return bool
     */
    public function hasPrototype($key){
        return (bool)$this->getRequest()->has($key);
    }

    /**
     * 批量设置属性
     * @param array $input
     * @param bool $isReplace
     * @return $this
     */
    public function loadPrototype(array $input, $isReplace = false)
    {
        /**
         * @var HttpRequest $request
         */
        $request = $this->getRequest();
        if ($isReplace) {
            $request->replace($input);
        } else {
            $request->merge($input);
        }
        // 释放内存
        unset($request);
        return $this;
    }
}


<?php

namespace Interpro\QS;

use Interpro\Core\Contracts\Taxonomy\TypesForecastList;
use Interpro\Core\Taxonomy\Collections\ManifestsCollection;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Core\Taxonomy\Manifests\ATypeManifest;
use Interpro\QS\Exception\QSException;

class ConfigInterpreter
{
    private $forecastList;

    public function __construct(TypesForecastList $forecastList)
    {
        $this->forecastList = $forecastList;
    }

    private function addFields(array & $fields_pattern, $config, $type_name, & $types)
    {
        if(array_key_exists($type_name, $config))
        {
            foreach($config[$type_name] as $field_name)
            {
                $fields_pattern[$field_name] = $type_name;
            }
            unset($types[$type_name]);
        }
    }

    private function addBlockPredefinedOwns(array & $fields_pattern)
    {
        $fields_pattern['name']  = 'string';
        $fields_pattern['title'] = 'string';
        $fields_pattern['show']  = 'bool';
    }

    private function addGroupPredefinedOwns(array & $fields_pattern)
    {
        $fields_pattern['id']     = 'int';
        $fields_pattern['name']   = 'string';
        $fields_pattern['slug']   = 'string';
        $fields_pattern['title']  = 'string';
        $fields_pattern['sorter'] = 'int';
        $fields_pattern['show']   = 'bool';
        $fields_pattern['predefined'] = 'bool';
        $fields_pattern['updated_at'] = 'timestamp';
        $fields_pattern['created_at'] = 'timestamp';
    }

    private function addImageSet(& $patterns, $block_name, $superior_type, $set_name, $image_name)
    {
        $patterns[$set_name] = ['owns' => [], 'refs' => []];

        $this->addGroupPredefinedOwns($patterns[$set_name]['owns']);

        $patterns[$set_name]['rank'] = TypeRank::GROUP;
        $patterns[$set_name]['owns'][$image_name] = 'image';
        $patterns[$set_name]['refs']['block_name'] = $block_name;

        //Если это набор картинок группы
        if($superior_type)
        {
            $patterns[$set_name]['refs']['superior'] = $superior_type;
        }
    }

    private function scan(array & $config)
    {
        $patterns = [];

        foreach($config as $block_name => $block_config)
        {
            //Из $block_types будем вычитать типы которые совпали с зарегестрированными,
            //а которые останутся - не правильно заполненные названия типов в конфиге
            $block_types = array_flip(array_keys($block_config));
            if(in_array('groups', $block_types)) unset($block_types['groups']);
            if(in_array('imageset', $block_types)) unset($block_types['imageset']);
            //---------------------------------------------------------------------

            //********************Поля блока***************************************
            $patterns[$block_name] = ['owns' => [], 'refs' => []];
            $patterns[$block_name]['rank'] = TypeRank::BLOCK;

            //Поля предопределенные
            $this->addBlockPredefinedOwns($patterns[$block_name]['owns']);

            $c_names = $this->forecastList->getCTypeNames();
            $b_names = $this->forecastList->getBTypeNames();
            $a_names = $this->forecastList->getATypeNames();

            //Если есть поля какого-либо типа
            foreach($c_names as $type_name)
            {
                $this->addFields($patterns[$block_name]['owns'], $block_config, $type_name, $block_types);
            }

            //Если есть поля какого-либо агрегатного типа
            foreach($b_names as $type_name)
            {
                $this->addFields($patterns[$block_name]['owns'], $block_config, $type_name, $block_types);
            }

            //Если есть ссылки на какой-либо тип, вставляем
            foreach($a_names as $type_name)
            {
                $this->addFields($patterns[$block_name]['refs'], $block_config, $type_name, $block_types);
            }

            //наборы картинок
            if(array_key_exists('imageset', $block_config))
            {
                foreach($block_config['imageset'] as $set_name => $image_name)
                {
                    $this->addImageSet($patterns, $block_name, '', $set_name, $image_name);
                }
            }

            if(!empty($block_types))
            {
                throw new QSException('В настройке пакета qsagr содержаться незарегестрированные названия типов: '.implode(', ', array_flip($block_types)).'!');
            }
            //*********************************************************************

            //********************Группы*******************************************
            if(array_key_exists('groups', $block_config))
            {
                foreach($block_config['groups'] as $group_name => $group_config)
                {
                    $group_types = array_flip(array_keys($group_config));
                    if(in_array('groups', $group_types)) unset($group_types['groups']);
                    if(in_array('imageset', $group_types)) unset($group_types['imageset']);

                    $patterns[$group_name] = ['owns' => [], 'refs' => []];
                    $patterns[$group_name]['refs']['block_name'] = $block_name;
                    $patterns[$group_name]['rank'] = TypeRank::GROUP;

                    //Поля предопределенные
                    $this->addGroupPredefinedOwns($patterns[$group_name]['owns']);

                    //Если есть поля какого-либо типа
                    foreach($c_names as $type_name)
                    {
                        $this->addFields($patterns[$group_name]['owns'], $group_config, $type_name, $group_types);
                    }

                    //Если есть поля какого-либо агрегатного типа
                    foreach($b_names as $type_name)
                    {
                        $this->addFields($patterns[$group_name]['owns'], $group_config, $type_name, $group_types);
                    }

                    //Если есть ссылки на какой-либо тип, вставляем
                    foreach($a_names as $type_name)
                    {
                        $this->addFields($patterns[$group_name]['refs'], $group_config, $type_name, $group_types);
                    }

                    //наборы картинок
                    if(array_key_exists('imageset', $group_config))
                    {
                        foreach($group_config['imageset'] as $set_name => $image_name)
                        {
                            $this->addImageSet($patterns, $block_name, $group_name, $set_name, $image_name);
                        }
                    }

                    if(!empty($group_types))
                    {
                        throw new QSException('В настройке пакета qsagr содержаться незарегестрированные названия типов: '.implode(', ', array_flip($group_types)).'!');
                    }
                }
            }
            //*********************************************************************

        }

        return $patterns;
    }

    private function checkNames()
    {
        //Проверка на наличие обязательных скалярных типов для предопределённых полей

        $c_names = $this->forecastList->getCTypeNames();
        $b_names = $this->forecastList->getBTypeNames();

        if(!in_array('string', $c_names))
        {
            throw new QSException('Не зарегестрировано имя типа string, интерпретация предопределенных полей не возможна!');
        }

        if(!in_array('int', $c_names))
        {
            throw new QSException('Не зарегестрировано имя типа int, интерпретация предопределенных полей не возможна!');
        }

        if(!in_array('bool', $c_names))
        {
            throw new QSException('Не зарегестрировано имя типа bool, интерпретация предопределенных полей не возможна!');
        }

        if(!in_array('timestamp', $c_names))
        {
            throw new QSException('Не зарегестрировано имя типа timestamp (метка времени), интерпретация предопределенных полей не возможна!');
        }

        if(!in_array('image', $b_names))
        {
            throw new QSException('Не зарегестрировано имя типа image, интерпретация полей картинок в imageset не возможна!');
        }
    }

    private function createManifest($type_name, $typeRank, & $owns, & $refs)
    {
        return new ATypeManifest('qs', $type_name, $typeRank, $owns, $refs);
    }

    private function addTextImagesBlock(array & $config, $block_name = 'textfield_block')
    {
        if(!array_key_exists($block_name, $config) or !is_array($config[$block_name]))
        {
            $config[$block_name] = [
                'imageset' => ['default_imageset' => 'image_item']
            ];
        }

        $block_config = & $config[$block_name];

        if(!array_key_exists('imageset', $block_config) or !is_array($block_config['imageset']))
        {
            $block_config['imageset'] = ['default_imageset' => 'image_item'];
        }

        $imageset_config = & $block_config['imageset'];

        if(count($imageset_config) === 0)
        {
            $imageset_config['default_imageset'] = 'image_item';
        }
    }

    /**
     * @param array $config
     *
     * @return \Interpro\Core\Taxonomy\Collections\ManifestsCollection
     */
    public function interpretConfig(array $config)
    {
        $manifests = new ManifestsCollection();

        $this->checkNames();

        $this->addTextImagesBlock($config);

        $patterns = $this->scan($config);

        foreach($patterns as $type_name => $pattern)
        {
            $man = $this->createManifest($type_name, $pattern['rank'], $pattern['owns'], $pattern['refs']);
            $manifests->addManifest($man);
        }

        return $manifests;
    }

}


<?php
namespace T3v\T3vContent\Utility;

/**
 * The content element utility class.
 *
 * @package T3v\T3vContent\Utility
 */
class ContentElementUtility {
  /**
   * Gets a content element identifier from an content element key.
   *
   * @param string $contentElementKey The content element key
   * @return string The content element identifier
   */
  public static function contentElementIdentifier(string $contentElementKey): string {
    $contentElementIdentifier = $contentElementKey;

    if (strpos($contentElementIdentifier, '_') ||
        strpos($contentElementIdentifier, '-') ||
        strpos($contentElementIdentifier, ' ')) {
      $contentElementIdentifier    = mb_strtolower($contentElementKey);
      $contentElementIdentifier    = str_replace('_', ' ', $contentElementIdentifier);
      $contentElementIdentifier    = str_replace('-', ' ', $contentElementIdentifier);
      $contentElementIdentifier    = str_replace(' ', '', ucwords($contentElementIdentifier));
    }

    if ($contentElementIdentifier[0]) {
      $contentElementIdentifier[0] = mb_strtoUpper($contentElementIdentifier[0]);
    }

    return $contentElementIdentifier;
  }

  /**
   * Alias for the `contentElementIdentifier` function.
   *
   * @param string $contentElementKey The content element key
   * @return string The content element identifier
   */
  public static function getContentElementIdentifier(string $contentElementKey): string {
    return self::contentElementIdentifier($contentElementKey);
  }

  /**
   * Gets a content element signature from an extension and content element identifier.
   *
   * @param string $extensionIdentifier The extension identifier
   * @param string $contentElementIdentifier The content element identifier
   * @return string The content element signature
   */
  public static function contentElementSignature(string $extensionIdentifier, string $contentElementIdentifier): string {
    $contentElementSignature = mb_strtolower($extensionIdentifier . '_' . $contentElementIdentifier);

    return $contentElementSignature;
  }

  /**
   * Alias for the `contentElementSignature` function.
   *
   * @param string $extensionIdentifier The extension identifier
   * @param string $contentElementIdentifier The content element identifier
   * @return string The content element signature
   */
  public static function getContentElementSignature(string $extensionIdentifier, string $contentElementIdentifier): string {
    return self::contentElementSignature($extensionIdentifier, $contentElementIdentifier);
  }
}


<?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: ColumnImage.php 3742 2011-04-16 07:25:29Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;

//include_once("ColumnText.php");

/**
 * ColumnImage class is element for ColumnImage,
 * show image on data list
 *
 * @package openbiz.bin.easy.element
 * @author Hu Zhaoxin, jixian2003
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class ColumnImage extends ColumnText
{
    /**
     * String for alternate attribute of image
     *
     *
     * @var string
     */
    public $alt;

    /**
     * String for title attribute of image
     *
     *
     * @var string
     */
    public $title;
    public $imgUrl; // image url prefix to the image path

    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->alt = isset($xmlArr["ATTRIBUTES"]["ALT"]) ? $xmlArr["ATTRIBUTES"]["ALT"] : null;
        $this->title = isset($xmlArr["ATTRIBUTES"]["TITLE"]) ? $xmlArr["ATTRIBUTES"]["TITLE"] : null;
        $this->imgUrl = isset($xmlArr["ATTRIBUTES"]["IMGURL"]) ? $xmlArr["ATTRIBUTES"]["IMGURL"] : '';
    }

    /**
     * Get image alternate(ALT) attribut
     *
     * @return string
     */
    protected function getAlt()
    {
        if ($this->alt == null) {
            return null;
        }
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->alt, $formobj);
    }

    /**
     * Get image title
     *
     * @return string
     */
    protected function getTitle()
    {
        if ($this->title == null) {
            return null;
        }
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->title, $formobj);
    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	if(!$this->getText())
    	{
    		$val = ($this->imgUrl) ? $this->imgUrl.$this->value : $this->value;
    	}else{
    		if(preg_match("/\{OPENBIZ_RESOURCE_URL\}/si",$this->text)){
    			$val = $this->getText();
    		}else{
    			$val = Openbizx::$app->getImageUrl()."/".$this->getText();
    		}
    	}
        if ($val == null || $val == "") {
            return "";
        }

        $style = $this->getStyle();
        $func = $this->getFunction();
        $alt = $this->getAlt();
        $title = $this->getTitle();

        if ($val)
        {
            if($height = $this->height)
            {
                $height = 'height="' . $height . '"';
            }

            if($width = $this->width)
            {
                $width = 'width="' . $width . '"';
            }

            $alt = 'alt="' . $alt . '"';
            $title = 'title="' . $title . '"';

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

}

?>


<?php

/**
 * ListForm class
 *
 * @package
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */

namespace Openbizx\View;

use Openbizx\View\BaseForm;
/*
 * public methods: fetchDataSet, deleteRecord, selectRecord, removeRecord, runSearch, sortRecord, gotoPage
 */
class ListForm extends BaseForm
{

    //list of method that can directly from browser
    protected $directMethodList = array('selectrecord', 'sortrecord', 'editrecord', 'copyrecord', 'deleterecord', 'removerecord', 'runsearch', 'gotopage', 'setpagesize', 'gotoselectedpage', 'switchform', 'loaddialog');
    public $range = 10;
    public $searchRule = null;
    public $fixSearchRule = null; // FixSearchRule is the search rule always applying on the search
    public $sortRule = null;
    protected $defaultFixSearchRule = null;
    protected $queryParams = array();
    // vars for grid(list)
    protected $currentPage = 1;
    protected $startItem = 1;
    public $totalPages = 1;
    protected $totalRecords = 0;
    protected $recordSet = null;
    protected $isRefreshData = false;

    protected function readMetadata($xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->range = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["PAGESIZE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["PAGESIZE"] : $this->range;
        $this->fixSearchRule = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["SEARCHRULE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["SEARCHRULE"] : null;
        $this->sortRule = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["SORTRULE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["SORTRULE"] : null;
        $this->defaultFixSearchRule = isset($xmlArr["EASYFORM"]["ATTRIBUTES"]["SEARCHRULE"]) ? $xmlArr["EASYFORM"]["ATTRIBUTES"]["SEARCHRULE"] : null;
    }

    protected function inheritParentObj()
    {
        if (!$this->inheritFrom)
            return;
        $parentObj = Openbizx::getObject($this->inheritFrom);
        parent::inheritParentObj();
        $this->range = $this->range ? $this->range : $parentObj->range;
        $this->fixSearchRule = $this->fixSearchRule ? $this->fixSearchRule : $parentObj->fixSearchRule;
        $this->defaultFixSearchRule = $this->defaultFixSearchRule ? $this->defaultFixSearchRule : $parentObj->defaultFixSearchRule;
    }

    /**
     * Get/Retrieve Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function loadStatefullVars($sessionContext)
    {
        $sessionContext->loadObjVar($this->objectName, "RecordId", $this->recordId);
        $sessionContext->loadObjVar($this->objectName, "FixSearchRule", $this->fixSearchRule);
        $sessionContext->loadObjVar($this->objectName, "SearchRule", $this->searchRule);
        $sessionContext->loadObjVar($this->objectName, "SearchRuleBindValues", $this->searchRuleBindValues);
        $sessionContext->loadObjVar($this->objectName, "SubForms", $this->subForms);
        $sessionContext->loadObjVar($this->objectName, "CurrentPage", $this->currentPage);
        $sessionContext->loadObjVar($this->objectName, "PageSize", $this->range);
        $sessionContext->loadObjVar($this->objectName, "SearchPanelValues", $this->searchPanelValues);
    }

    /**
     * Save object variable to session context
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function saveStatefullVars($sessionContext)
    {
        $sessionContext->saveObjVar($this->objectName, "RecordId", $this->recordId);
        $sessionContext->saveObjVar($this->objectName, "FixSearchRule", $this->fixSearchRule);
        $sessionContext->saveObjVar($this->objectName, "SearchRule", $this->searchRule);
        $sessionContext->saveObjVar($this->objectName, "SearchRuleBindValues", $this->searchRuleBindValues);
        $sessionContext->saveObjVar($this->objectName, "SubForms", $this->subForms);
        $sessionContext->saveObjVar($this->objectName, "CurrentPage", $this->currentPage);
        $sessionContext->saveObjVar($this->objectName, "PageSize", $this->range);
        $sessionContext->saveObjVar($this->objectName, "SearchPanelValues", $this->searchPanelValues);
    }

    /**
     * Fetch record set
     *
     * @return array array of record
     */
    public function fetchDataSet()
    {
        $dataObj = $this->getDataObj();

        if (!$dataObj)
            return null;

        if ($this->isRefreshData)
            $dataObj->resetRules();
        else
            $dataObj->clearSearchRule();
        /*
          if ($this->fixSearchRule)
          {
          if ($this->searchRule)
          $searchRule = $this->searchRule . " AND " . $this->fixSearchRule;
          else
          $searchRule = $this->fixSearchRule;
          }
          else
          $searchRule = $this->searchRule;

          $dataObj->setSearchRule($searchRule);
         */
        $dataObj->setQueryParameters($this->queryParams);
        if ($this->startItem > 1) {
            $dataObj->setLimit($this->range, $this->startItem);
        } else {
            $dataObj->setLimit($this->range, ($this->currentPage - 1) * $this->range);
        }
        if ($this->sortRule && $this->sortRule != $this->getDataObj()->sortRule) {
            $dataObj->setSortRule($this->sortRule);
        }
        $resultRecords = $dataObj->fetch();
        $this->totalRecords = $dataObj->count();
        if ($this->range && $this->range > 0)
            $this->totalPages = ceil($this->totalRecords / $this->range);
        $selectedIndex = 0;

        //if current page is large than total pages ,then reset current page to last page
        if ($this->currentPage > $this->totalPages && $this->totalPages > 0) {
            $this->currentPage = $this->totalPages;
            $dataObj->setLimit($this->range, ($this->currentPage - 1) * $this->range);
            $resultRecords = $dataObj->fetch();
        }

        $this->getDataObj()->setActiveRecord($resultRecords[$selectedIndex]);

        if (!$this->recordId) {
            $this->recordId = $resultRecords[0]["Id"];
        } else {
            $foundRecordId = false;
            foreach ($resultRecords as $record) {
                if ($this->recordId == $record['Id']) {
                    $foundRecordId = true;
                }
            }
            if ($foundRecordId == false) {
                $this->recordId = $result[0]['Id'];
            }
        }

        return $resultRecords;
    }

    public function switchForm($formName = null, $id = null)
    {
        if ($id == null || $id == '')
            $id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');
        $this->formHelper->switchForm($formName, $id);
    }

    public function loadDialog($formName = null, $id = null)
    {
        if ($id == null || $id == '')
            $id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');
        $this->formHelper->loadDialog($formName, $id);
    }

    /**
     * Delete Record
     * NOTE: use redirectpage attr of eventhandler to redirect or redirect to previous page by default
     *
     * @param string $id
     * @return void
     */
    public function deleteRecord($id = null)
    {
        if ($id == null || $id == '')
            $id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');

        $selIds = Openbizx::$app->getClientProxy()->getFormInputs('row_selections', false);
        if ($selIds == null)
            $selIds[] = $id;
        foreach ($selIds as $id) {
            $dataRec = $this->getDataObj()->fetchById($id);
            //$this->getDataObj()->setActiveRecord($dataRec);
            // take care of exception
            try {
                $dataRec->delete();
            } catch (Openbizx\Data\Exception $e) {
                // call $this->processDataException($e);
                $this->processDataException($e);
                return;
            }
        }
        //$this->runEventLog();
        $this->rerender();
    }

    /**
     * Select Record
     *
     * @param string $recId
     * @access remote
     * @return void
     */
    public function selectRecord($recId)
    {
        if ($recId == null || $recId == '')
            $recId = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');
        $this->recordId = $recId;
        if ($this->getDataObj()) {
            $this->getDataObj()->setActiveRecordId($this->recordId);
        }
        $this->rerender(false); // not redraw the this form, but draw the subforms
        //$this->rerender();
    }

    /**
     * Edit Record
     * NOTE: append fld:Id=$id to the redirect page url
     *
     * @param mixed $id
     * @return void
     */
    public function editRecord($id = null)
    {
        if ($id == null || $id == '')
            $id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');

        if (!isset($id)) {
            Openbizx::$app->getClientProxy()->showClientAlert($this->getMessage("PLEASE_EDIT_A_RECORD"));
            return;
        }

        $_REQUEST['fld:Id'] = $id;

        $this->formHelper->processPostAction();
    }

    /**
     * Copy record to new record
     *
     * @param mixed $id id of record that want to copy,
     * it parameter not passed, id is '_selectedId'
     * @return void
     */
    public function copyRecord($id = null)
    {
        $this->editRecord($id);
    }

    /**
     * Remove the record out of the associate relationship
     *
     * @return void
     */
    public function removeRecord()
    {
        if ($id == null || $id == '')
            $id = Openbizx::$app->getClientProxy()->getFormInputs('_selectedId');

        $selIds = Openbizx::$app->getClientProxy()->getFormInputs('row_selections', false);
        if ($selIds == null)
            $selIds[] = $id;
        foreach ($selIds as $id) {
            $rec = $this->getDataObj()->fetchById($id);
            $ok = $this->getDataObj()->removeRecord($rec, $bPrtObjUpdated);
            if (!$ok)
                return $this->processDataObjError($ok);
        }

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

    /**
     * Goto page specified by $page parameter, and ReRender
     * If page not specified, goto page 1
     *
     * @param number $page
     */
    public function gotoPage($page = 1)
    {
        $tgtPage = intval($page);
        if ($tgtPage == 0)
            $tgtPage = 1;
        $this->currentPage = $tgtPage;
        $this->rerender();
    }

    public function gotoSelectedPage($elemName)
    {
        $page = Openbizx::$app->getClientProxy()->getFormInputs(str_replace(".", "_", $this->objectName) . '_' . $elemName);
        $this->gotoPage($page);
    }

    public function setPageSize($elemName)
    {
        $pagesize = Openbizx::$app->getClientProxy()->getFormInputs(str_replace(".", "_", $this->objectName) . '_' . $elemName);
        $this->range = $pagesize;
        $this->rerender();
    }

    /**
     * Sort Record, for list form
     *
     * @param string $sortCol column name to sort
     * @param string $order 'dec' (decending) or 'asc' (ascending)
     * @access remote
     * @return void
     */
    public function sortRecord($sortCol, $order = 'ASC')
    {
        $element = $this->getElement($sortCol);
        // turn off the OnSort flag of the old onsort field
        $element->setSortFlag(null);
        // turn on the OnSort flag of the new onsort field
        if ($order == "ASC")
            $order = "DESC";
        else
            $order = "ASC";
        $element->setSortFlag($order);

        // change the sort rule and issue the query
        $this->getDataObj()->setSortRule("[" . $element->fieldName . "] " . $order);

        // move to 1st page
        $this->currentPage = 1;
        $this->sortRule = "";

        $this->rerender();
    }

    /**
     * Run Search
     *
     * @return void
     */
    public function runSearch()
    {
        /* static $isSearchHelperLoaded = false;

          if (!$isSearchHelperLoaded) {
          include_once(OPENBIZ_BIN."/Easy/SearchHelper.php");
          $isSearchHelperLoaded = true;
          } */
        $queryArray = array();
        foreach ($this->searchPanel as $element) {
            if (!$element->fieldName)
                continue;

            $value = Openbizx::$app->getClientProxy()->getFormInputs($element->objectName);
            $this->searchPanelValues[$element->fieldName] = $value; // ??? neede
            if ($element->fuzzySearch == "Y") {
                $value = "*$value*";
            }
            if ($value != '') {
                $this->queryParams[$element->fieldName] = $value;
            }
        }

        $this->isRefreshData = true;

        $this->currentPage = 1;

        Openbizx::$app->getLog()->log(LOG_DEBUG, "FORMOBJ", $this->objectName . "::runSearch(), SearchRule=" . $this->searchRule);

        //$recArr = $this->readInputRecord();
        //$this->searchPanelValues = $recArr;
        //$this->runEventLog();
        $this->rerender();
    }

    /**
     * Reset search
     *
     * @return void
     */
    public function resetSearch()
    {
        $this->searchRule = "";
        $this->isRefreshData = true;
        $this->currentPage = 1;
        $this->runEventLog();
        $this->rerender();
    }

    public function setSearchRule($searchRule, $searchRuleBindValues = null)
    {
        $this->searchRule = $searchRule;
        $this->searchRuleBindValues = $searchRuleBindValues;
        $this->isRefreshData = true;
        $this->currentPage = 1;
    }
}


<?php
namespace T3v\T3vContent\ViewHelpers;

use T3v\T3vCore\ViewHelpers\AbstractViewHelper;

use T3v\T3vContent\Service\ExtensionService;

/**
 * The view column view helper class.
 *
 * @package T3v\T3vContent\ViewHelpers
 */
class ViewColumnViewHelper extends AbstractViewHelper {
  /**
   * The extension service.
   *
   * @var \T3v\T3vContent\Service\ExtensionService
   * @inject
   */
  protected $extensionService;

  /**
   * The view helper render function.
   *
   * @param int $viewColumn The UID of the view column
   * @param array $data The page data
   * @return string The rendered content of the view column
   */
  public function render(int $viewColumn, $data) {
    $output       = '';
    $viewChildren = $data['tx_gridelements_view_children'];
    $viewChildren = $this->filterViewChildrenByViewColumn($viewChildren, $viewColumn);

    if ($this->extensionService->runningInStrictMode()) {
      $viewChildren = $this->filterViewChildrenBySysLanguage($viewChildren);
    }

    foreach($viewChildren as $viewChild) {
      $uid              = $viewChild['uid'];
      $viewChildId      = "tx_gridelements_view_child_{$uid}";
      $viewChildContent = $data[$viewChildId];

      if (!empty($viewChildContent)) {
        $output .= $viewChildContent;
      }
    }

    return $output;
  }

  /**
   * Filters the view children by a view column.
   *
   * @param array $viewChildren The view children
   * @param int $viewColumn The UID of the view column
   * @return array The filtered view children
   */
  protected function filterViewChildrenByViewColumn(array $viewChildren, int $viewColumn) {
    $result = [];

    if ($viewChildren) {
      foreach($viewChildren as $viewChild) {
        if (intval($viewChild['tx_gridelements_columns']) == $viewColumn) {
          $result[] = $viewChild;
        }
      }
    }

    return $result;
  }

  /**
   * Filters the view children by the current system language.
   *
   * @param array $viewChildren The view children
   * @return array The filtered view children
   */
  protected function filterViewChildrenBySysLanguage($viewChildren) {
    $result = [];

    if ($viewChildren) {
      $sysLanguageUid = $this->getSysLanguageUid();

      foreach($viewChildren as $viewChild) {
        if (intval($viewChild['sys_language_uid']) == $sysLanguageUid) {
          $result[] = $viewChild;
        }
      }
    }

    return $result;
  }
}


<?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: CKEditor.php 3486 2011-03-11 17:30:28Z jixian2003 $
 */

namespace Openbizx\Easy\Element;

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

/**
 * CKEditor class is element for CKEditor
 *
 * @package openbiz.bin.easy.element
 * @author jixian2003, Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class CKEditor extends InputElement
{
	public $config;
	public $mode;
    /**
     * Read array meta data, and store to meta object
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetaData(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->mode = isset($xmlArr["ATTRIBUTES"]["MODE"]) ? $xmlArr["ATTRIBUTES"]["MODE"] : null;
        $this->config = isset($xmlArr["ATTRIBUTES"]["CONFIG"]) ? $xmlArr["ATTRIBUTES"]["CONFIG"] : null;
    }

    /**
     * Render element, according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        Openbizx::$app->getClientProxy()->includeCKEditorScripts();

        $elementName = $this->objectName;

        $value = $this->getValue();
        $value = htmlentities($value, ENT_QUOTES, "UTF-8");
        $style = $this->getStyle();
        $width = $this->width ? $this->width : 600;
        $height = $this->height ? $this->height : 300;
        //$func = "onclick=\"editRichText('$elementName', $width, $height);\"";
        if(!strlen($value)>0) // fix suggested by smarques
            $value=" ";

        $type = strtolower($this->mode);
        $fileBrowserPage = OPENBIZ_APP_URL."/bin/filebrowser/browser.html";

        $languageCode = I18n::getCurrentLangCode();
        $languageCode = str_replace("_","-",$languageCode);
        $config = $this->config;
        $sHTML .= "<textarea id=\"$elementName\" name=\"$elementName\" >$value</textarea>\n";
        $sHTML .= "<script type=\"text/javascript\">\n";
        if($config){
        	//remove the last commas
        	$config=trim($config);
        	if(substr($config,strlen($config)-1,1)==','){
        		$config = substr($config,strlen($config)-1);
        	}
        	$sHTML .= "Openbizx.CKEditor.init('$elementName',{'type':'$type','filebrowserBrowseUrl':'$fileBrowserPage','language':'$languageCode','height':'$height','width':'$width',$config});\n";
        }else{
        	$sHTML .= "Openbizx.CKEditor.init('$elementName',{'type':'$type','filebrowserBrowseUrl':'$fileBrowserPage','language':'$languageCode','height':'$height','width':'$width'});\n";
        }
        $sHTML .= "</script>\n";

        return $sHTML;
    }

}

?>


<?php

namespace UMA\SchemaBundle\Validation;

use JsonSchema\Validator;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpFoundation\Request;
use UMA\SchemaBundle\Annotation\JsonSchema;
use UMA\SchemaBundle\Exception\BadJsonRequestException;

class JsonValidator
{
    /**
     * @var FileLocator
     */
    private $locator;

    /**
     * @var Validator
     */
    private $validator;

    /**
     * @param FileLocator $locator
     */
    public function __construct(FileLocator $locator)
    {
        $this->locator = $locator;
        $this->validator = new Validator();
    }

    /**
     * @param Request    $request    An HTTP JSON request to validate
     * @param JsonSchema $annotation The shit
     *
     * @throws BadJsonRequestException When the request does not pass
     *                                 the schema validation
     */
    public function validate(Request $request, JsonSchema $annotation)
    {
        if (null === $requestContent = json_decode($request->getContent())) {
            throw new BadJsonRequestException($request->getContent(), null, ['HTTP request body does not contain a JSON payload']);
        }

        if ($annotation->strict && $request->headers->get('Content-Type') !== $annotation->contentType) {
            throw new BadJsonRequestException($request->getContent(), null, ["HTTP request Content-Type must be {$annotation->contentType}"]);
        }

        $this->validator->check(
            $requestContent, (object) ['$ref' => $fullPath = sprintf('file://%s', $this->getSchemaPath($annotation))]
        );

        if (!$this->validator->isValid()) {
            throw new BadJsonRequestException(
                $requestContent,
                $this->validator->getSchemaStorage()->getSchema($fullPath),
                $this->validator->getErrors()
            );
        }
    }

    /**
     * @param JsonSchema $annotation
     *
     * @return string
     *
     * @throws \InvalidArgumentException When the schema file is not found
     * @throws \UnexpectedValueException When multiple schema files
     *                                   with the same name are found
     */
    private function getSchemaPath(JsonSchema $annotation)
    {
        if (is_array($path = $this->locator->locate($annotation->filename))) {
            throw new \UnexpectedValueException('Multiple schemas found');
        }

        return $path;
    }
}


<?php

namespace Svi\OrmBundle;

use \Doctrine\DBAL\Schema\Schema;
use \Doctrine\DBAL\Schema\Table;
use \Doctrine\DBAL\Schema\Column;
use \Doctrine\DBAL\Connection;
use \Doctrine\DBAL\Query\QueryBuilder;
use Svi\AppContainer;
use Svi\Application;

abstract class Manager extends AppContainer implements ManagerInterface
{
	private $schemaName = null;
	/** @var Schema[] Schema */
	private static $schemas = [];
	private $cache = [];
	/** @var \ReflectionClass */
	private $reflection = null;

	public function __construct(Application $app, $schemaName = 'default')
	{
		parent::__construct($app);

		$this->schemaName = $schemaName;
	}

	public function getSchemaName()
	{
		return $this->schemaName;
	}

	/**
	 * @return Connection
	 */
	public function getConnection()
	{
		return $this->app['dbs'][$this->schemaName];
	}

	/**
	 * Must return fields in like that: classFieldName => Column schema
	 */
	abstract public function getDbFieldsDefinition();

	/**
	 * Must return table name in SQL DB where entity stored
	 */
	abstract public function getTableName();

	abstract public function getEntityClassName();

	/**
	 * @return \Doctrine\DBAL\Schema\Schema
	 */
	public function getDbSchema()
	{
		return self::$schemas[$this->getSchemaName()];
	}

	/**
	 * @return Table
	 * @throws \Exception
	 */
	public function getTableSchema()
	{
		if (!array_key_exists($this->getSchemaName(), self::$schemas)) {
			self::$schemas[$this->getSchemaName()] = new Schema();
		}
		if (!self::$schemas[$this->getSchemaName()]->hasTable($this->getTableName())) {
			/** @var \Doctrine\DBAL\Schema\Table $table */
			$table = self::$schemas[$this->getSchemaName()]->createTable($this->getTableName());
			$this->cache['table'] = $table;

			$dbColumnsToFieldNames = [];
			$fieldToColumnNames = [];
			$columns = [];
			foreach ($this->getDbFieldsDefinition() as $key => $value) {
				$column = $table->addColumn($value[0], $value[1]);
				if (count($value) > 2) {
					$i = 0;
					foreach ($value as $pKey => $pVal) {
						$i++;
						if ($i < 3)	continue;
						if ($pVal === 'id') {
                            $column->setNotnull(true);
                            $column->setAutoincrement(true);
                            $table->setPrimaryKey(array($value[0]));
                            $this->cache['idFieldName'] = $key;
                            $this->cache['idColumnName'] = $column->getName();
                        } elseif ($pVal === 'primary') {
                            $column->setNotnull(true);
                            $table->setPrimaryKey(array($value[0]));
                            $this->cache['idFieldName'] = $key;
                            $this->cache['idColumnName'] = $column->getName();
						} elseif ($pVal === 'ai') {
							$column->setAutoincrement(true);
						} elseif ($pVal === 'null') {
							$column->setNotnull(false);
						} elseif($pVal === 'unique') {
							$table->addUniqueIndex(array($column->getName()));
						} elseif($pVal === 'index') {
							$table->addIndex(array($column->getName()));
						} elseif($pVal === 'unsigned') {
							$column->setUnsigned(true);
						} else {
							switch (strtolower($pKey)) {
								case 'length': $column->setLength($pVal);break;
								case 'precision': $column->setPrecision($pVal);break;
								case 'scale': $column->setScale($pVal);break;
								case 'unsigned': $column->setUnsigned($pVal);break;
								case 'fixed': $column->setFixed($pVal);break;
								case 'notnull': $column->setNotnull($pVal);break;
								case 'ai': $column->setAutoincrement($pVal);break;
								case 'comment': $column->setComment($pVal);break;
                                case 'default': $column->setDefault($pVal);break;
								default: throw new \Exception("Unsupported parameter \"$pVal\" for column \"$key\"");
							}
						}
					}
				}
				if (!$table->getPrimaryKey()) {
					throw new \Exception('There is no primary key for ' . $this->getEntityClassName());
				}
				$columns[$key] = $column;
				$dbColumnsToFieldNames[$column->getName()] = $key;
				$fieldToColumnNames[$key] = $column->getName();
			}
			foreach ($this->getIndexes() as $cols) {
				$table->addIndex($cols);
			}
			foreach ($this->getForeigners() as $manager => $params) {
				/** @var Manager $foreignManager */
				$foreignManager = call_user_func($manager . '::getInstance("' . $this->schemaName . '")');
				$table->addForeignKeyConstraint($foreignManager->getTableSchema(),
					is_array($params[0]) ? $params[0] : array($params[0]),
					is_array($params[1]) ? $params[1] : array($params[1]), isset($params[2]) ? $params[2] : array());
			}

			$this->cache['columns'] = $columns;
			$this->cache['db_to_field'] = $dbColumnsToFieldNames;
			$this->cache['field_to_db'] = $fieldToColumnNames;
			$this->cache['table'] = $table;
		}

		return $this->cache['table'];
	}

	/**
	 * Must return table indexes in that format:
	 * return [
	 *   ['tableDbColumn1', 'tableDbColumn2', ...],
	 *   ['tableDbColumn4', 'tableDbColumn7', ...],
	 *   ...
	 * ];
	 *
	 * If you want to add one-column index, just use 'index' field parameter in getFields()
	 *
	 * @return array
	 */
	public function getIndexes()
	{
		return [];
	}

	/**
	 * Must return table foreign keys constraints in that format:
	 * return [
	 *   'My\TestBundle\Manager\SomeForeignManager' => [['ourTableDbColumn1', 'ourTableDbColumn1', ...], ['foreignTableDbColumn1', 'foreignTableDbColumn2', ...]],
	 *   'My\TestBundle\Manager\OtherForeignManager' =>[['ourTableDbColumn2', 'ourTableDbColumn4', ...], ['foreignTableDbColumn2', 'foreignTableDbColumn4', ...]],
	 *   ...
	 * ];
	 *
	 * or simply:
	 *
	 * return [
	 *   'My\TestBundle\Entity\SomeForeignEntity' => ['ourTableDbColumn1', 'foreignTableDbColumn1', ['onDelete' => 'cascade']],
	 *   'My\TestBundle\Entity\OtherForeignEntity' =>['ourTableDbColumn2', 'foreignTableDbColumn2'],
	 *   ...
	 * ];
	 *
	 * @return array
	 */
	public function getForeigners()
	{
		return [];
	}

	/**
	 * Return schemas in like that: classFieldName => Column schema
	 * @return Column[]
	 * @throws \Exception
	 */
	public function getColumnsSchemas()
	{
		if (!array_key_exists('columns', $this->cache)) {
			$this->getTableSchema();
		}

		return $this->cache['columns'];
	}

	/**
	 * Returns field value by class private field name
	 * @param Entity $entity
	 * @param $fieldName
	 * @return mixed
	 */
	public function getFieldValue(Entity $entity, $fieldName)
	{
		$method = 'get' . ucfirst($fieldName);

		return $entity->$method();
	}

	/**
	 * @param Entity $entity
	 * @param $fieldName
	 * @param $value
	 * @return mixed
	 */
	public function setFieldValue(Entity $entity, $fieldName, $value)
	{
		$method = 'set' . ucfirst($fieldName);

		return $entity->$method($value);
	}

	/**
     * @param Entity $entity
	 * @param $dbFieldName
	 * @return mixed
	 * @throws \Exception
	 */
	public function getFieldValueByDbKey(Entity $entity, $dbFieldName)
	{
		$this->getTableSchema();
		if (!array_key_exists('db_to_field', $this->cache) && !array_key_exists($dbFieldName, $this->cache['db_to_field'])) {
			throw new \Exception('There is no field mapped to ' . $dbFieldName . ' in ' . $this->getEntityClassName());
		}
		$method = 'get' . ucfirst($this->cache['db_to_field'][$dbFieldName]);

		return $entity->$method();
	}

	/**
	 * Sets class field value by DB field name
	 *
     * @param Entity $entity
	 * @param $dbFieldName
	 * @param $value
	 * @throws \Exception
	 */
	public function setFieldValueByDbKey(Entity $entity, $dbFieldName, $value)
	{
		$this->getTableSchema();
		if (!array_key_exists('db_to_field', $this->cache) && !array_key_exists($dbFieldName, $this->cache['db_to_field'])) {
			throw new \Exception('There is no field mapped to ' . $dbFieldName . ' in ' . get_class($this));
		}
		$fieldName = $this->cache['db_to_field'][$dbFieldName];
		$method = 'set' . ucfirst($fieldName);

		/** @var Column $columnSchema */
		$columnSchema = $this->cache['columns'][$fieldName];
		if ($columnSchema->getType() == 'Array') {
			if (!is_array($value)) {
				$value = $value ? json_decode($value, true) : [];
			}
		} elseif ($columnSchema->getType() == 'Boolean') {
			$value = $value ? true : false;
		}

		$entity->$method($value);
	}

	/**
	 * Returns class field name which is primary ID field
	 *
	 * @return string
	 */
	public function getIdFieldName()
	{
		$this->getTableSchema();

		return $this->cache['idFieldName'];
	}

	/**
	 * Returns DB field name which is primary ID field
	 *
	 * @return mixed
	 */
	public function getIdColumnName()
	{
		$this->getTableSchema();

		return $this->cache['idColumnName'];
	}

	public function getDbColumnNames()
	{
		$this->getTableSchema();

		return $this->cache['field_to_db'];
	}

	/**
	 * Returns array which used for update or insert SQL operations
	 *
	 * @param Entity $entity
	 * @param bool $onlyChanged
	 * @param bool $updateLoadedData
	 * @return array
	 */
	public function getDataArray(Entity $entity, $onlyChanged = false, $updateLoadedData = false)
	{
		$result = array();

		foreach ($this->getColumnsSchemas() as $fieldName => $schema) {
			$value = $this->getFieldValue($entity, $fieldName);
			if ($schema->getType() == 'Array') {
				if (!is_array($value) || !$value) {
					$value = json_encode([]);
				} else {
					$value = json_encode($value);
				}
			}
			if ($onlyChanged && array_key_exists($schema->getName(), $entity->getLoadedData())) {
				if ($schema->getType() == 'Boolean') {
					if ($value === ($entity->getLoadedData()[$schema->getName()] ? true : false)) {
						continue;
					}
				}
				if ($value === $entity->getLoadedData()[$schema->getName()]) {
					continue;
				}
			}
			if ($updateLoadedData) {
				$entity->getLoadedData()[$schema->getName()] = $value;
			}
			if (!$value) {
				if ($value === false) {
					$value = '0';
				} elseif ($value === 0) {
					$value = '0';
				}
			}
			$result[$schema->getName()] = $value;
		}

		return $result;
	}

    /**
     * @param array $data
     * @return Entity[]
     */
	public function getListByData(array $data)
    {
        $result = [];

        foreach ($data as $entityData) {
            $result[] = $this->fillByData($entityData);
        }

        return $result;
    }

	/**
	 * Fills class fields by SQL returned data
	 *
	 * @param array $data
	 * @param Entity|null $entity
	 * @return Entity
	 */
	public function fillByData(array $data, Entity $entity = null)
	{
		$entity = $entity ? $entity : $this->createEntity();
		$entity->setLoadedData($data);
		foreach ($data as $key => $value) {
			if ($key == $this->getIdColumnName()) {
				$entity->setLoadedFromDb(true);
			}
			$this->setFieldValueByDbKey($entity, $key, $value);
		}

		return $entity;
	}

	public function save(Entity $entity)
	{
		$connection = $this->getConnection();
		if ($entity->getLoadedFromDb()) {
			$data = $this->getDataArray($entity,true, true);
			if (count($data)) {
				$connection->update($this->getTableName(), $data, [$this->getIdColumnName() => $this->getFieldValue($entity, $this->getIdFieldName())]);
			}
		} else {
			$data = $this->getDataArray($entity, false, true);
			if (count($data)) {
                if ($this->getIdFieldName() && $this->getColumnsSchemas()[$this->getIdFieldName()]->getAutoincrement()) {
                    unset($data[$this->getIdColumnName()]);
                }
				$connection->insert($this->getTableName(), $data);
			}
            if ($this->getIdFieldName() && $this->getColumnsSchemas()[$this->getIdFieldName()]->getAutoincrement()) {
                $this->setFieldValue($entity, $this->getIdFieldName(), $connection->lastInsertId());
            }
		}
		$this->cache['fetch'] = [];
		$entity->setLoadedFromDb(true);

		return $entity;
	}

	public function delete(Entity $entity)
	{
		$connection = $this->getConnection();
		if ($entity->getLoadedFromDb()) {
			$connection->delete($this->getTableName(), array($this->getIdColumnName() => $this->getFieldValue($entity, $this->getIdFieldName())));
			$this->cache['fetch'] = [];
		}
	}

	/**
	 * @param QueryBuilder $qb
	 * @param null $noCache
	 * @return Entity|null
	 */
	public function fetchOne(QueryBuilder $qb, $noCache = null)
	{
		$result = $this->fetch($qb, $noCache);

		return array_key_exists(0, $result) ? $result[0] : null;
	}

	/**
	 * @param QueryBuilder $qb
	 * @param null $noCache
	 * @return Entity[]
	 */
	public function fetch(QueryBuilder $qb, $noCache = null)
	{
		$qb->resetQueryPart('from');
		$columnNames = [];
		foreach ($this->getDbColumnNames() as $n) {
			$columnNames[] = 'e.' . $n;
		}
		$tableName = $this->getTableName();
		$qb->select(implode(', ', $columnNames))->from($tableName, 'e');

		$cacheKey = null;
		if (!$noCache) {
			$cacheKey = $qb->getSQL();
			foreach ($qb->getParameters() as $k => $v) {
				$cacheKey .= $k . $v;
			}
		}

		if ($cacheKey) {
			if (array_key_exists('fetch', $this->cache) && array_key_exists($cacheKey, $this->cache['fetch'])) {
				return $this->cache['fetch'][$cacheKey];
			}
		}
		$result = [];
		$items = $qb->execute()->fetchAll();
		if (count($items)) {
			foreach ($items as $e) {
				$result[] = $this->fillByData($e);
			}
		}
		if ($cacheKey) {
			if (!array_key_exists('fetch', $this->cache)) {
				$this->cache['fetch'] = [];
			}
			$this->cache['fetch'][$cacheKey] = $result;
		}

		return $result;
	}

	/**
	 * @param array $criteria
	 * @param array|null $orderBy
	 * @param null $limit
	 * @param null $offset
	 * @param null $noCache
	 * @return Entity[]
	 * @throws \Exception
	 */
	public function findBy(array $criteria = [], array $orderBy = null, $limit = null, $offset = null, $noCache = null)
	{
		$connection = $this->getConnection();

		$db = $connection->createQueryBuilder();
        if (count($criteria)) {
            foreach ($criteria as $col => $val) {
                if ($val === null) {
                    $db->andWhere($col . " IS NULL");
                } elseif (is_array($val)) {
                    $db->andWhere($col . " IN (" . implode(', ', $val) . ')');
                } elseif (is_numeric($col)) {
                    $db->andWhere($val);
                } else {
                    $db->andWhere($col . " = :$col")->setParameter($col, $val);
                }
            }
        }
		if (is_array($orderBy) && count($orderBy)) {
			foreach ($orderBy as $col => $val) {
				$db->addOrderBy($col, $val);
			}
		}
		if ($limit !== null) {
			$db->setMaxResults($limit);
		}
		if ($offset != null) {
			$db->setFirstResult($offset);
		}

		return $this->fetch($db, $noCache);
	}

	/**
	 * @param array $criteria
	 * @param array|null $orderBy
	 * @param null $noCache
	 * @return Entity|null
	 */
	public function findOneBy(array $criteria = [], array $orderBy = null, $noCache = null)
	{
		$result = self::findBy($criteria, $orderBy, 1, null, $noCache);

		return count($result) ? $result[0] : null;
	}

	public function __call($name, $arguments) {
	    $getTableColName = function ($field) {
            $field = lcfirst($field);
            $columns = $this->getDbColumnNames();
            if (!array_key_exists($field, $columns)) {
                throw new \Exception('There is no field ' . $field . ' in entity ' . $this->getEntityClassName());
            }

            return $columns[$field];
        };

		if (preg_match('/^findBy(.*)$/', $name, $matches)) {
			if (count($arguments) < 1) {
				throw new \Exception('Too few parameters');
			}

			return self::findBy([$getTableColName($matches[1]) => $arguments[0]],
                isset($arguments[1]) ? $arguments[1] : null,
                isset($arguments[2]) ? $arguments[2] : null,
                isset($arguments[3]) ? $arguments[3] : null,
                isset($arguments[4]) ? $arguments[4] : null);
		} elseif (preg_match('/^findOneBy(.*)$/', $name, $matches)) {
			if (count($arguments) < 1) {
				throw new \Exception('Too few parameters');
			}

			return $this->findOneBy([$getTableColName($matches[1]) => $arguments[0]],
                isset($arguments[1]) ? $arguments[1] : null,
                isset($arguments[2]) ? $arguments[2] : null);
		}

		throw new \ErrorException ('Call to Undefined Method ' . get_called_class() . '::' . $name . '()', 0, E_ERROR);
	}

	/**
	 * @return \ReflectionClass
	 */
    protected function getReflection()
	{
		if ($this->reflection === null) {
			$this->reflection = new \ReflectionClass($this->getEntityClassName());
		}

		return $this->reflection;
	}

	public function implementsInterface($interface)
    {
        return $this->getReflection()->implementsInterface($interface);
    }

	public function isRemovable()
	{
		return $this->getReflection()->implementsInterface(RemovableInterface::class);
	}

	/**
	 * @return Entity
	 */
	public function createEntity()
	{
		$className = $this->getEntityClassName();

		return new $className();
	}

	public function hasField($fieldName)
    {
        return isset($this->getDbFieldsDefinition()[$fieldName]);
    }

}


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

namespace DoctrineModule\Service;

use InvalidArgumentException;
use Doctrine\Common\Annotations;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
use Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator;
use DoctrineModule\Options\Driver as DriverOptions;
use DoctrineModule\Service\AbstractFactory;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * MappingDriver ServiceManager factory
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @author  Kyle Spraggs <theman@spiffyjr.me>
 */
class DriverFactory extends AbstractFactory
{
    /**
     * {@inheritDoc}
     * @return MappingDriver
     */
    public function createService(ServiceLocatorInterface $sl)
    {
        /* @var $options DriverOptions */
        $options = $this->getOptions($sl, 'driver');

        return $this->createDriver($sl, $options);
    }

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

    /**
     * @param  ServiceLocatorInterface  $sl
     * @param  DriverOptions            $options
     * @throws InvalidArgumentException
     * @return MappingDriver
     */
    protected function createDriver(ServiceLocatorInterface $sl, DriverOptions $options)
    {
        $class = $options->getClass();

        if (!$class) {
            throw new InvalidArgumentException('Drivers must specify a class');
        }

        if (!class_exists($class)) {
            throw new InvalidArgumentException(sprintf('Driver with type "%s" could not be found', $class));
        }

        // Not all drivers (DriverChain) require paths.
        $paths = $options->getPaths();

        // Special options for AnnotationDrivers.
        if ('Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver' === $class
            || is_subclass_of($class, 'Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver')
        ) {
            $reader = new Annotations\AnnotationReader;
            $reader = new Annotations\CachedReader(
                new Annotations\IndexedReader($reader),
                $sl->get($options->getCache())
            );
            /* @var $driver MappingDriver */
            $driver = new $class($reader, $paths);
        } else {
            /* @var $driver MappingDriver */
            $driver = new $class($paths);
        }

        if ($options->getExtension() && $driver instanceof FileDriver) {
            /* @var $driver FileDriver */
            /* @var $locator \Doctrine\Common\Persistence\Mapping\Driver\FileLocator */
            $locator = $driver->getLocator();

            if (get_class($locator) === 'Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator') {
                $driver->setLocator(new DefaultFileLocator($locator->getPaths(), $options->getExtension()));
            } else {
                throw new InvalidArgumentException(
                    sprintf(
                        'Discovered file locator for driver of type "%s" is an instance of "%s". This factory '
                        . 'supports only the DefaultFileLocator when an extension is set for the file locator',
                        get_class($driver),
                        get_class($locator)
                    )
                );
            }
        }

        // Extra post-create options for DriverChain.
        if ($driver instanceof MappingDriverChain && $options->getDrivers()) {
            /* @var $driver \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain */
            $drivers = $options->getDrivers();

            if (!is_array($drivers)) {
                $drivers = array($drivers);
            }

            foreach ($drivers as $namespace => $driverName) {
                if (null === $driverName) {
                    continue;
                }
                $options = $this->getOptions($sl, 'driver', $driverName);
                $driver->addDriver($this->createDriver($sl, $options), $namespace);
            }
        }

        return $driver;
    }
}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

use LibXMLError;
use Nette\IOException;
use Nette\Utils\Finder;
use SimpleXMLElement;
use SplFileInfo;
use ZipArchive;

/**
 * Pomocna trida pro praci se soubory
 *
 * @author Attreid <attreid@gmail.com>
 */
class File
{

	/**
	 * Smazani adresare
	 * @param string $directory adresar
	 * @param bool $removeDir smazat adresar (false smaze jen obsah)
	 */
	public static function removeDir(string $directory, bool $removeDir = true): void
	{
		$dir = @dir($directory);
		if ($dir) {
			while ($file = $dir->read()) {
				if ($file == '.' || $file == '..') {
					continue;
				} else if (is_dir($dir->path . DIRECTORY_SEPARATOR . $file)) {
					self::removeDir($dir->path . DIRECTORY_SEPARATOR . $file);
				} else {
					unlink($dir->path . DIRECTORY_SEPARATOR . $file);
				}
			}
			if ($removeDir) {
				rmdir($dir->path);
			}
			$dir->close();
		}
	}

	/**
	 * Je adresar prazdny?
	 * @param string $path
	 * @return bool
	 */
	public static function isDirEmpty(string $path): bool
	{
		return (count(glob("$path/*")) === 0);
	}

	/**
	 * Rozbaleni adresare ZIP
	 * @param string $archive
	 * @param string $dir
	 * @param bool $remove
	 * @throws IOException
	 */
	public static function extractZip(string $archive, string $dir, bool $remove = false): void
	{
		$zip = new ZipArchive();
		$x = $zip->open($archive);
		if ($x === true) {
			if (!$zip->extractTo($dir)) {
				throw new IOException("File '$archive' cannot be extracted");
			}
			$zip->close();
			if ($remove) {
				unlink($archive);
			}
		} else {
			throw new IOException("File '$archive' cannot be opened: $x");
		}
	}

	/**
	 * Zazipuje soubor/y nebo adresar|e
	 *
	 * @param string|array $sourcePath cesta k adresari k archivaci
	 * @param string $outZipPath cesta k vystupnimu souboru zip
	 */
	public static function zip($sourcePath, string $outZipPath): void
	{
		$zipFile = new ZipArchive();
		$zipFile->open($outZipPath, ZipArchive::CREATE);

		if (is_array($sourcePath)) {
			foreach ($sourcePath as $source) {
				self::addToZip((string) $source, $zipFile);
			}
		} else {
			self::addToZip((string) $sourcePath, $zipFile);
		}

		$zipFile->close();
	}

	/**
	 * Prida source do zipu
	 * @param string $sourcePath
	 * @param ZipArchive $zipFile
	 */
	private static function addToZip(string $sourcePath, ZipArchive $zipFile): void
	{
		$source = new SplFileInfo($sourcePath);
		$exclusiveLength = strlen(str_replace($source->getFilename(), '', $source->getRealPath()));

		if ($source->isReadable()) {
			if ($source->isDir()) {
				$zipFile->addEmptyDir($source->getFilename());

				foreach (Finder::findFiles('*')
							 ->from($sourcePath) as $file) {
					/* @var $file \SplFileObject */
					$filePath = $file->getRealPath();
					$localPath = substr($filePath, $exclusiveLength);

					if ($file->isDir()) {
						$zipFile->addEmptyDir($localPath);
					} else {
						$zipFile->addFile($filePath, $localPath);
					}
				}
			} else {
				$zipFile->addFile($source->getRealPath(), $source->getFilename());
			}
		}
	}

	/**
	 * Rozbaleni adresare GZ
	 * @param string $archive
	 * @param string $sufix
	 * @throws IOException
	 */
	public static function extractGZ(string $archive, string $sufix = null): void
	{
		if ($sfp = @gzopen($archive, "rb")) {
			$source = str_replace('.gz', '', $archive);
			if ($sufix != null) {
				$source .= '.' . $sufix;
			}
			if ($fp = @fopen($source, "w")) {

				while (!gzeof($sfp)) {
					$string = gzread($sfp, 4096);
					if (!fwrite($fp, $string, strlen($string))) {
						throw new IOException("File '$source' cannot be write.");
					}
				}
				fclose($fp);
			} else {
				throw new IOException("File '$source' cannot be write.");
			}
			gzclose($sfp);
			unlink($archive);
		} else {
			throw new IOException("File '$archive' cannot be read.");
		}
	}

	/**
	 * Cteni ze souboru po radcich
	 * @param string $file
	 * @param callable $callable function($buffer, $line) $line -> cislo radku, pokud metoda vrati false, ukonci se cyklus
	 * @param int|null $length
	 * @throws IOException
	 */
	public static function readLine(string $file, callable $callable, ?int $length = 4096): void
	{
		if (!$handle = fopen($file, "r")) {
			throw new IOException("File '$file' cannot be open.");
		}

		$fgets = function () use (&$handle, &$length) {
			if ($length !== null) {
				return fgets($handle, $length);
			} else {
				return fgets($handle);
			}
		};

		$line = 1;
		$stopped = false;
		while (($buffer = $fgets()) !== false) {
			if ($callable($buffer, $line++) === false) {
				$stopped = true;
				break;
			}
		}
		if (!$stopped && !feof($handle)) {
			throw new IOException("Error: unexpected fgets() fail '$file'");
		}
		fclose($handle);
	}

	/**
	 * Vrati velikost souboru nebo slozky
	 * @param string $path
	 * @return float
	 */
	public static function size(string $path): float
	{
		if (is_file($path)) {
			return filesize($path);
		} else {
			$size = 0;
			foreach (glob(rtrim($path, '/') . '/*', GLOB_NOSORT) as $each) {
				$size += self::size($each);
			}
			return $size;
		}
	}

	/**
	 * Vrati nazvy trid v souboru
	 * @param string $file
	 * @return string[]
	 */
	public static function getClasses(string $file): array
	{
		$php_code = file_get_contents($file);
		$classes = [];
		$tokens = token_get_all($php_code);
		$count = count($tokens);
		for ($i = 2; $i < $count; $i++) {
			if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) {
				$class_name = $tokens[$i][1];
				$classes[] = $class_name;
			}
		}
		return $classes;
	}

	/**
	 * Parsuje XML
	 * @param string $file
	 * @return SimpleXMLElement
	 * @throws IOException
	 */
	public static function parseXml(string $file): SimpleXMLElement
	{
		libxml_use_internal_errors(true);
		$xml = simplexml_load_file($file);

		if (!$xml) {
			/* @var $errors LibXMLError[] */
			$errors = libxml_get_errors();

			$return = '';
			foreach ($errors as $error) {
				switch ($error->level) {
					case LIBXML_ERR_WARNING:
						$return .= "Warning $error->code ";
						break;
					case LIBXML_ERR_ERROR:
						$return .= "Error $error->code ";
						break;
					case LIBXML_ERR_FATAL:
						$return .= "Fatal Error $error->code ";
						break;
				}
				$return .= "on line $error->line and column $error->column: " . trim($error->message) . ". ";
			}

			$return .= "File: $file";

			libxml_clear_errors();
			libxml_use_internal_errors(false);
			throw new IOException($return);
		}
		libxml_use_internal_errors(false);
		return $xml;
	}
}


<?php

namespace Limber\Router;

use Symfony\Component\HttpFoundation\Request;

class IndexedRouter extends Router
{
    /**
     * Set of indexed pointers to routes.
     *
     * @var array<string, array<Route>>
     */
    protected $indexes = [];

    /**
     * Router constructor.
     * @param array<Route>|null $routes
     */
    public function __construct(array $routes = null)
    {
        if( $routes ){
            foreach( $routes as $route ){
                $this->indexRoute($route);
            }
        }
    }

    /**
     * Index the route.
     *
     * @param Route $route
     * @return void
     */
    protected function indexRoute(Route $route): void
    {
        foreach( $route->getMethods() as $method ){
            $this->indexes[$method][] = $route;
        }
    }

    /**
     * Add a route
     *
     * @param array $methods
     * @param string $uri
     * @param string|callable $target
     * @return Route
     */
    public function add($methods, string $uri, $target): Route
    {
        // Create new Route instance
        $route = new Route($methods, $uri, $target, $this->config);

        // Index the route
        $this->indexRoute($route);

        return $route;
    }

    /**
     * Resolve a request into its route.
     *
     * @param Request $request
     * @return Route|null
     */
    public function resolve(Request $request): ?Route
    {
        foreach( $this->indexes[$request->getMethod()] ?? [] as $route ){

            if( $route->matchUri($request->getPathInfo()) &&
                $route->matchMethod($request->getMethod()) &&
                $route->matchHostname($request->getHost()) &&
                $route->matchScheme($request->getScheme()) ){

                return $route;
            }
        }

        return null;
    }

    /**
     * @inheritDoc
     */
    public function getMethodsForUri(Request $request): array
    {
        $methods = [];

        foreach( $this->indexes as $routes ) {

            foreach( $routes as $route ){
                if( $route->matchUri($request->getPathInfo()) &&
                    $route->matchHostname($request->getHost()) &&
                    $route->matchScheme($request->getScheme()) ){
                    $methods = array_merge($methods, $route->getMethods());
                }
            }

        }

        return array_unique($methods);
    }
}


<?php

namespace Modules\Menu\Services;

use Dowilcox\KnpMenu\Menu as MenuProvider;
use Knp\Menu\MenuItem;
use Modules\Menu\Entities\Menu;

class MenuItemBuilder
{
    /**
     * @var \Knp\Menu\MenuFactory
     */
    public $factory;

    /**
     * MenuItemBuilder constructor.
     *
     * @param MenuProvider $provider
     */
    public function __construct(MenuProvider $provider)
    {
        $this->factory = $provider->getFactory();
    }

    /**
     * @return array
     */
    public function getMenuItems()
    {
        $items = [];

        $roots = Menu::roots()->visible()->get();
        foreach ($roots as $item) {
            $parent = $this->createItem($item->content->title)
                ->setExtra('patterns', $this->extractPattern($item))
                ->setUri($item->url);

            $this->attachChildren($item->children, $parent);

            $items[] = $parent;
        }

        return $items;
    }

    /**
     * @param $items
     * @param $parent
     *
     * @return array
     */
    private function attachChildren($items, $parent = null)
    {
        foreach ($items as $item) {
            /** @var $parent MenuItem */
            $parent = $parent->addChild($item->content->title)
                ->setExtra('patterns', $this->extractPattern($item))
                ->setUri($item->url);

            return $this->attachChildren($item->children, $parent);
        }
    }

    /**
     * @param Menu $item
     *
     * @return array
     */
    private function extractPattern($item)
    {
        $pattern = '';

        if ($item->type == Menu::TYPE_ROUTE) {
            $pattern = '/'.preg_quote($item->target).'\.(.+)/';
        }

        return [$pattern];
    }

    /**
     * creates a new menu item.
     *
     * @param $title
     *
     * @return MenuItem
     */
    private function createItem($title)
    {
        return new MenuItem($title, $this->factory);
    }
}


<?php

namespace Limber;

class Config
{
    /**
     * Config structure.
     *
     * @var array<string, mixed>
     */
    protected $items = [];

    /**
     * Resolve the flattened key into the actual value.
     *
     * @param string $key
     * @throws \Exception
     * @return mixed
     */
    protected function resolve(string $key)
    {
        // Break the dotted notation keys into its parts
        $parts = explode(".", $key);

        // Set the pointer at the root of the items array
        $pointer = &$this->items;

        /**
         *
         * Loop through all the parts and see if the key exists.
         *
         */
        foreach( $parts as $part ){

            if( array_key_exists($part, $pointer) === false ){
                throw new \Exception("Config key {$key} not found.");
            }

            $pointer = &$pointer[$part];
        }

        return $pointer;
    }

    /**
     * See if config has given key.
     *
     * @param string $key
     * @return boolean
     */
    public function has(string $key): bool
    {
        try {

            $this->resolve($key);

        } catch( \Exception $exception ){

            return false;
        }

        return true;
    }

    /**
     * Lazy load configuration files.
     *
     * @TODO How do we fallback to a default value?
     *
     * @param string $key
     * @param mixed|null $default
     * @return mixed
     */
    public function get(string $key, $default = null)
    {
        // Attempt to lazy load keys.
        if( $this->has($key) === false ){

            $this->load($key);

        }

        return $this->resolve($key);
    }

    /**
     * Add a new key/value pair
     *
     * @param string $key
     * @param mixed $value
     * @return void
     */
    public function add(string $key, $value): void
    {
        $this->items[$key] = $value;
    }

    /**
     * Undocumented function
     *
     * @param string $key
     * @return void
     */
    public function load(string $key): void
    {
        if( preg_match("/^([^\.]+)\.?/", $key, $match) ){

            // Save the key
            $key = $match[1];

            // Build the file path
            $file = path("config/{$key}.php");

            $this->loadFile($key, $file);
        }
    }

    /**
     * Load a file and assign it to the key.
     *
     * @param string $key
     * @param string $file
     * @return void
     */
    public function loadFile(string $key, string $file): void
    {
        // Check for file's existence
        if( file_exists($file) === false ){
            throw new \Exception("Config file not found: {$file}");
        }

        // Pull config file in and add values into master config
        $config = require_once $file;
        $this->add($key, $config);
    }
}


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

namespace Openbizx\Easy\Element;

use Openbizx\Easy\Element\InputElement;

/**
 * Password class is element for input password
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class Password extends InputElement
{
	public function readMetaData(&$xmlArr){
		parent::readMetaData($xmlArr);
		$this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "input_text";
		$this->cssErrorClass = isset($xmlArr["ATTRIBUTES"]["CSSERRORCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSERRORCLASS"] : $this->cssClass."_error";
		$this->cssFocusClass = isset($xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSFOCUSCLASS"] : $this->cssClass."_focus";
	}
    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
        $disabledStr = ($this->getEnabled() == "N") ? "DISABLED=\"true\"" : "";
        $style = $this->getStyle();
        $formobj = $this->GetFormObj();
		if (OPENBIZ_CLIENT_DEVICE != 'mobile') {
			if($formobj->errors[$this->objectName]){
				$func .= "onchange=\"this.className='$this->cssClass'\"";
			}else{
				$func .= "onfocus=\"this.className='$this->cssFocusClass'\" onblur=\"this.className='$this->cssClass'\"";
			}
		}
        $sHTML = "<INPUT TYPE=\"PASSWORD\" NAME='$this->objectName' ID=\"" . $this->objectName ."\" VALUE='$this->value' $disabledStr $this->htmlAttr $style $func />";
    	if($this->hint){
        	$sHTML.="<script>
        	\$j('#" . $this->objectName . "').tbHinter({
				text: '".$this->hint."'
			});
        	</script>";
        }
        return $sHTML;
    }

}

?>