<?php

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

namespace Openbizx\Easy;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\Object\MetaIterator;
use Openbizx\Object\Statefullable;
use Openbizx\Object\MetaObject;
use Openbizx\I18n\I18n;
use Openbizx\Helpers\MessageHelper;
/**
 * WebPage class is the class that contains list of forms.
 * View is same as html page.
 *
 * @package openbiz.bin.easy
 * @author rocky swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class WebPage extends MetaObject implements Statefullable
{

    public $title;
    public $keywords;
    public $templateEngine;
    public $templateFile;
    public $viewSet;
    public $tab;
    public $formRefs;
    public $widgets;
    public $isPopup = false;
    public $height;
    public $width;
    public $consoleOutput = true;
    public $messageFile = null;        // message file path
    protected $objectMessages;
    public $cacheLifeTime = 0;
    public $lastRenderedForm;

    public $formRefLibs;

    private $_app;

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

    /**
     * Read Metadata from xml array
     *
     * @param array $xmlArr
     * @return void
     */
    protected function readMetadata(&$xmlArr)
    {
        parent::readMetaData($xmlArr);
        $this->objectName = $this->prefixPackage($this->objectName);
        $this->title = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["TITLE"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["TITLE"] : null;
        $this->keywords = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["KEYWORDS"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["KEYWORDS"] : null;
        $this->templateEngine = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["TEMPLATEENGINE"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["TEMPLATEENGINE"] : null;
        $this->templateFile = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["TEMPLATEFILE"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["TEMPLATEFILE"] : null;
        //echo __METHOD__. '-' . __LINE__ . ' templateFile : ' . $this->templateFile . '
';
        $this->viewSet = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["VIEWSET"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["VIEWSET"] : null;
        $this->tab = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["TAB"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["TAB"] : null;

        $this->formRefs = new MetaIterator($xmlArr["WEBPAGE"]["FORMREFERENCES"]["REFERENCE"], "Openbizx\Easy\FormReference", $this);

        if ($xmlArr["WEBPAGE"]["FORMREFERENCELIBS"]) {
            $this->formRefLibs = new MetaIterator($xmlArr["WEBPAGE"]["FORMREFERENCELIBS"]["REFERENCE"], "Openbizx\Easy\FormReference", $this);
        }
        if ($xmlArr["WEBPAGE"]["WIDGETS"]) {
            $this->widgets = new MetaIterator($xmlArr["WEBPAGE"]["WIDGETS"]["REFERENCE"], "Openbizx\Easy\FormReference", $this);
        }
        $this->messageFile = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["MESSAGEFILE"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["MESSAGEFILE"] : null;
        $this->objectMessages = MessageHelper::loadMessage($this->messageFile, $this->package);
        $this->cacheLifeTime = isset($xmlArr["WEBPAGE"]["ATTRIBUTES"]["CACHELIFETIME"]) ? $xmlArr["WEBPAGE"]["ATTRIBUTES"]["CACHELIFETIME"] : "0";

        $this->readTile($xmlArr); // TODO: is this needed as title supports expression?

        $this->translate(); // translate for multi-language support
        if (empty($this->title)) {
            $this->title = $this->objectDescription;
        }
    }

    protected function readTile(&$xmlArr)
    {
        if (isset($xmlArr["WEBPAGE"]["TILE"])) {
            $this->formRefs = array();
            if (isset($xmlArr["WEBPAGE"]["TILE"]["ATTRIBUTES"])) {
                $tileName = $xmlArr["WEBPAGE"]["TILE"]["ATTRIBUTES"]["NAME"];
                $this->tiles[$tileName] = new MetaIterator($xmlArr["WEBPAGE"]["TILE"]["REFERENCE"], "Openbizx\Easy\FormReference", $this);
            } else {
                foreach ($xmlArr["WEBPAGE"]["TILE"] as $child) {
                    $tileName = $child["ATTRIBUTES"]["NAME"];
                    $this->tiles[$tileName] = new MetaIterator($child["REFERENCE"], "Openbizx\Easy\FormReference", $this);
                }
            }
            //echo "
"; print_r($this->tiles); echo "
";
            $tmp = array();
            $this->formRefs = new MetaIterator($tmp, "", $this);
            foreach ($this->tiles as $tile) {
                foreach ($tile as $ref) {
                    $this->formRefs->set($ref->objectName, $ref);
                }
            }
        }
    }

    /**
     * Check the Form is in the lib
     *
     * @param string $formName form name
     * @return bool inside or not
     */
    public function isInFormRefLibs($formName)
    {
        if ($this->formRefLibs) {
            $this->formRefLibs->rewind();
            while ($this->formRefLibs->valid()) {
                $reference = $this->formRefLibs->current();
                if ($reference->objectName == $formName) {
                    return true;
                }
                $this->formRefLibs->next();
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * Get message, and translate it
     *
     * @param <type> $msgId message Id
     * @param array $params
     * @return string message string
     */
    protected function getMessage($msgId, $params = array())
    {
        $message = isset($this->objectMessages[$msgId]) ? $this->objectMessages[$msgId] : constant($msgId);
        $message = I18n::t($message, $msgId, $this->getModuleName($this->objectName));
        return vsprintf($message, $params);
    }

    /**
     * Get/Retrieve Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function loadStatefullVars($sessionContext)
    {
        $sessionContext->loadObjVar($this->objectName, "LastRenderedForm", $this->lastRenderedForm);
    }

    /**
     * Save Session data of this object
     *
     * @param \Openbizx\Web\SessionContext $sessionContext
     * @return void
     */
    public function saveStatefullVars($sessionContext)
    {
        $sessionContext->saveObjVar($this->objectName, "LastRenderedForm", $this->lastRenderedForm);
    }

    /**
     * Get view set name
     *
     * @return mixed viewset name or null
     */
    public function getViewSet()
    {
        return $this->viewSet;
    }

    /**
     * Set the Render output to console (as calling print ...) or to a string buffer
     *
     * @param boolean $consoleOutput
     * @return void
     */
    public function setConsoleOutput($consoleOutput)
    {
        $this->consoleOutput = $consoleOutput;
    }

    /**
     * Proses rule
     *
     * @return void
     */
    public function processRule()
    {
    }

    /**
     * Set parameters
     *
     * @return void
     */
    public function setParameters()
    {
    }

    /**
     * Render this WebPage.
     *
     * @return mixed either print html content, or return html content
     * @example ../../../example/ViewObject.php
     */
    public function render()
    {
        if (!$this->allowAccess()) {
            $accessDenyWebpage = Openbizx::getObject(OPENBIZ_ACCESS_DENIED_WEBPAGE);
            return $accessDenyWebpage->render();
        }
        $this->initAllForms();
        // check the "fld_..." arg in url and put it in the search rule
        $this->processRequest();
        return $this->_render();
    }

    /**
     * Render this view. This function is called by Render() or ReRender()
     *
     * @return mixed either print html content or return html content if called by Render(), or void if called by ReRender()
     */
    protected function _render()
    {
        if ($this->cacheLifeTime > 0) {
            $pageUrl = $this->curPageURL();
            $cache_id = md5($pageUrl);
            //try to process cache service.
            $cacheSvc = Openbizx::getService(CACHE_SERVICE, 1);
            $cacheSvc->init($this->objectName, $this->cacheLifeTime);
            $this->consoleOutput = false;
            $output = ViewRenderer::render($this);
            Openbizx::$app->getLog()->log(LOG_DEBUG, "VIEW", "Set cache. url = " . $pageUrl);
            $cacheSvc->save($output, $cache_id);
            return $output;
        } else {
            $this->setClientScripts();
            return ViewRenderer::render($this);
        }
        return;
    }

    /**
     * Get current page URL
     * NOTE:
     * This method on next version maybe removed.
     * New method is {@link getCurrentPageUrl}
     *
     * @return string page URL
     */
    public function curPageURL()
    {
        return $this->getCurrentPageUrl();
    }

    /**
     * Get current page URL
     *
     * @return string page URL
     */
    public function getCurrentPageUrl()
    {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    /**
     * Set default client javascript and css that included in the html content
     *
     * @return void
     */
    protected function setClientScripts()
    {
        Openbizx::$app->getClientProxy()->includeBaseClientScripts();
    }

    /**
     * Initialize all form objects.
     *
     * @return void
     */
    protected function initAllForms()
    {
        foreach ($this->formRefs as $formRef) {
            $formRef->setViewName($this->objectName);
            $formName = $formRef->objectName;
            $formObj = Openbizx::getObject($formName);
            if ($formRef->subForms && method_exists($formObj, "SetSubForms")) {
                $formObj->setSubForms($formRef->subForms);
            }
        }
    }

    /**
     * Process request
     *
     * @return void
     */
    protected function processRequest()
    {
        // if url has form=...
        $paramForm = isset($_REQUEST['form']) ? $_REQUEST['form'] : null;

        // check url arg as fld:name=val
        $getKeys = array_keys($_REQUEST);
        $pageid = $_GET["pageid"];

        $paramFields = null;
        foreach ($getKeys as $key) {
            if (substr($key, 0, 4) == "fld:") {
                $fieldName = substr($key, 4);
                $fieldValue = $_REQUEST[$key];
                $paramFields[$fieldName] = $fieldValue;
            }
        }

        if (!$paramFields && !$pageid) {
            return;
        }

        // get the form object
        if (!$paramForm) { // get the first form name if no form is given
            foreach ($this->formRefs as $formRef) {
                $paramForm = $formRef->objectName;
                break;
            }
        }
        if (!$paramForm) {
            return;
        }
        $paramForm = $this->prefixPackage($paramForm);
        $formObj = Openbizx::getObject($paramForm);
        $formObj->setRequestParams($paramFields);
        if ($pageid) {
            $formObj->setCurrentPage($pageid);
        }
    }

    /**
     * Get output attributs
     *
     * @return array
     * @todo need to raname to getOutputAttributs() or getAttributes
     */
    public function outputAttrs()
    {
        $out['name'] = $this->objectName;
        $out['module'] = $this->getModuleName($this->objectName);
        $out['description'] = $this->objectDescription;
        $out["keywords"] = $this->keywords;
        if ($this->title) {
            $title = Expression::evaluateExpression($this->title, $this);
        } else {
            $title = $this->objectDescription;
        }
        $out['title'] = $title;
        return $out;
    }

    protected function translate()
    {
        $module = $this->getModuleName($this->objectName);
        $trans_string = I18n::t($this->title, $this->getTransKey('Title'), $module, $this->getTransPrefix());
        if ($trans_string) {
            $this->title = $trans_string;
        }
        $trans_string = I18n::t($this->objectDescription, $this->getTransKey('Description'), $module, $this->getTransPrefix());
        if ($trans_string) {
            $this->objectDescription = $trans_string;
        }
    }

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

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

}


<?php

namespace Purethink\CMSBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\SoftDeleteable;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Purethink\CoreBundle\Entity\Category;
use Purethink\CoreBundle\Entity\Gallery;
use Purethink\CoreBundle\Entity\Media;
use Purethink\CoreBundle\Entity\Tag;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use A2lix\I18nDoctrineBundle\Doctrine\ORM\Util\Translatable;

/**
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="Purethink\CMSBundle\Repository\ArticleRepository")
 * @ORM\HasLifecycleCallbacks
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class Article implements MetadataInterface, ArticleViewInterface, SoftDeleteable
{
    use Translatable;
    use SoftDeleteableEntity;
    use TimestampableEntity;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var boolean
     *
     * @ORM\Column(type="boolean")
     */
    protected $published = true;

    /**
     * @var UserInterface
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\User")
     * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
     */
    protected $user;

    /**
     * @var ArticleViewInterface
     *
     * @ORM\OneToOne(targetEntity="ArticleView", cascade={"persist"})
     * @ORM\JoinColumn(onDelete="CASCADE", nullable=false)
     */
    protected $view;

    /**
     * @var ComponentHasArticle
     *
     * @ORM\OneToMany(targetEntity="ComponentHasArticle", mappedBy="article")
     */
    protected $componentHasArticle;

    /**
     * @var Media
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Media", cascade={"persist"})
     * @ORM\JoinColumn(nullable=true)
     */
    protected $media;

    /**
     * @var Gallery
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Gallery", cascade={"persist"})
     * @ORM\OrderBy({"position" = "ASC"})
     */
    protected $gallery;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Purethink\CoreBundle\Entity\Tag", cascade={"persist"})
     * @ORM\JoinTable(name="article_has_tag",
     *      joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id")}
     * )
     * @Assert\Valid()
     */
    protected $tags;

    /**
     * @var Category
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Category", cascade={"persist"})
     */
    protected $category;

    /**
     * @var Article
     *
     * @ORM\OneToMany(targetEntity="Purethink\CMSBundle\Entity\ArticleSource", mappedBy="article", orphanRemoval=true, cascade={"persist"})
     * @Assert\Valid()
     */
    protected $sources;

    protected $translations;

    public function getName()
    {
        if ($this->getCurrentTranslation()) {
            return $this->getCurrentTranslation()->getName();
        }

        return null;
    }

    public function getSlug()
    {
        if ($this->getCurrentTranslation()) {
            return $this->getCurrentTranslation()->getSlug();
        }

        return null;
    }

    public function getTitle()
    {
        return $this->getName();
    }

    public function getDescription()
    {
        return $this->getCurrentTranslation()->getDescription();
    }

    public function getKeyword()
    {
        return $this->getCurrentTranslation()->getKeyword();
    }

    public function getViews()
    {
        return $this->getView();
    }

    public function getFirstSource()
    {
        if ($this->getSources()->count() > 0) {
            return $this->getSources()->first();
        }

        return null;
    }

    /**
     * @ORM\PreRemove
     *
     * @param LifecycleEventArgs $args
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        /** @var ComponentHasArticle $component */
        foreach ($this->getComponentHasArticle() as $component) {
            $element = $component->getComponentHasElement();

            $em = $args->getEntityManager();
            $em->remove($element);
            $em->flush();
        }
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    public function __toString()
    {
        if ($this->translations && $this->translations->count()) {
            return (string)$this->getName();
        }
        return '';
    }

    /**
     * Set user
     *
     * @param UserInterface $user
     * @return Article
     */
    public function setUser(UserInterface $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return UserInterface
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Constructor
     *
     * @param UserInterface $user
     */
    public function __construct(UserInterface $user = null)
    {
        $this->translations = new ArrayCollection();
        $this->componentHasArticle = new ArrayCollection();
        $this->sources = new ArrayCollection();
        $this->tags = new ArrayCollection();
        $this->setView(new ArticleView());

        if (null != $user) {
            $this->setUser($user);
        }
    }

    /**
     * Add componentHasArticle
     *
     * @param ComponentHasArticle $componentHasArticle
     * @return Article
     */
    public function addComponentHasArticle(ComponentHasArticle $componentHasArticle)
    {
        $this->componentHasArticle[] = $componentHasArticle;

        return $this;
    }

    /**
     * Remove componentHasArticle
     *
     * @param ComponentHasArticle $componentHasArticle
     */
    public function removeComponentHasArticle(ComponentHasArticle $componentHasArticle)
    {
        $this->componentHasArticle->removeElement($componentHasArticle);
    }

    /**
     * Get componentHasArticle
     *
     * @return Collection
     */
    public function getComponentHasArticle()
    {
        return $this->componentHasArticle;
    }

    /**
     * Set published
     *
     * @param boolean $published
     * @return Article
     */
    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }

    /**
     * Get published
     *
     * @return boolean
     */
    public function getPublished()
    {
        return $this->published;
    }

    /**
     * Set view
     *
     * @param ArticleViewInterface $view
     * @return Article
     */
    public function setView(ArticleViewInterface $view)
    {
        $this->view = $view;

        return $this;
    }

    /**
     * Get view
     *
     * @return ArticleViewInterface
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * @return Gallery
     */
    public function getGallery()
    {
        return $this->gallery;
    }

    /**
     * @param Gallery $gallery
     */
    public function setGallery($gallery)
    {
        $this->gallery = $gallery;
    }

    /**
     * Add tag
     *
     * @param Tag $tag
     *
     * @return Article
     */
    public function addTag(Tag $tag)
    {
        $this->tags[] = $tag;

        return $this;
    }

    /**
     * Remove tag
     *
     * @param Tag $tag
     */
    public function removeTag(Tag $tag)
    {
        $this->tags->removeElement($tag);
    }

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

    /**
     * @return Media
     */
    public function getMedia()
    {
        return $this->media;
    }

    /**
     * @param Media $media
     * @return Article
     */
    public function setMedia($media)
    {
        $this->media = $media;
        return $this;
    }

    /**
     * @return Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param Category $category
     * @return Article
     */
    public function setCategory($category)
    {
        $this->category = $category;
        return $this;
    }

    /**
     * Add source
     *
     * @param ArticleSource $source
     *
     * @return Article
     */
    public function addSource(ArticleSource $source)
    {
        $source->setArticle($this);
        $this->sources[] = $source;

        return $this;
    }

    /**
     * Remove source
     *
     * @param ArticleSource $source
     */
    public function removeSource(ArticleSource $source)
    {
        $this->sources->removeElement($source);
    }

    /**
     * Get sources
     *
     * @return Collection
     */
    public function getSources()
    {
        return $this->sources;
    }
}


<?php

namespace Environaut\Checks;

use Environaut\Checks\Check;

/**
 * This check compares PHP runtime configuration options (from php.ini etc.) against given values.
 * The following comparison operations are supported:
 * - "equals": the default comparison; checks whether the setting is exactly as given (e.g. "foo")
 * - "null": checks whether the setting is NULL
 * - "notempty": checks whether the setting has a value set (that is, not null or empty string)
 * - "version": checks how versions compare (e.g. "=>2.6.30")
 * - "regex": checks whether the PHP setting's value matches the given regular expression (e.g. "/file\.ini/"
 * - "integer": checks whether the integer or byte value of the PHP setting is correct (e.g. ">30" or ">=256M")
 *
 * By default the name of the check will be used as the PHP runtime setting name to check. For integer
 * or byte values that may be set to infinite values (like "-1" or "0") you can specify the setting's
 * infinite value via the "infinite" parameter. The comparison operation is "equals" by default and
 * may be specified via the "comparison" parameter.
 *
 * All supported parameters are:
 * - "setting": name of setting to check (defaults to the "name" of the check)
 * - "custom_name": name to be used for messages if the check's name is used as setting name
 * - "value": the value to compare the setting's value against
 * - "infinite": the infinite value of the setting to check (e.g. "-1" or "0" for integer or byte values)
 * - "comparison": the comparison operation to use (see above)
 * - "help": message to display when the setting's value is not correct
 */
class PhpSettingCheck extends Check
{
    /**
     * Default group name used in messages of the report.
     * By default also used as default setting group name if not customized.
     */
    const DEFAULT_CUSTOM_GROUP_NAME = 'PHP Settings';

    /**
     * Returns the default group name this check uses when none is specified.
     *
     * @return string default group name of the check
     */
    public function getDefaultGroupName()
    {
        return self::DEFAULT_CUSTOM_GROUP_NAME;
    }

    public function run()
    {
        $params = $this->getParameters();

        $setting = $params->get('setting', $this->getName());
        if (empty($setting)) {
            throw new \InvalidArgumentException(
                'Parameter "setting" must be a (valid) php.ini setting to check on class "' . get_class($this) . '".'
            );
        }

        $custom_name = $params->get('custom_name', $this->getName());
        $help = $params->get('help');
        $setting_value = $params->get('value');
        $infinite_value = $params->get('infinite');
        $comparison = strtolower($params->get('comparison', 'equals'));

        if (!in_array($comparison, self::getSupportedComparisons())) {
            throw new \InvalidArgumentException(
                'Unsupported comparison name: "' . $comparison .
                '". Supported are: ' . implode(', ', self::getSupportedComparisons())
            );
        }

        /**
         * The value of the configuration option as
         * - a string on success or
         * - an empty string for null values or
         * - false if the setting doesn't exist
         */
        $value = ini_get($setting);

        $okay = true;
        if (false === $value) {
            $this->addError('There is no setting with the name "' . $setting . '".', $custom_name);
            $okay = false;
        } else {
            switch ($comparison) {
                case 'integer':
                    // bail out here directly to not compare float values like "2.75M" or "1e3"
                    if ($value !== trim($value) || strpos($value, '.') !== false || stripos($value, 'e') !== false) {
                        $this->addError(
                            'Value of "' . $setting . '" should be "' . $setting_value .
                            '", but is: "' . $value . '". Leading whitespace or ' .
                            'decimal values will fail in practice as PHP treats e.g. "2.75M" as "2M"!',
                            $custom_name
                        );
                        $okay = false;
                        break;
                    }

                    if ((null !== $infinite_value && $value != $infinite_value) || null === $infinite_value) {
                        $okay = self::compareIntegers($value, $setting_value);
                        if (!$okay) {
                            $this->addError(
                                'Value of "' . $setting . '" should be "' . $setting_value .
                                '", but is: "' . $value . '"',
                                $custom_name
                            );
                        }
                    }
                    break;
                case 'regex':
                    if (!preg_match($setting_value, $value)) {
                        $this->addError(
                            'Value of "' . $setting . '" does not match "' . $setting_value .
                            '": ' . $value . '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
                case 'version':
                    $operator = self::getOperator($setting_value);
                    $setting_value_without_operator = ltrim($setting_value, '<>!=');
                    if (!version_compare($value, $setting_value_without_operator, $operator)) {
                        $this->addError(
                            'Version of "' . $setting . '" should be "' . $setting_value .
                            '", but is: "' . $value . '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
                case 'notempty':
                    if ($value === null || $value === "") {
                        $this->addError(
                            'Value of "' . $setting . '" should not be NULL or empty string, but is: "' . $value .
                            '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
                case 'null':
                    if ($value !== "") {
                        $this->addError(
                            'Value of "' . $setting . '" must be NULL, but is: "' . $value . '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
                case 'notequals':
                    if ($value === $setting_value) {
                        $this->addError(
                            'Value of "' . $setting . '" should not be "' . $setting_value . '", but is: "' . $value .
                            '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
                case 'equals':
                default:
                    if ($value === "" && $setting_value === "0") {
                        break; // boolean value should be off (and can be reported as "" or "0" according to php docs)
                    }
                    if ($value !== $setting_value) {
                        $this->addError(
                            'Value of "' . $setting . '" should be "' . $setting_value . '", but is: "' . $value .
                            '"',
                            $custom_name
                        );
                        $okay = false;
                    }
                    break;
            }
        }

        if (!$okay && $help !== null) {
            // TODO depending on local/global value and access level we could generate
            //  a small help here where to change the ini setting
            $this->addNotice($help, $custom_name);
        }

        if ($okay) {
            // TODO give better info depending on comparison type?
            $this->addInfo('Value of "' . $setting . '" is okay: "' . $value . '"', $custom_name);
        }

        return $okay;
    }

    /**
     * Returns the supported comparison names that may be used in comparison operations.
     *
     * @return array of strings (supported comparison names)
     */
    public static function getSupportedComparisons()
    {
        return array(
            'equals',
            'notequals',
            'regex',
            'notempty',
            'null',
            'version',
            'integer',
        );
    }

    /**
     * Compares the given values according to the comparison operator the second
     * value might have and returns whether the evaluation is true.
     *
     * @param string $value integer value that is set in php.ini (e.g. "8M")
     * @param string $setting_value comparison value as string (e.g. ">=8M")
     *
     * @return bool true if comparison is okay; false otherwise.
     */
    public static function compareIntegers($value, $setting_value)
    {
        $okay = false;

        $actual = self::getIntegerValue($value);
        $operator = self::getOperator($setting_value);
        $expected = self::getIntegerValue($setting_value);
        switch ($operator) {
            case '>':
                $okay = $actual > $expected;
                break;
            case '>=':
                $okay = $actual >= $expected;
                break;
            case '<':
                $okay = $actual < $expected;
                break;
            case '<=':
                $okay = $actual <= $expected;
                break;
            case '!=':
                $okay = $actual != $expected;
                break;
            case '=':
            default:
                $okay = $actual == $expected;
                break;
        }

        return $okay;
    }

    /**
     * Returns the comparison operator part of the given value. Valid known
     * comparison operators are: "<", ">", "<=", ">=", "!=" and "=".
     * By default a ">=" will be returned (if no comparison operator is found).
     *
     * @param string $value string that might contain a comparison operator (e.g. "<=2M")
     *
     * @return string operator string found
     */
    public static function getOperator($value)
    {
        // TODO make this smarter and perhaps support "eq", "ne", "le", "ge" etc.
        $operator = strpos($value, '>=') === 0 ? '>=' : null;
        if (null === $operator) {
            $operator = strpos($value, '>') === 0 ? '>' : null;
        }
        if (null === $operator) {
            $operator = strpos($value, '=') === 0 ? '=' : null;
        }
        if (null === $operator) {
            $operator = strpos($value, '<=') === 0 ? '<=' : null;
        }
        if (null === $operator) {
            $operator = strpos($value, '<') === 0 ? '<' : null;
        }
        if (null === $operator) {
            $operator = strpos($value, '!=') === 0 ? '!=' : null;
        }
        if (null === $operator) {
            $operator = '>=';
        }

        return $operator;
    }

    /**
     * Returns the integer value of the given value.
     *
     * @param mixed $value string to interpret (e.g. ">=2.75M")
     *
     * @return int integer value as PHP interprets it on ini settings
     */
    public static function getIntegerValue($value)
    {
        if (!is_numeric($value)) {
            // strip excessive whitespace
            $value = trim($value);
            // strip comparison operator
            $value = ltrim($value, '<>!=');
            // remove the K|M|G suffix if necessary
            $len = strlen($value);
            if (!is_numeric($value)) {
                $quantity = substr($value, 0, $len - 1);
                // we need this, as PHP sets a memory_limit of 0 if the ini value is 0.25M
                // another example: 2.75M will be 2M for PHP (e.g. on post_max_size)
                $quantity = intval($quantity);
            } else {
                $quantity = $value;
            }
            // get unit if this string represents a byte value
            $unit = strtolower(substr($value, $len - 1));
            switch ($unit) {
                case 'k':
                    $quantity *= 1024;
                    break;
                case 'm':
                    $quantity *= 1048576;
                    break;
                case 'g':
                    $quantity *= 1073741824;
                    break;
            }

            return $quantity;
        }

        return intval($value);
    }
}


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

Copyright 2017, Egbert van der Wal

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

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

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

use ReflectionClass;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Wedeto\Util\Cache\Cache;
use Wedeto\Util\DefVal;

/**
 * Autoloader that implements PSR-0 and PSR-4 standards. By default it will use
 * PSR-4, but registerNS can be instructed to treat a namespace as PSR-0
 * compatible. Alternatively, you can even provide a custom function to use as
 * a loader for a specific namespace.
 *
 * The class loader supports authorative mode - in this case it will trust the cache.
 * A cache instance is required for this mode. Each resolved class will be
 */
final class Autoloader
{
    const PSR0 = "PSR-0";
    const PSR4 = "PSR-4";

    protected static $logger = null;
    private $cache = null;
    private $authorative = false;
    private $registered_namespaces = [];
    private $root_namespace = ['sub_ns' => [], 'loaders' => []];

    public static function setLogger(LoggerInterface $logger)
    {
        self::$logger = $logger;
    }

    /**
     * @codeCoverageIgnore The NullLogger can only be set once, automatically. Unpredictable in testing
     */
    public static function getLogger()
    {
        if (self::$logger === null)
            self::$logger = new NullLogger;
        return self::$logger;
    }

    /**
     * Find all .php source files in the specified path or any subdirectory,
     * and return them in an array.
     *
     * @return array The list of .php files.
     */
    public static function findSourceFiles(string $path)
    {
        $result = array();
        $reader = dir($path);

        while ($file = $reader->read())
        {
            if ($file === '.' || $file === '..')
                continue;

            $file = $path . '/' . $file;
            if (substr($file, -4) === ".php")
            {
                $result[] = $file;
            }
            elseif (is_dir($file))
            {
                $sub = self::findSourceFiles($file);
                foreach ($sub as $f)
                    $result[] = $f;
            }
        }

        return $result;
    }

    /**
     * Look up file according to PSR0 standard:
     * http://www.php-fig.org/psr/psr-0/
     *
     * @param $ns string The namespace of the class
     * @param $class_name string The class to locate
     * @param $path string The path where the namespace classes are located
     * @return string The path to the class file. Null when not found
     */
    public static function findPSR0($ns, $class_name, $path)
    {
        $class = str_replace($ns, "", $class_name);
        $last_ns = strrpos($class, '\\');
        if ($last_ns !== false)
        {
            $prefix = substr($class, 0, $last_ns + 1);
            $class = substr($class, $last_ns + 1);
        }
        else
        {
            $prefix = "";
        }

        $prefix = str_replace('\\', DIRECTORY_SEPARATOR, $prefix);
        $class_file = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
        $class_path = $path . DIRECTORY_SEPARATOR . $prefix . $class_file;

        if (file_exists($class_path))
            return $class_path;

        return null;
    }

    /**
     * Look up file according to PSR4 standard:
     * http://www.php-fig.org/psr/psr-4/
     *
     * @param $ns string The namespace of the class
     * @param $class_name string The class to locatae
     * @param $path string The path where the namespace classes are located
     * @return string The path to the class file. Null when not found
     */
    public static function findPSR4($ns, $class_name, $path)
    {
        $class = str_replace($ns, "", $class_name);
        $class_file = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

        $class_path = $path . DIRECTORY_SEPARATOR . $class_file;
        if (file_exists($class_path))
            return $class_path;

        return null;
    }

    /**
     * Set the cache object caching resolved classes
     * @param Cache $cache The cache to use
     * @return Autoloader Provides fluent interface
     */
    public function setCache(Cache $cache)
    {
        $this->cache = $cache;
        return $this;
    }

    /**
     * @return Cache the cache object in use
     */
    public function getCache()
    {
        return $this->cache;
    }

    /**
     * Set the authorative state
     * @param bool $authorative When true, classes without a cache entry are considered
     *                          non-existent. On the first call to autoload, the cache
     *                          is built if this wasn't done before. Without a cache,
     *                          this flag is useless and ignored.
     * @return Autoloader Provides fluent interface
     */
    public function setAuthorative(bool $authorative = true)
    {
        $this->authorative = $authorative;
        return $this;
    }

    /**
     * @return bool The authorative state. When true, the autoloader will not attempt to
     *              load classes where no cache entry exists for.
     */
    public function getAuthorative()
    {
        return $this->authorative;
    }

    /**
     * Register a namespace with the autoloader.
     *
     * @param $ns string The namespace to register
     * @param $path string The path where to find classes in this namespace
     * @param $standard mixed Autoloader::PSR4 or Autoloader::PSR0. PSR4 is
     *                        used by default. You may also provide a callback
     *                        function here that will be used as the loader for
     *                        this namespace, rather than the provided PSR-0
     *                        and PSR-4 loaders.
     */
    public function registerNS(string $ns, string $path, $standard = Autoloader::PSR4)
    {
        if (!file_exists($path) || !is_dir($path) || !is_readable($path))
            throw new \InvalidArgumentException("Path $path is not readable");

        if ($standard !== Autoloader::PSR0 && $standard !== Autoloader::PSR4 && !is_callable($standard))
            throw new \InvalidArgumentException("Invalid standard: $standard");

        // Strip a leading namespace separator
        $ns = trim($ns, '\\');

        // Get the namespace parts
        $parts = explode('\\', $ns);

        $this->registered_namespaces[$ns] = true;

        // Make sure there is a trailing namespace separator
        if ($ns !== "" && substr($ns, -1, 1) !== '\\')
            $ns .= '\\';

        $ref = &$this->root_namespace;
        foreach ($parts as $part)
        {
            // Registering empty namespace
            if ($part === "")
                break;

            if (!isset($ref['sub_ns'][$part]))
                $ref['sub_ns'][$part] = ['loaders' => [], 'sub_ns' => []];

            $ref = &$ref['sub_ns'][$part];
        }

        $ref['loaders'][] = [
            'ns' => $ns,
            'path' => $path,
            'std' => $standard
        ];
    }

    /**
     * Build or rebuild the class cache. This will scan all defined PSR4 paths for .php files,
     * deduce the resulting classname from the path and add the path to the cache.
     *
     * This works only when solely PSR4 namespaces are defined. There is
     * ambiguity in the file path -> class name for PSR0-based namespaces as
     * directory separators can be converted to either namespace separators or
     * underscores. To avoid this ambiguity, a exception is thrown when PSR0 namespaces
     * have been registered.
     *
     * If any of the paths contain files that are not PSR4 compatible, errors may occur,
     * because the files are not actually loaded to check if they contain the correct class.
     * When two or more files map to the same class name, a LogicException is thrown.
     *
     * When authorative mode is enabled, after running buildCache the class loader will only
     * load classes that were found by buildCache.
     */
    public function buildCache()
    {
        if ($this->cache === null)
            throw new \LogicException("Cannot build cache without a cache instance");

        $this->cache->set('cache_built', false);
        $this->cache->set('classpaths', array());

        $stack = array($this->root_namespace);

        while (!empty($stack))
        {
            $ref = array_pop($stack);
            foreach ($ref['loaders'] as $loader)
            {
                if ($loader['std'] !== Autoloader::PSR4)
                    throw new \LogicException("Cache builder only works with pure PSR4-based namespaces");

                $class_count = 0;
                $root = $loader['path'] . DIRECTORY_SEPARATOR;
                $ns = $loader['ns'];
                $php_files = self::findSourceFiles($loader['path']);
                foreach ($php_files as $file)
                {
                    $rel_file = substr($file, strlen($root));

                    // Store absolute resolved paths when not using stream wrappers
                    if (strpos($file, '://') === false) $file = realpath($file);
                    $parts = explode(DIRECTORY_SEPARATOR, $rel_file);
                    $class_name = substr($ns . implode('\\', $parts), 0, -4);
                    if ($this->cache->has('classpaths', $class_name))
                    {
                        $conflict = $this->cache->get('classpaths', $class_name);
                        throw new \LogicException(sprintf(
                            "Duplicate class definition in file %s and %s (conflicting namespace: %s)",
                            $file,
                            $conflict,
                            $ns
                        ));
                    }

                    $this->cache->set('classpaths', $class_name, $file);
                    ++$class_count;
                }
                self::getLogger()->info('Found {0} classes in namespace {1}', [$class_count, $ns]);
            }

            foreach ($ref['sub_ns'] as $sub_ns)
                array_push($stack, $sub_ns);
        }

        $this->cache->set('cache_built', true);
        self::getLogger()->info('Class cache built');
    }

    /**
     * The spl_autoloader that loads classes registered namespaces
     * @param string $class_name The class to load
     */
    public function autoload($class_name)
    {
        // Basic check
        if (class_exists($class_name, false))
            return;

        // Use cache when available
        if ($this->cache !== null)
        {
            $cache_built = $this->cache->dget('cache_built', false);

            $path = $this->cache->get('classpaths', $class_name);
            if ($this->authorative && ($path === false || ($cache_built && $path === null)))
                return; // Authorative, no match found, so no loading

            if (!empty($path))
            {
                require_once $path;
                return;
            }

            // No match found, not authorative. Keep looking
        }

        $loaders = $this->getClassLoaders($class_name);
        foreach ($loaders as $loader)
        {
            $path = null;
            if ($loader['std'] === Autoloader::PSR0)
            {
                $path = self::findPSR0($loader['ns'], $class_name, $loader['path']);
            }
            elseif ($loader['std'] === Autoloader::PSR4)
            {
                $path = self::findPSR4($loader['ns'], $class_name, $loader['path']);
            }
            elseif (is_callable($loader['std']))
            {
                try
                {
                    $path = $loader['std']($class_name);
                }
                catch (\Throwable $e)
                {
                    self::getLogger()->critical(
                        'Class loader for {ns} threw exception with ' .
                        'attempting to load class {class}: {exception}',
                        ['ns' => $loader['ns'], 'exception' => $e, 'class' => $class_name]
                    );
                } // Don't throw any errors
            }

            if (empty($path))
                continue;

            require_once $path;

            $exists = class_exists($class_name) || trait_exists($class_name) || interface_exists($class_name);
            if (self::$logger)
            {
                if (trait_exists($class_name))
                    self::$logger->debug("Loaded trait {0} from path {1}", [$class_name, $path]);
                elseif (interface_exists($class_name))
                    self::$logger->debug("Loaded interface {0} from path {1}", [$class_name, $path]);
                elseif (class_exists($class_name, false))
                    self::$logger->debug("Loaded class {0} from path {1}", [$class_name, $path]);
                else
                    self::$logger->error("File {0} does not contain class {1}", [$path, $class_name]);
            }

            // When a class has been loaded, don't loop any further
            if ($exists)
                break;
        }

        // Cache resolved path
        if ($this->cache !== null)
        {
            if (!empty($path))
                $this->cache->set('classpaths', $class_name, $path);
            else // Cache failure
                $this->cache->set('classpaths', $class_name, false);
        }
    }

    /**
     * Find the class name of the Composer autoloader. The name starts
     * with ComposerAutoloader and has a random suffix. Therefore, the list
     * of class names is obtained and all class names are compared with this pattern.
     */
    public static function findComposerAutoloader()
    {
        // Find the Composer Autoloader class using its (generated) name
        $list = get_declared_classes();
        foreach ($list as $cl)
            if (substr($cl, 0, 18) === "ComposerAutoloader")
                return $cl;

        // @codeCoverageIgnoreStart
        // Tests run using composer autoloader
        return null;
        // @codeCoverageIgnoreEnd
    }

    /**
     * Get the Composer vendor directory, using the Composer autoloader class
     * name provided.
     *
     * @param string $composer_loader_class The fully qualified class name of the Composer autoloader
     * @return string The vendor dir used by composer
     */
    public static function findComposerAutoloaderVendorDir(string $composer_loader_class)
    {
        $ref = new \ReflectionClass($composer_loader_class);

        // Composer is located at MyProject/vendor/composer
        $path = dirname($ref->getFileName());
        return dirname($path);
    }

    /**
     * Import the configuration from the Composer autoloader, by specifying the
     * class name of the Composer Autoloader. This is used to locate the
     * composer folder, which contains files autoload_psr0.ph and/or
     * autoload_psr4.php which return an array of namespace -> path mappings,
     * which are then registered in the Wedeto Autoloader.
     *
     * @param string $composer_loader_class The fully qualified class name of
     * the Composer class loader.
     */
    public function importComposerAutoloaderConfiguration(string $composer_vendor_dir)
    {
        $cdir = $composer_vendor_dir . DIRECTORY_SEPARATOR . 'composer';
        $psr0 = $cdir . DIRECTORY_SEPARATOR . 'autoload_psr0.php';
        if (file_exists($psr0))
        {
            $namespaces = include($psr0);
            foreach ($namespaces as $ns => $paths)
                foreach ($paths as $path)
                    $this->registerNS($ns, $path, Autoloader::PSR0);
        }

        $psr4 = $cdir . DIRECTORY_SEPARATOR . 'autoload_psr4.php';
        if (file_exists($psr4))
        {
            $namespaces = include($psr4);
            foreach ($namespaces as $ns => $paths)
                foreach ($paths as $path)
                    $this->registerNS($ns, $path, Autoloader::PSR4);
        }
    }

    /**
     * Get a list of class loaders that may be able to load the specified
     * class or namespace. The resulting list is ordered so that the most
     * specific class loader comes first and the most generic comes last.
     *
     * @param string $class The fully qualified class (or namespace) to be loaded
     * @return array A list of loaders, each containing keys:
     *               - 'path' where the classes are stored
     *               - 'std' either Autoloader::PSR0, Autoloader::PSR4 or a callable to be used
     *                  delegate the autoload task to
     *               - 'ns' the namespace this loader provides
     */
    public function getClassLoaders(string $class)
    {
        $parts = explode("\\", $class);
        $result = array();
        $ref = &$this->root_namespace;
        $sub_ns = "";
        foreach ($parts as $part)
        {
            foreach ($ref['loaders'] as $loader)
                $result[] = $loader;

            if (!isset($ref['sub_ns'][$part]))
                break;

            $ref = &$ref['sub_ns'][$part];
        }

        // Reverse the result, because the last one is the most specific
        // namespace, which would be the one to try first.
        return array_reverse($result);
    }

    /**
     * @return array The list of registered namespace
     */
    public function getRegisteredNamespaces()
    {
        return array_keys($this->registered_namespaces);
    }
}


<?php declare(strict_types=1);

namespace Quanta;

class Printable
{
    /**
     * The value to represent as a string.
     *
     * @var mixed
     */
    private $value;

    /**
     * Whether the value should be represented as a callable.
     *
     * @var bool
     */
    private $callable;

    /**
     * The string length limit.
     *
     * @var int
     */
    private $strlim;

    /**
     * The array size limit.
     *
     * @var int
     */
    private $arrlim;

    /**
     * Constructor.
     *
     * @param mixed $value
     * @param bool  $callable
     * @param int   $strlim
     * @param int   $arrlim
     */
    public function __construct($value, bool $callable = false, int $strlim = 20, int $arrlim = 3)
    {
        $this->value = $value;
        $this->callable = $callable;
        $this->strlim = $strlim;
        $this->arrlim = $arrlim;
    }

    /**
     * Return a new Printable with the given string limit.
     *
     * @param int $strlim
     * @return \Quanta\Printable
     */
    public function withStringLimit(int $strlim): Printable
    {
        return new Printable($this->value, $this->callable, $strlim, $this->arrlim);
    }

    /**
     * Return a new Printable with the given array limit.
     *
     * @param int $arrlim
     * @return \Quanta\Printable
     */
    public function withArrayLimit(int $arrlim): Printable
    {
        return new Printable($this->value, $this->callable, $this->strlim, $arrlim);
    }

    /**
     * Return a string representation of the value.
     *
     * @return string
     */
    public function __toString()
    {
        $type = gettype($this->value);

        switch ($type) {
            case 'boolean':
                return $this->boolean($this->value);
                break;
            case 'integer':
                return $this->int($this->value);
                break;
            case 'double':
                return $this->float($this->value);
                break;
            case 'string':
                return $this->string($this->value);
                break;
            case 'array':
                return $this->array($this->value);
                break;
            case 'object':
                return $this->object($this->value);
                break;
            case 'resource':
                return $this->resource($this->value);
                break;
            case 'NULL':
                return 'NULL';
                break;
            default:
                return '(unknown type)';
                break;
        };
    }

    /**
     * Return a formatted string from the given boolean.
     *
     * @param bool $value
     * @return string
     */
    private function boolean(bool $value): string
    {
        return $value ? 'true' : 'false';
    }

    /**
     * Return a formatted string from the given int.
     *
     * @param int $value
     * @return string
     */
    private function int(int $value): string
    {
        return (string) $value;
    }

    /**
     * Return a formatted string from the given float.
     *
     * @param float $value
     * @return string
     */
    private function float(float $value): string
    {
        return (string) $value;
    }

    /**
     * Return a formatted string from the given string.
     *
     * Prepend the string with an ellipsis when it is longer than the limit.
     *
     * @param string $value
     * @return string
     */
    private function string(string $value): string
    {
        if ($this->callable && is_callable($value)) {
            return sprintf('function %s()', $value);
        }

        return strlen($value) > $this->strlim
            ? $this->quoted(substr($value, 0, $this->strlim) . '...')
            : $this->quoted($value);
    }

    /**
     * Return a formatted string from the given array.
     *
     * @param array $value
     * @return string
     */
    private function array(array $value): string
    {
        if ($this->callable && is_callable($value)) {
            $class = ! is_string($value[0])
                ? $this->classname($value[0])
                : $value[0];

            $method = $value[1];

            return sprintf('function %s::%s()', $class, $method);
        }

        $slice = array_slice($value, 0, $this->arrlim, true);

        $elems = $this->isAssociative($slice)
            ? array_map([$this, 'arrayPair'], array_keys($slice), $slice)
            : array_map([$this, 'arrayValue'], $slice);

        return vsprintf('[%s%s]', [
            implode(', ', $elems),
            count($value) > $this->arrlim ? ', ...' : '',
        ]);
    }

    /**
     * Return a formatted string for the given key => value pair.
     *
     * @param int|string    $key
     * @param mixed         $val
     * @return string
     */
    private function arrayPair($key, $val): string
    {
        $key_str = is_int($key) ? $key : $this->quoted($key);

        $val_str = $this->arrayValue($val);

        return sprintf('%s => %s', $key_str, $val_str);
    }

    /**
     * Return a formatted strinf for the given array value.
     *
     * @param mixed $val
     * @return string
     */
    private function arrayValue($val): string
    {
        return ! is_array($val)
            ? (string) new Printable($val, $this->callable, $this->strlim)
            : '[...]';
    }

    /**
     * Return a formatted string from the given object.
     *
     * @param object $value
     * @return string
     */
    private function object($value): string
    {
        $class = $this->classname($value);

        if ($class == \Closure::class) {
            return 'function {closure}()';
        }

        return ($this->callable && is_callable($value))
            ? sprintf('function %s::__invoke()', $class)
            : sprintf('Object(%s)', $class);
    }

    /**
     * Return a formatted string from the given resource.
     *
     * @param resource $value
     * @return string
     */
    private function resource($value): string
    {
        return (string) $value;
    }

    /**
     * Return a quoted string.
     *
     * @param string $value
     * @return string
     */
    private function quoted(string $value): string
    {
        return sprintf('\'%s\'', $value);
    }

    /**
     * Return the classname of the given object.
     *
     * @param object $value
     * @return string
     */
    private function classname($value): string
    {
        $class = get_class($value);

        return preg_match('/^class@anonymous/', $class)
            ? 'class@anonymous'
            : $class;
    }

    /**
     * Return whether the given array is associative.
     *
     * @param array $value
     * @return bool
     */
    private function isAssociative(array $value): bool
    {
        return count(array_filter(array_keys($value), 'is_string')) > 0;
    }
}


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

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

class InitOneBlockCommandHandler {

    private $imageLogicAgent;

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

    /**
     * Handle the command.
     *
     * @param  Command  $command
     * @return void
     */
    public function handle(Command $command)
    {
        $this->initBlocks($command->block_name);
    }

    //Создание структуры блоков лэндинга из конфига
    public function initBlocks($block_name='')
    {
        if($block_name==''){
            //Создаем поля по структуре
            $qstorage = config('qstorage');
        }else{
            $qstorage = [$block_name=>config('qstorage')[$block_name]];
        }

        foreach($qstorage as $blockname => $blockstruct)
        {
            $newBlock = Block::find($blockname);

            if(!$newBlock)
            {

                $newBlock = new Block();
                $newBlock->name = $blockname;

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

                if(array_key_exists('stringfields', $blockstruct))
                {
                    foreach($blockstruct['stringfields'] as $fieldname)
                    {
                        $stringfield = Stringfield::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('textfields', $blockstruct))
                {
                    foreach($blockstruct['textfields'] as $fieldname)
                    {
                        $textfield = Textfield::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('numbs', $blockstruct))
                {
                    foreach($blockstruct['numbs'] as $fieldname)
                    {
                        $numb = Numb::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('bools', $blockstruct))
                {
                    foreach($blockstruct['bools'] as $fieldname)
                    {
                        $boolitem = Bool::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('pdatetimes', $blockstruct))
                {
                    foreach($blockstruct['pdatetimes'] as $fieldname)
                    {
                        $dtitem = Pdatetime::firstOrCreate(['block_name'=>$blockname, 'name'=>$fieldname]);
                    }
                }

                if(array_key_exists('images', $blockstruct))
                {
                    foreach($blockstruct['images'] as $fieldname)
                    {
                        $image_name = $blockname.'_'.$fieldname;

                        $image = Imageitem::firstOrNew(['block_name'=>$blockname, 'name'=>$fieldname]);

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

                        $image->save();
                    }
                }

                $newBlock->save();

//                //Создание элементов групп с фиксированным количеством (только для 1-го уровня),
//                //для элементов вложенных групп та же процедура будет проделана при создании элемента - владельца.
//                foreach($blockstruct['groups'] as $groupstruct)
//                {
//                    if(array_key_exists('fixed', $groupstruct) && !array_key_exists('owner', $groupstruct))
//                    {
//                        $fixed = $groupstruct['fixed'];
//
//                        for ($count=0; $count<$fixed; $count++)
//                        {
//                            //Создание элемента группы
//
//
//
//                        }
//                    }
//                }

            }
        }
    }

}


<?php
/**
 * Created by PhpStorm.
 * User: antoine
 * Date: 2017-11-01
 * Time: 15:49
 */

namespace InteractiveSolutions\Bernard\Events;

use Bernard\BernardEvents;
use Bernard\Event\EnvelopeEvent;
use Bernard\Event\RejectEnvelopeEvent;
use InteractiveSolutions\Bernard\Message\AbstractExplicitMessage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class NewrelicBackgroundTransaction implements EventSubscriberInterface
{
    public function begin(EnvelopeEvent $event)
    {
        if (!function_exists('newrelic_start_transaction')) {
            return;
        }

        newrelic_start_transaction(ini_get('newrelic.appname'));
        newrelic_background_job(true);
        newrelic_name_transaction($event->getEnvelope()->getName());
    }

    /**
     * This is called after a transaction has "successfully" finished
     */
    public function acknowledge()
    {
        if (!function_exists('newrelic_end_transaction')) {
            return;
        }

        newrelic_end_transaction();
    }

    /**
     * Reject is called when a task throws an exception
     *
     * @param RejectEnvelopeEvent $event
     */
    public function reject(RejectEnvelopeEvent $event)
    {
        if (!function_exists('newrelic_end_transaction')) {
            return;
        }

        newrelic_notice_error($event->getEnvelope()->getName(), $event->getException());
        newrelic_end_transaction();
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            BernardEvents::INVOKE      => ['begin'],
            BernardEvents::ACKNOWLEDGE => ['acknowledge'],
            BernardEvents::REJECT      => ['reject'],
        ];
    }
}


<?php

namespace Askedio\Laravelcp\Providers;

use App;
use Config;
use Lang;
use View;
use Illuminate\Support\ServiceProvider;
use Askedio\Laravelcp\Helpers\NavigationHelper;
use Askedio\Laravelcp\Helpers\HookHelper;
use Askedio\Laravelcp\Helpers\SearchHelper;

class LaravelcpServiceProvider extends ServiceProvider
{
  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register()
  {
    App::register('Askedio\Laravelcp\Providers\RBACServiceProvider');
  }

  /**
   * Register routes, translations, views and publishers.
   *
   * @return void
   */
public function boot(\Illuminate\Routing\Router $router)
  {

    Config::set('auth.model', 'Askedio\Laravelcp\Models\User');
    Config::set('auth.password.email', 'lcp::emails.password');

    $router->middleware('auth', 'Askedio\Laravelcp\Http\Middleware\Authenticate');
    $router->middleware('auth.basic', 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth');
    $router->middleware('guest', 'Askedio\Laravelcp\Http\Middleware\RedirectIfAuthenticated');
    $router->middleware('role', 'Askedio\Laravelcp\Http\Middleware\VerifyRole');
    $router->middleware('permission', 'Askedio\Laravelcp\Http\Middleware\VerifyPermission');

    $loader = \Illuminate\Foundation\AliasLoader::getInstance();
    $loader->alias('Nav', 'Askedio\Laravelcp\Helpers\NavigationHelper');
    $loader->alias('Hook', 'Askedio\Laravelcp\Helpers\HookHelper');
    $loader->alias('Search', 'Askedio\Laravelcp\Helpers\SearchHelper');

    NavigationHelper::Initialize();
    HookHelper::Initialize();
    SearchHelper::Initialize();

    if (! $this->app->routesAreCached()) {
      require realpath(__DIR__.'/../Http/routes.php');
    }

    $this->loadTranslationsFrom(realpath(__DIR__.'/../Resources/Lang'), 'lcp');

    $this->loadViewsFrom(realpath(__DIR__.'/../Resources/Views'), 'lcp');

    NavigationHelper::Add(['nav' => 'main', 'sort' => '0',  'link' => url('/dashboard'), 'title' => trans('lcp::nav.dashboard'), 'icon' => 'fa-dashboard']);

    $this->publishes([
      realpath(__DIR__.'/../Resources/Views') => base_path('resources/views/vendor/askedio/laravelcp'),
    ], 'views');

    $this->publishes([
      realpath(__DIR__.'/../Resources/Assets') => public_path('assets'),
    ], 'public');

    $this->publishes([
      realpath(__DIR__.'/../Resources/Config') => config_path('')
    ], 'config');

    $this->publishes([
      realpath(__DIR__.'/../Database/Migrations') => database_path('migrations')
    ], 'migrations');

    $this->publishes([
      realpath(__DIR__.'/../Database/Seeds') => database_path('seeds')
    ], 'seeds');

  }
}


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

namespace Openbizx\Easy;

use Openbizx\Openbizx;
use Openbizx\Core\Expression;
use Openbizx\Helpers\TemplateHelper;

/**
 * ViewRenderer class is view helper for rendering form
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2011
 * @access public
 */
class ViewRenderer
{

    /**
     * Render view object
     *
     * @param WebPage $webpage
     * @return string result of rendering process
     */
    static public function render($webpage)
    {
        $tplEngine = $webpage->templateEngine;
        $tplAttributes = ViewRenderer::buildTemplateAttributes($webpage);

        ob_start();

        if ($tplEngine == "Smarty" || $tplEngine == null) {
            ViewRenderer::renderSmarty($webpage, $tplAttributes);
        } else {
            ViewRenderer::renderPHP($webpage, $tplAttributes);
        }

        $html = ob_get_contents();
        ob_end_clean();

        if (defined("OPENBIZ_PAGE_MINIFY") && OPENBIZ_PAGE_MINIFY == 1) {
            $html = self::MinifyOutput($html);
        }
        return $html;
    }

    /**
     *
     * Minify the HTML code and rewrite the code for
     * including CSS and JS files to make it redirect to /bin/min/index.php?f
     * @param string $html
     * @return string $html
     */
    static public function MinifyOutput($html)
    {

        $minifyURL = OPENBIZ_APP_URL . "/bin/min/index.php";
        $headEnd = "</head>";

        //fetch js requests
        preg_match_all("/\<script.*?src\s?\=\s?[\"|\'](.*?\.js)[\"|\']/i", $html, $matches);
        $jsListStr = implode(array_unique($matches[1]), ',');
        $jsURL = $minifyURL . '?f=' . $jsListStr;
        $jsCode = "<script type=\"text/javascript\" src=\"$jsURL\"></script>";

        //remove old js include
        $html = preg_replace("/\<script.*?src\s?\=\s?[\"|\'].*?\.js[\"|\'].*?\<\/script\>/i", "", $html);

        //add new js include
        $html = str_replace($headEnd, $jsCode . "\n" . $headEnd, $html);

        preg_match_all("/\<link.*?href\s?\=\s?\"(.*?\.css)\"/i", $html, $matches);
        $cssListStr = implode(array_unique($matches[1]), ',');
        $cssURL = $minifyURL . '?f=' . $cssListStr;
        $cssCode = "<link rel=\"stylesheet\" href=\"$cssURL\" type=\"text/css\">";

        $html = preg_replace("/\<link.*?href\s?\=\s?\"(.*?\.css)\".*?\>/i", "", $html);
        $html = str_replace($headEnd, $cssCode . "\n" . $headEnd, $html);

        require_once OPENBIZ_APP_PATH . '/bin/min/lib/Minify/HTML.php';
        $html = Minify_HTML::minify($html);
        return $html;
    }

    /**
     * Gather all template variables needed. Should play well with Smarty or \Zend templates
     *
     * @param WebPage $webPage
     * @return array associative array holding all needed VIEW based template variables
     */
    static public function buildTemplateAttributes($webPage)
    {
        // Assocative Array to hold all Template Values
        // Fill with default viewobj attributes
        //$tplAttributes = $viewObj->outputAttrs();
        //Not sure what this is doing...
        $newClntObjs = '';

        //Fill other direct view variables
        $tplAttributes["module"] = $webPage->getModuleName($webPage->objectName);
        $tplAttributes["description"] = $webPage->objectDescription;
        $tplAttributes["keywords"] = $webPage->keywords;

        if (isset($webPage->tiles)) {
            foreach ($webPage->tiles as $tname => $tile) {
                // renderForms() : BEGIN
                foreach ($tile as $formRef) {
                    if ($formRef->display == false) {
                        continue;
                    }
                    $tiles[$tname][$formRef->objectName] = Openbizx::getObject($formRef->objectName)->render();
                    $tiletabs[$tname][$formRef->objectName] = $formRef->objectDescription;
                }
                // renderForms() : END
            }
        } else {
            // renderForms() : BEGIN
            foreach ($webPage->formRefs as $formRef) {
                if ($formRef->display == false) {
                    continue;
                }
                $forms[$formRef->objectName] = Openbizx::getObject($formRef->objectName)->render();
                $formtabs[$formRef->objectName] = $formRef->objectDescription;
            }
            // renderForms() : END
        }
        if (count($webPage->widgets)) {
            // renderForms() : BEGIN
            foreach ($webPage->widgets as $formRef) {
                if ($formRef->display == false) {
                    continue;
                }
                $widgets[$formRef->objectName] = Openbizx::getObject($formRef->objectName)->render();
            }
        }
        //Fill Loop related data
        $tplAttributes["forms"] = $forms;
        $tplAttributes["widgets"] = $widgets;
        $tplAttributes["formtabs"] = $formtabs;
        $tplAttributes["tiles"] = $tiles;
        $tplAttributes["tiletabs"] = $tiletabs;

        // add clientProxy scripts
        $includedScripts = Openbizx::$app->getClientProxy()->getAppendedScripts();
        $tplAttributes["style_sheets"] = Openbizx::$app->getClientProxy()->getAppendedStyles();

        if ($webPage->isPopup && $bReRender == false) {
            $moveToCenter = "moveToCenter(self, " . $webPage->width . ", " . $webPage->height . ");";
            $tplAttributes["scripts"] = $includedScripts . "\n<script>\n" . $newClntObjs . $moveToCenter . "</script>\n";
        } else {
            $tplAttributes["scripts"] = $includedScripts . "\n<script>\n" . $newClntObjs . "</script>\n";
        }
        if ($webPage->title) {
            $tplAttributes["title"] = Expression::evaluateExpression($webPage->title, $webPage);
        } else {
            $tplAttributes["title"] = $webPage->objectDescription;
        }
        if (OPENBIZ_DEFAULT_SYSTEM_NAME) {
            $tplAttributes["title"] = $tplAttributes["title"] . ' - ' . OPENBIZ_DEFAULT_SYSTEM_NAME;
        }
        return $tplAttributes;
    }

    /**
     * Render smarty template for view object
     *
     * @param WebPage $webpage
     * @param string $tplFile
     * @return string result of rendering process
     */
    static protected function renderSmarty($webpage, $tplAttributes = Array())
    {
        $smarty = TemplateHelper::getSmartyTemplate();

        $viewOutput = $webpage->outputAttrs();
        foreach ($viewOutput as $k => $v) {
            $smarty->assign($k, $v);
        }
        // render the formobj attributes
        $smarty->assign("view", $viewOutput);

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            $smarty->assign($key, $value);
        }

        self::registerSmartyPlugin($smarty);

        //if ($webpage->consoleOutput) {
            $smarty->display(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
        //} else {
        //    return $smarty->fetch(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
        //}
    }

    public static function registerSmartyPlugin($smarty)
    {

    }

    public static function blockTranslate($params, $content, $template, &$repeat)
    {

    }

    /**
     * Render PHP template for view object
     *
     * @param EasyForm $formObj
     * @param string $tplFile
     * @return string result of rendering process
     */
    static protected function renderPHP($viewObj, $tplAttributes = Array())
    {
        $view = TemplateHelper::getZendTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($viewObj->templateFile, $viewObj->package);
        $view->addScriptPath(dirname($tplFile));

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            if ($value == NULL) {
                $view->$key = '';
            } else {
                $view->$key = $value;
            }
        }
        if ($viewObj->consoleOutput) {
            echo $view->render($viewObj->templateFile);
        } else {
            return $view->render($viewObj->templateFile);
        }
    }

    /**
     * Set headers of view
     *
     * @param WebPage $viewObj
     * @return void
     */
    static protected function setHeaders($viewObj)
    {
        // get the cache attribute
        // if cache = browser, set the cache control in headers
        header('Pragma:', true);
        header('Cache-Control: max-age=3600', true);
        $offset = 60 * 60 * 24 * - 1;
        $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        header($ExpStr, true);
    }

}

?>


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

namespace Openbizx\Easy\Element;

use Openbizx\Openbizx;

/**
 * InputText class is element for input text
 *
 * @package openbiz.bin.easy.element
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @access public
 */
class ColumnInputText extends InputElement
{
	protected function readMetaData(&$xmlArr){
		parent::readMetaData($xmlArr);
		$this->cssClass = isset($xmlArr["ATTRIBUTES"]["CSSCLASS"]) ? $xmlArr["ATTRIBUTES"]["CSSCLASS"] : "column_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";
	}

	public function getItemValue($id)
	{
		$valueArr = $this->value;
		return $valueArr[$id];
	}

	public function setValue($value)
	{
		Openbizx::$app->getSessionContext()->loadObjVar($this->getFormObj()->objectName, $this->objectName, $this->value);
		$valueArr = $_POST[$this->objectName];
		if(is_array($valueArr))
		{
			foreach($valueArr as $key=>$value)
			{
				$this->value[$key] = $value;
			}
		}
		Openbizx::$app->getSessionContext()->saveObjVar($this->getFormObj()->objectName, $this->objectName, $this->value);
	}

	public function renderLabel()
    {
        if ($this->sortable == "Y")
        {
            $rule = $this->objectName;

            $function = $this->formName . ".SortRecord($rule,$this->sortFlag)";
            if($this->sortFlag == "ASC" || $this->sortFlag == "DESC"){
            	$class=" class=\"current\" ";
            }else{
            	$class=" class=\"normal\" ";
            }
            if ($this->sortFlag == "ASC")
            	$span_class = " class=\"sort_up\" ";
            else if ($this->sortFlag == "DESC")
                $span_class = " class=\"sort_down\" ";
            $sHTML = "" . $this->label ."";
            $sHTML .= "";
        }
        else
        {
            $sHTML = $this->label;
        }
        return $sHTML;
    }

    /**
     * Render, draw the control according to the mode
     *
     * @return string HTML text
     */
    public function render()
    {
    	$rec = $this->getFormObj()->getActiveRecord();
		$recId = $rec["Id"];

    	if($this->value!=null){
    		$value = $this->getItemValue($recId);
    	}else{
    		$value = $this->getText();
    	}

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

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

        $sHTML = "<INPUT NAME=\"" . $this->objectName . "[".$recId."]\" ID=\"" . $this->objectName ."\" VALUE=\"" . $value . "\" $disabledStr $this->htmlAttr $style $func />";
        if($this->hint){
        	$sHTML.="";
        }
        return $sHTML;
    }

}

?>


<?php

/*
 * This file is part of the Kreta package.
 *
 * (c) Beñat Espiña <benatespina@gmail.com>
 * (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Kreta\Component\Comment\Factory;

use Kreta\Component\Issue\Model\Interfaces\IssueInterface;
use Kreta\Component\User\Model\Interfaces\UserInterface;

/**
 * Class CommentFactory.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 */
class CommentFactory
{
    /**
     * The class name.
     *
     * @var string
     */
    protected $className;

    /**
     * Constructor.
     *
     * @param string $className The class name
     */
    public function __construct($className)
    {
        $this->className = $className;
    }

    /**
     * Creates an instance of comment.
     *
     * @param \Kreta\Component\Issue\Model\Interfaces\IssueInterface $issue The issue
     * @param \Kreta\Component\User\Model\Interfaces\UserInterface   $user  The user
     *
     * @return \Kreta\Component\Comment\Model\Interfaces\CommentInterface
     */
    public function create(IssueInterface $issue, UserInterface $user)
    {
        $comment = new $this->className();

        return $comment
            ->setIssue($issue)
            ->setWrittenBy($user);
    }
}


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

Copyright 2017, Egbert van der Wal

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

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

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

namespace Wedeto\Resolve;

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

class Router extends SubResolver
{
    /** The root route node */
    protected $root = null;

    /** The search path root is based on */
    protected $root_search_path = null;

    public function __construct(string $name = "router")
    {
        parent::__construct($name);
    }

    /**
     * Resolve an controller / route.
     * @param string $request string The incoming request
     *
     * @return array An array containing:
     *               'path' => The file that best matches the route
     *               'route' => The part of the request that matches
     *               'module' => The source module for the controller
     *               'remainder' => Arguments object with the unmatched part of the request
     */
    public function resolve(string $request)
    {
        $parts = array_filter(explode("/", $request));

        // Determine the file extension
        $last_part = end($parts);
        $dpos = strrpos($last_part, '.');
        if (!empty($dpos)) // If a dot exists after the first character
            $ext = substr($last_part, $dpos);
        else
            $ext = "";

        $root = $this->getRoutes();

        $route = $root->resolve($parts, $ext);

        if (!empty($route) && !file_exists($route['path']) && !$this->authorative)
        {
            // A non-existing file was found in the cache - flush the cache and
            // try again.
            $this->clearCache();
            $root = $this->getRoutes();
            $route = $root->resolve($parts, $ext);
        }

        if ($route === null)
            self::$logger->info("Failed to resolve route for request to {0}", [$request]);
        else
            self::$logger->debug("Resolved route for {route} to {path} (module: {module})", $route);

        return $route;
    }

    /**
     * Find files and directories in a directory. The contents are filtered on
     * .php files and files.
     *
     * @param $dir string The directory to list
     * @param $recursive boolean Whether to also scan subdirectories
     * @return array The contents of the directory.
     */
    public static function listDir(string $dir, bool $recursive = true)
    {
        $contents = array();
        $subdirs = array();
        $reader = dir($dir);
        while ($entry = $reader->read())
        {
            if ($entry === "." || $entry === "..")
                continue;

            $entry = $dir . DIRECTORY_SEPARATOR . $entry;
            if (substr($entry, -4) === ".php")
            {
                $contents[] = $entry;
            }
            elseif (is_dir($entry) && $recursive)
            {
                $subdirs = array_merge($subdirs, self::listDir($entry));
            }
        }

        // Sort the direct contents of the directory so that index.php comes first
        usort($contents, function ($a, $b) {
            $sla = strlen($a);
            $slb = strlen($b);

            // index files come first
            $a_idx = substr($a, -10) === "/index.php";
            $b_idx = substr($b, -10) === "/index.php";
            if ($a_idx !== $b_idx)
                return $a_idx ? -1 : 1;

            // sort the rest alphabetically
            return strcasecmp($a, $b);
        });

        // Add the contents of subdirectories to the direct contents
        return array_merge($contents, $subdirs);
    }

    /**
     * Sort the modules, check if anything has changed
     */
    protected function sortModules()
    {
        parent::sortModules();

        if ($this->root !== null && $this->root_search_path !== $this->search_path)
        {
            $this->root = null;
            $this->root_search_path = null;
        }
    }

    /**
     * Get all routes available from all modules. If the routes have already been
     * determined, they will be used. Clear the cache to redo this.
     *
     * @return array The available routes and the associated controller
     */
    public function getRoutes()
    {
        if (!$this->sorted)
            $this->sortModules();

        $cache = $this->getCachedData();

        if ($cache !== null && $this->root === null)
        {
            $root = $cache->get('data');
            if ($root instanceof Route)
            {
                $this->root = $root;
                $this->root_search_path = $cache->get('search_path');
            }
        }

        if ($this->root !== null)
            return $this->root;

        $this->root = new Route('/', 0);
        $this->root_search_path = $this->search_path;
        foreach ($this->search_path as $module => $info)
        {
            $app_path = $info['path'];
            $files = self::listDir($app_path);
            foreach ($files as $path)
            {
                $file = str_replace($app_path, "", $path);
                $parts = array_filter(explode("/", $file));
                $ptr = $this->root;

                $cnt = 0;
                $l = count($parts);
                foreach ($parts as $part)
                {
                    $last = $cnt === $l - 1;
                    if ($last)
                    {
                        if ($part === "index.php")
                        {
                            // Only store if empty -
                            $ptr->addApp($path, '', $module);
                        }
                        else
                        {
                            $app_name = substr($part, 0, -4);

                            // Strip file extension
                            $ext = "";
                            $ext_pos = strrpos($app_name, '.');
                            if (!empty($ext_pos))
                            {
                                $ext = substr($app_name, $ext_pos);
                                $app_name = substr($app_name, 0, $ext_pos);
                            }

                            $app = $ptr->getSubRoute($app_name);
                            $app->addApp($path, $ext, $module);
                        }
                        break;
                    }

                    // Move the pointer deeper
                    $ptr = $ptr->getSubRoute($part);
                    ++$cnt;
                }
            }
        }

        if ($cache !== null)
            $cache->set('data', $this->root);

        return $this->root;
    }

    /**
     * Clear the cached resolved files
     * @return Router Provides fluent interface
     */
    public function clearCache()
    {
        parent::clearCache();
        $this->root = null;
    }
}


<?PHP

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

namespace Openbizx\Easy;

use Openbizx\Object\MetaObject;

/**
 * HTMLMenus class is the base class of HTML menus
 *
 * @package openbiz.bin.easy
 * @author Rocky Swen
 * @copyright Copyright (c) 2005-2009
 * @since 1.2
 * @access public
 */
class HTMLMenus extends MetaObject implements UIControlInterface
{

    protected $menuItemsXml = null;

    /**
     * Initialize HTMLMenus with xml array
     *
     * @param array $xmlArr
     * @return void
     */
    function __construct(&$xmlArr)
    {
        $this->readMetadata($xmlArr);
        Openbizx::$app->getClientProxy()->appendStyles("menu", "menu.css");
        Openbizx::$app->getClientProxy()->appendScripts("menu-ie-js", '', false);
    }

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

    /**
     * Render the html menu
     *
     * @return string html content of the menu
     */
    public function render()
    {
        // list all views and highlight the current view
        $sHTML = "
\n";
        $sHTML .= $this->renderMenuItems($this->menuItemsXml);
        $sHTML .= "
";
        return $sHTML;
    }

    /**
     * Render menu items
     *
     * @param array $menuItemArray menu item array
     * @return string html content of the menu items
     */
    protected function renderMenuItems(&$menuItemArray)
    {
        $sHTML = "";
        if (isset($menuItemArray["ATTRIBUTES"])) {
            $sHTML .= $this->renderSingleMenuItem($menuItemArray);
        } else {
            foreach ($menuItemArray as $menuItem) {
                $sHTML .= $this->renderSingleMenuItem($menuItem);
            }
        }
        return $sHTML;
    }

    /**
     * Render single menu item
     *
     * @param array $menuItem menu item metadata xml array
     * @return string html content of each menu item
     */
    protected function renderSingleMenuItem(&$menuItem)
    {
        $profile = Openbizx::$app->getUserProfile();
        $svcobj = Openbizx::getService(ACCESS_SERVICE);
        $role = isset($profile["ROLE"]) ? $profile["ROLE"] : null;

        if ( isset($menuItem["ATTRIBUTES"]['URL']) ) {
            $url = $menuItem["ATTRIBUTES"]["URL"];
        } elseif ( isset($menuItem["ATTRIBUTES"]['VIEW']) ) {
            $view = $menuItem["ATTRIBUTES"]["VIEW"];
            // menuitem's containing VIEW attribute is renderd if access is granted in accessservice.xml
            // menuitem's are rendered if no definition is found in accessservice.xml (default)
            if ($svcobj->allowViewAccess($view, $role)) {
                $url = "javascript:GoToView('" . $view . "')";
            } else {
                return '';
            }
        }

        $caption = $this->translate($menuItem["ATTRIBUTES"]["CAPTION"]);
        $target = $menuItem["ATTRIBUTES"]["TARGET"];
        $icon = $menuItem["ATTRIBUTES"]["ICON"];
        $img = $icon ? "getImageUrl() . "/$icon' class=menu_img> " : "";

        if ($view)
            $url = "javascript:GoToView('" . $view . "')";

        if ($target)
            $sHTML .= "
$img" . $caption . "";
        else
            $sHTML .= "
$img" . $caption . "";
        if ($menuItem["MENUITEM"]) {
            $sHTML .= "\n
\n";
            $sHTML .= $this->renderMenuItems($menuItem["MENUITEM"]);
            $sHTML .= "
";
        }
        $sHTML .= "
\n";

        return $sHTML;
    }

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

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

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

}

?>


<?php

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

namespace Openbizx\Service;

use Openbizx\Openbizx;
/**
 * queryService class is the plug-in service of fetching query results
 *
 * @package   openbiz.bin.service
 * @author    Rocky Swen
 * @copyright Copyright (c) 2003-2009, Rocky Swen
 * @access    public
 */
class queryService
{

    /**
     * Initialize queryService
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Fetch all data from specified data object
     *
     * @param string $doName data object name
     * @param string $searchRule rule of serach
     * @return array array of records
     */
    public function fetchAll($doName, $searchRule)
    {
        $do = Openbizx::getObject($doName);
        if (!$do) {
            throw new Exception("System cannot get object of $doName.");
        }
        return $do->directFetch($searchRule);
    }

    /**
     * Fetch record
     *
     * @param string $doName data object name
     * @param string $searchRule rule of search
     * @return mixed
     */
    public function fetchRecord($doName, $searchRule)
    {
        $do = Openbizx::getObject($doName);
        if (!$do) {
            throw new Exception("System cannot get object of $doName.");
            return;
        }
        $r = $do->directFetch($searchRule, 1);
        if (count($r) > 0)
            return $r[0];
        return null;
    }

    /**
     * Fetch field
     *
     * @param string $doName data object name
     * @param string $searchRule search rule
     * @param string $fieldName field name
     * @return mixed
     */
    public function fetchField($doName, $searchRule, $fieldName)
    {
        $rec = $this->fetchRecord($doName, $searchRule);
        if ($rec)
            return $rec[$fieldName];
        return null;
    }

}

?>