<?php
/**
 * Something between Atom and Sand
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2017 Vitex@hippy.cz (G)
 */

namespace Ease;

/**
 * Description of Molecule
 *
 * @author vitex
 */
class Molecule extends Atom
{

    /**
     * Here Live Shared Object
     *
     * @var Shared
     */
    public $easeShared = null;

    /**
     * Molecule Can Log and Use Shared
     */
    public function __construct()
    {
        $this->easeShared = Shared::singleton();
        $this->logger     = $this->easeShared->logger();

        $this->setObjectName();
    }

    /**
     * Nastaví jméno objektu.
     *
     * @param string $objectName
     *
     * @return string Jméno objektu
     */
    public function setObjectName($objectName = null)
    {
        if (empty($objectName)) {
            $this->objectName = get_class($this);
        } else {
            $this->objectName = $objectName;
        }

        return $this->objectName;
    }

    /**
     * Vrací jméno objektu.
     *
     * @return string
     */
    public function getObjectName()
    {
        return $this->objectName;
    }

    /**
     * Set up one of properties
     *
     * @param array  $options  array of given properties
     * @param string $name     name of property to process
     * @param string $constant load default property value from constant
     */
    public function setupProperty($options, $name, $constant = null)
    {
        if (isset($options[$name])) {
            $this->$name = $options[$name];
        } else {
            if (is_null($this->$name) && !empty($constant) && defined($constant)) {
                $this->$name = constant($constant);
            }
        }
    }

    /**
     * Zapíše zprávu do logu.
     *
     * @param string $message zpráva
     * @param string $type    typ zprávy (info|warning|success|error|*)
     *
     * @return bool byl report zapsán ?
     */
    public function addToLog($message, $type = 'message')
    {
        $logged = false;
        if (isset($this->logger) && is_object($this->logger)) {
            $this->logger->addToLog($this->getObjectName(), $message, $type);
        } else {
            $logged = Shared::logger()->addToLog($this->getObjectName(),
                $message, $type);
        }

        return $logged;
    }

    /**
     * Přidá zprávu do sdíleného zásobníku pro zobrazení uživateli.
     *
     * @param string $message  Text zprávy
     * @param string $type     Fronta zpráv (warning|info|error|success)
     *
     * @return
     */
    public function addStatusMessage($message, $type = 'info')
    {
        return $this->easeShared->takeMessage(new Logger\Message($message,
                    $type, get_class($this)));
    }

    /**
     * Obtain Status Messages
     *
     * @param bool $clean Remove messages from strack ?
     *
     * @return array
     */
    public function getStatusMessages($clean = false)
    {
        $messages = $this->easeShared->getStatusMessages();
        if ($clean) {
            $this->easeShared->cleanMessages();
        }
        return $messages;
    }

    /**
     * Pro serializaci připraví vše.
     *
     * @return array
     */
    public function __sleep()
    {
        $objectVarsRaw = get_object_vars($this);
        $objectVars    = array_combine(array_keys($objectVarsRaw),
            array_keys($objectVarsRaw));
        $parent        = get_parent_class(__CLASS__);
        if (method_exists($parent, '__sleep')) {
            $parentObjectVars = parent::__sleep();
            if (is_array($parentObjectVars)) {
                $objectVars = array_merge($objectVars, $parentObjectVars);
            }
        }
        return $objectVars;
    }

    /**
     * Akce po probuzení ze serializace.
     */
    public function __wakeup()
    {
        $this->setObjectName();
    }
}


<?php
/**
 * Třída pro logování.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2016 Vitex@hippy.cz (G)
 */

namespace Ease\Logger;

/**
 * Log to syslog.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2012 Vitex@hippy.cz (G)
 */
class ToSyslog extends ToStd implements Loggingable
{
    /**
     * Předvolená metoda logování.
     *
     * @var string
     */
    public $logType = 'syslog';

    /**
     * Saves obejct instace (singleton...).
     */
    private static $_instance = null;

    /**
     * Handle to logger.
     *
     * @var resource
     */
    public $logger = null;

    /**
     * Logovací třída.
     *
     * @param string $
     */
    public function __construct($logName = null)
    {
        if (!is_null($logName)) {
            $this->logger = openlog($logName, LOG_NDELAY, LOG_USER);
        }
    }

    /**
     * Pri vytvareni objektu pomoci funkce singleton (ma stejne parametry, jako
     * konstruktor) se bude v ramci behu programu pouzivat pouze jedna jeho
     * instance (ta prvni).
     *
     * @link http://docs.php.net/en/language.oop5.patterns.html Dokumentace a
     * priklad
     */
    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            $class = __CLASS__;
            if (defined('EASE_APPNAME')) {
                self::$_instance = new $class(constant('EASE_APPNAME'));
            } else {
                self::$_instance = new $class('EaseFramework');
            }
        }

        return self::$_instance;
    }

    /**
     * Output logline to syslog/messages by its type
     *
     * @param string $type    message type 'error' or anything else
     * @param string $logLine message to output
     */
    public function output($type, $logLine)
    {
        switch ($type) {
            case 'error':
                syslog(LOG_ERR, $this->finalizeMessage($logLine));
                break;
            default:
                syslog(LOG_INFO, $this->finalizeMessage($logLine));
                break;
        }
    }

    /**
     * Uzavře chybové soubory.
     */
    public function __destruct()
    {
        if ($this->logger) {
            closelog();
        }
    }
}


<?php

namespace Ease\TWB;

class RadioButtonGroup extends \Ease\Container
{
    /**
     * Jméno.
     *
     * @var string
     */
    public $name = null;

    /**
     * Typ.
     *
     * @var bool
     */
    public $inline = false;

    /**
     * Položky k zobrazení.
     *
     * @var array
     */
    public $radios = [];

    /**
     * Předvolená hodnota.
     *
     * @var string
     */
    public $checked = null;

    /**
     * Zobrazí pole radiobuttonů.
     *
     * @param string $name
     * @param array  $radios  pole Hodnota=>Popisek
     * @param string $checked
     * @param bool   $inline
     */
    public function __construct($name, $radios, $checked = null, $inline = false)
    {
        $this->name    = $name;
        $this->checked = $checked;
        $this->inline  = $inline;
        $this->radios  = $radios;
        parent::__construct();
    }

    /**
     * Seskládá pole radiobuttonů.
     */
    public function finalize()
    {
        $class = 'radio';
        if ($this->inline) {
            $class .= '-inline';
        }
        $pos = 1;
        foreach ($this->radios as $value => $caption) {
            if ($value == $this->checked) {
                $checked = 'checked';
            } else {
                $checked = null;
            }
            $tagProperties = ['id' => $this->name.$pos++, 'name' => $this->name,
                $checked,];
            $this->addItem(new \Ease\Html\DivTag(new \Ease\Html\LabelTag(null,
                        [new \Ease\Html\InputRadioTag($this->name, $value,
                            $tagProperties), $caption]), ['class' => $class]));
        }
    }
}


<?php
/**
 * @author    Labs64 <netlicensing@labs64.com>
 * @license   Apache-2.0
 * @link      http://netlicensing.io
 * @copyright 2017 Labs64 NetLicensing
 */

namespace NetLicensing;

/**
 * PHP representation of the Utility Service. See NetLicensingAPI for details:
 * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services
 * @package NetLicensing
 */
class UtilityService
{
    /**
     * Returns all license types. See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services#UtilityServices-LicenseTypeslist
     *
     * determines the vendor on whose behalf the call is performed
     * @param Context $context
     *
     * array of available license types or empty array if nothing found.
     * @return Page
     * @throws \ErrorException
     * @throws RestException
     */
    public static function listLicenseTypes(Context $context)
    {
        $response = NetLicensingService::getInstance()
            ->get($context, Constants::UTILITY_ENDPOINT_PATH . '/' . Constants::UTILITY_ENDPOINT_PATH_LICENSE_TYPES);

        $licenseTypes = [];
        $pageNumber = !empty($response->items->pagenumber) ? $response->items->pagenumber : 0;
        $itemsNumber = !empty($response->items->itemsnumber) ? $response->items->itemsnumber : 0;
        $totalPages = !empty($response->items->totalpages) ? $response->items->totalpages : 0;
        $totalItems = !empty($response->items->totalitems) ? $response->items->totalitems : 0;

        if (!empty($response->items->item)) {
            foreach ($response->items->item as $item) {
                $licenseTypes[] = ItemToArrayConverter::convert($item);
            }
        }

        return new Page($licenseTypes, $pageNumber, $itemsNumber, $totalPages, $totalItems);
    }

    /**
     * Returns all license models. See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services#UtilityServices-LicensingModelslist
     *
     * determines the vendor on whose behalf the call is performed
     * @param Context $context
     *
     * array of available license models or empty array if nothing found.
     * @return Page
     * @throws \ErrorException
     * @throws RestException
     */
    public static function listLicensingModels(Context $context)
    {
        $response = NetLicensingService::getInstance()
            ->get($context, Constants::UTILITY_ENDPOINT_PATH . '/' . Constants::UTILITY_ENDPOINT_PATH_LICENSING_MODELS);

        $licensingModels = [];
        $pageNumber = !empty($response->items->pagenumber) ? $response->items->pagenumber : 0;
        $itemsNumber = !empty($response->items->itemsnumber) ? $response->items->itemsnumber : 0;
        $totalPages = !empty($response->items->totalpages) ? $response->items->totalpages : 0;
        $totalItems = !empty($response->items->totalitems) ? $response->items->totalitems : 0;

        if (!empty($response->items->item)) {
            foreach ($response->items->item as $item) {
                $licensingModels[] = ItemToArrayConverter::convert($item);
            }
        }

        return new Page($licensingModels, $pageNumber, $itemsNumber, $totalPages, $totalItems);
    }

    /**
     * Returns all countries.
     *
     * determines the vendor on whose behalf the call is performed
     * @param Context $context
     *
     * reserved for the future use, must be omitted / set to NULL
     * @param null $filter
     *
     * @return Page
     * @throws RestException
     * @throws \ErrorException
     */
    public static function listCountries(Context $context, $filter = null)
    {
        $queryParams = (!is_null($filter)) ? [Constants::FILTER => $filter] : [];

        $response = NetLicensingService::getInstance()
            ->get($context, Constants::UTILITY_ENDPOINT_PATH . '/' . Constants::UTILITY_ENDPOINT_PATH_COUNTRIES, $queryParams);

        $countries = [];
        $pageNumber = !empty($response->items->pagenumber) ? $response->items->pagenumber : 0;
        $itemsNumber = !empty($response->items->itemsnumber) ? $response->items->itemsnumber : 0;
        $totalPages = !empty($response->items->totalpages) ? $response->items->totalpages : 0;
        $totalItems = !empty($response->items->totalitems) ? $response->items->totalitems : 0;

        if (!empty($response->items->item)) {
            foreach ($response->items->item as $item) {
                $country = ItemToCountryConverter::convert($item);
                $country->exists = true;

                $countries[] = $country;
            }
        }

        return new Page($countries, $pageNumber, $itemsNumber, $totalPages, $totalItems);
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: minhao
 * Date: 2016-02-02
 * Time: 14:37
 */

namespace Oasis\SlimApp\SentinelCommand;

use Oasis\SlimApp\ConsoleApplication;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Console\Application;

class CommandConfiguration implements ConfigurationInterface
{
    /**
     * @var Application
     */
    private $application;

    public function __construct(Application $application)
    {
        $this->application = $application;
    }

    /**
     * Generates the configuration tree builder.
     *
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        $root = $builder->root('daemon-monitor');
        {
            $commands = $root->children()->arrayNode('commands');
            {
                /** @var ArrayNodeDefinition $command */
                $command = $commands->prototype('array');
                {
                    $normalizer = function ($value) {
                        return $this->replaceParameterInValue($value);
                    };

                    $command->children()->scalarNode('name')->isRequired();
                    $command->children()->variableNode('args')->defaultValue([])->beforeNormalization()->always(
                        function ($array) {
                            if (!is_array($array)) {
                                throw new InvalidConfigurationException("args is not an array!");
                            }
                            foreach ($array as &$value) {
                                $value = $this->replaceParameterInValue($value);
                            }

                            return $array;
                        }
                    );
                    $command->children()->scalarNode('parallel')->defaultValue(1)->beforeNormalization()->always(
                        $normalizer
                    );
                    $command->children()->booleanNode('once')->defaultValue(false)->beforeNormalization()->always(
                        $normalizer
                    );
                    $command->children()->booleanNode('alert')->defaultValue(true)->beforeNormalization()->always(
                        $normalizer
                    );
                    $command->children()->integerNode('interval')->defaultValue(0)->beforeNormalization()->always(
                        $normalizer
                    );
                    $command->children()->integerNode('frequency')->defaultValue(0)->beforeNormalization()->always(
                        $normalizer
                    );
                    $command->children()
                            ->booleanNode('frequency_fixed')
                            ->defaultValue(false)
                            ->beforeNormalization()
                            ->always($normalizer);
                }
            }
        }

        return $builder;
    }

    protected function replaceParameterInValue($value)
    {
        if ($this->application instanceof ConsoleApplication
            && is_string($value)
            && preg_match('#(%([^%].*?)%)#', $value, $matches, 0)
        ) {
            $key         = $matches[2];
            $replacement = $this->application->getSlimapp()->getParameter($key);
            if ($replacement === null) {
                throw new \InvalidArgumentException("Cannot get config value $key");
            }
            $value = $replacement;
        }

        return $value;
    }
}


<?php
/**
 * Twitter Bootstrap common class.
 *
 * @author Vitex <vitex@hippy.cz>
 */

namespace Ease\TWB;

class Part extends \Ease\JQuery\Part
{

    /**
     * Vložení náležitostí pro twitter bootstrap.
     */
    public function __construct()
    {
        parent::__construct();
        self::twBootstrapize();
    }

    /**
     * Opatří objekt vším potřebným pro funkci bootstrapu.
     */
    public static function twBootstrapize()
    {
        parent::jQueryze();
        $webPage = \Ease\Shared::webPage();
        $webPage->includeCSS($webPage->bootstrapCSS);
        $webPage->includeCSS($webPage->bootstrapThemeCSS);
        $webPage->includeJavaScript($webPage->bootstrapJavaScript);

        return true;
    }

    /**
     * Vrací ikonu.
     *
     * @link  http://getbootstrap.com/components/#glyphicons Přehled ikon
     *
     * @param string $code       Kód ikony z přehledu
     * @param array  $properties Vlastnosti Tagu
     */
    public static function glyphIcon($code, $properties = [])
    {
        if (is_null($properties)) {
            $properties = ['class' => 'glyphicon glyphicon-'.$code];
        } else {
            if (isset($properties['class'])) {
                $properties['class'] = 'glyphicon glyphicon-'.$code.' '.$properties['class'];
            } else {
                $properties['class'] = 'glyphicon glyphicon-'.$code;
            }
        }

        return new \Ease\Html\Span(null, $properties);
    }
}


<?php

namespace Ease\TWB;

class ListGroup extends \Ease\Html\UlTag
{

    /**
     * Vytvori ListGroup.
     *
     * @link  http://getbootstrap.com/components/#list-group ListGroup
     *
     * @param mixed $ulContents položky seznamu
     * @param array $properties parametry tagu
     */
    public function __construct($ulContents = null, $properties = [])
    {
        parent::__construct($ulContents, $properties);
        $this->addTagClass('list-group');
    }

    /**
     * Every item id added in \Ease\Html\LiTag envelope.
     *
     * @param mixed  $pageItem   obsah vkládaný jako položka výčtu
     * @param string $properties Vlastnosti LI tagu
     *
     * @return mixed
     */
    public function &addItemSmart($pageItem, $properties = [])
    {
        $item = parent::addItemSmart($pageItem, $properties);
        $item->addTagClass('list-group-item');

        return $item;
    }
}


<?php

namespace Ease\Html;

/**
 * Tag Label pro LabeledInput.
 *
 * @author Vítězslav Dvořák <vitex@hippy.cz>
 */
class LabelTag extends PairTag
{
    /**
     * Odkaz na obsah.
     *
     * @var mixed
     */
    public $contents = null;

    /**
     * Show tag label
     *
     * @param string $for        vztažný element
     * @param mixed  $contents   obsah opatřovaný popiskem
     * @param array  $properties vlastnosti tagu
     */
    public function __construct($for, $contents = null, $properties = [])
    {
        $this->setTagProperties(['for' => $for]);
        parent::__construct('label', $properties);
        $this->contents = $this->addItem($contents);
    }

    /**
     * Set object name.
     *
     * @param string $objectName nastavované jméno
     *
     * @return string New object name
     */
    public function setObjectName($objectName = null)
    {
        if (is_null($objectName)) {
            $objectName = get_class($this).'@'.$this->getTagProperty('for');
        }

        return parent::setObjectName($objectName);
    }
}


<?php
/**
 * Class to Log messages to Console.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2016 Vitex@hippy.cz (G)
 */

namespace Ease\Logger;

/**
 * Description of ToConsole
 *
 * @author vitex
 */
class ToConsole extends ToMemory
{
    /**
     * Saves obejct instace (singleton...).
     */
    private static $_instance = null;

    /**
     * Standard Output handle
     * @var resource
     */
    public $stdout = null;

    /**
     * Standard error handle
     * @var resource
     */
    public $stderr = null;

    /**
     * Ansi Codes
     * @var array
     */
    protected static $ANSI_CODES = array(
        "off" => 0,
        "bold" => 1,
        "italic" => 3,
        "underline" => 4,
        "blink" => 5,
        "inverse" => 7,
        "hidden" => 8,
        "black" => 30,
        "red" => 31,
        "green" => 32,
        "yellow" => 33,
        "blue" => 34,
        "magenta" => 35,
        "cyan" => 36,
        "white" => 37,
        "black_bg" => 40,
        "red_bg" => 41,
        "green_bg" => 42,
        "yellow_bg" => 43,
        "blue_bg" => 44,
        "magenta_bg" => 45,
        "cyan_bg" => 46,
        "white_bg" => 47
    );

    /**
     * Log Status messages to console
     */
    public function __construct()
    {
        parent::__construct();
        $this->stdout = fopen('php://stdout', 'w');
        $this->stderr = fopen('php://stderr', 'w');
    }

    /**
     * Set Ansi Color
     *
     * @param string $str
     * @param string $color
     * @return string
     */
    public static function set($str, $color)
    {
        $color_attrs = explode("+", $color);
        $ansi_str    = "";
        foreach ($color_attrs as $attr) {
            $ansi_str .= "\033[".self::$ANSI_CODES[$attr]."m";
        }
        $ansi_str .= $str."\033[".self::$ANSI_CODES["off"]."m";
        return $ansi_str;
    }

    /**
     * Zapise zapravu do logu.
     *
     * @param string $caller  název volajícího objektu
     * @param string $message zpráva
     * @param string $type    typ zprávy (success|info|error|warning|*)
     *
     * @return boolean|null byl report zapsán ?
     */
    public function addToLog($caller, $message, $type = 'message')
    {
        $message = $this->set(' '.Message::getTypeUnicodeSymbol($type).' '.strip_tags($message),
            self::getTypeColor($type));
        $logLine = strftime("%D %T").' `'.$caller.'` '.$message;

        switch ($type) {
            case 'error':
                fputs($this->stderr, $logLine."\n");
                break;
            default:
                fputs($this->stdout, $logLine."\n");
                break;
        }
    }

    /**
     * Get color code for given message
     *
     * @param string $type
     */
    public static function getTypeColor($type)
    {
        switch ($type) {
            case 'mail':                       // Envelope
                $color = 'blue';
                break;
            case 'warning':                    // Vykřičník v trojůhelníku
                $color = 'yellow';
                break;
            case 'error':                      // Lebka
                $color = 'red';
                break;
            case 'debug':                      // Kytička
                $color = 'magenta';
                break;
            case 'success':                    // Kytička
                $color = 'green';
                break;
            default:                           // i v kroužku
                $color = 'white';
                break;
        }
        return $color;
    }

    /**
     * Pri vytvareni objektu pomoci funkce singleton (ma stejne parametry, jako
     * konstruktor) se bude v ramci behu programu pouzivat pouze jedna jeho
     * instance (ta prvni).
     *
     * @link http://docs.php.net/en/language.oop5.patterns.html Dokumentace a
     * priklad
     */
    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            $class           = __CLASS__;
            self::$_instance = new $class();
        }

        return self::$_instance;
    }
}


<?php
/**
 * @author    Labs64 <netlicensing@labs64.com>
 * @license   Apache-2.0
 * @link      http://netlicensing.io
 * @copyright 2017 Labs64 NetLicensing
 */

namespace NetLicensing;

use Curl\Curl;

class NetLicensingService
{
    private static $_instance = null;

    /**
     * @var $curl Curl
     */
    private $curl;

    /**
     * NetLicensingService constructor.
     * @throws \ErrorException
     */
    private function __construct()
    {
        $this->curl = new NetLicensingCurl();
        $this->curl->setHeader('Accept', 'application/json');
        $this->curl->setUserAgent('NetLicensing/PHP ' . PHP_VERSION . ' (https://netlicensing.io)' . '; ' . $_SERVER['HTTP_USER_AGENT']);
    }

    protected function __clone()
    {
    }

    /**
     * @return NetLicensingService|null
     * @throws \ErrorException
     */
    static public function getInstance()
    {
        if (is_null(self::$_instance)) self::$_instance = new self();
        return self::$_instance;
    }

    /**
     * Return curl object
     *
     * @return Curl|NetLicensingCurl
     */
    public function curl()
    {
        return $this->curl;
    }

    /**
     * Return curl info
     *
     * @return object
     */
    public function lastCurlInfo()
    {
        return (object)$this->curl->toArray();
    }

    /**
     * Helper method for performing GET request to NetLicensing API services. Finds and returns first suitable item with
     * type resultType from the response.
     *
     * Context for the NetLicensing API call
     * @param Context $context
     *
     * the REST URL template
     * @param $urlTemplate
     *
     * The REST query parameters values. May be null if there are no parameters.
     * @param array $queryParams
     *
     * @return mixed|null
     * @throws RestException
     */

    public function get(Context $context, $urlTemplate, array $queryParams = [])
    {
        return $this->request($context, 'get', $urlTemplate, $queryParams);
    }

    /**
     * Helper method for performing POST request to NetLicensing API services. Finds and returns first suitable item
     * with type resultType from the response.
     *
     * context for the NetLicensing API call
     * @param Context $context
     *
     * the REST URL template
     * @param $urlTemplate
     *
     * The REST query parameters values. May be null if there are no parameters.
     * @param array $queryParams
     *
     * @return mixed|null
     * @throws RestException
     */
    public function post(Context $context, $urlTemplate, array $queryParams = [])
    {
        return $this->request($context, 'post', $urlTemplate, $queryParams);
    }

    /**
     * Helper method for performing DELETE request to NetLicensing API services.
     *
     * context for the NetLicensing API call
     * @param Context $context
     *
     * the REST URL template
     * @param $urlTemplate
     *
     * The REST query parameters values. May be null if there are no parameters.
     * @param array $queryParams
     *
     * @return mixed|null
     * @throws RestException
     */
    public function delete(Context $context, $urlTemplate, array $queryParams = [])
    {
        return $this->request($context, 'delete', $urlTemplate, $queryParams);
    }

    /**
     * @param Context $context
     * @param $method
     * @param $urlTemplate
     * @param array $queryParams
     * @return array|null
     * @throws RestException
     */
    public function request(Context $context, $method, $urlTemplate, array $queryParams = [])
    {
        $restUrl = $context->getBaseUrl() . preg_replace('#/+#', '/', '/' . $urlTemplate);

        // validate http method
        $this->validateMethod($method);

        // validate context
        $this->validateBaseUrl($context);

        // validate baseUrl +  urlTemplate
        $this->validateRestUrl($restUrl);

        // configure
        $this->configure($context);

        // set vendor
        if ($context->getVendorNumber()) {
            $queryParams[Constants::VENDOR_NUMBER] = $context->getVendorNumber();
        }

        $response = $this->curl->{$method}($restUrl, $queryParams);

        switch ($this->getStatusCode()) {
            case 200:
                return $response;
                break;
            case 204:
                return null;
                break;
            default:
                throw new RestException(sprintf("Unsupported response status code %s: %s",
                    $this->getStatusCode(), $this->getReasonPhrase($response)));
                break;

        }
    }

    /**
     * @param $method
     * @throws RestException
     */
    protected function validateMethod($method)
    {
        if (!in_array(strtolower($method), ['get', 'post', 'delete'])) {
            throw new RestException('Invalid request type:' . $method . ', allowed requests types: GET, POST, DELETE.');
        }
    }

    /**
     * @param Context $context
     * @throws RestException
     */
    protected function validateBaseUrl(Context $context)
    {

        if (!$context->getBaseUrl()) {
            throw new RestException('Base url must be specified');
        }

        if (filter_var($context->getBaseUrl(), FILTER_VALIDATE_URL) === false) {
            throw new RestException('Base url "' . $context->getBaseUrl() . '" is not a valid URL');
        }
    }

    /**
     * @param $restUrl
     * @throws RestException
     */
    protected function validateRestUrl($restUrl)
    {
        if (filter_var($restUrl, FILTER_VALIDATE_URL) === false) {
            throw new RestException('Rest url"' . $restUrl . '" is not a valid URL');
        }
    }

    /**
     * @param Context $context
     * @throws RestException
     */
    private function configure(Context $context)
    {
        if (!$context->getSecurityMode()) {
            throw new RestException('Security mode must be specified');
        }

        switch ($context->getSecurityMode()) {
            case Constants::BASIC_AUTHENTICATION:
                if (!$context->getUsername()) throw new RestException('Missing parameter "username"');
                if (!$context->getPassword()) throw new RestException('Missing parameter "password"');

                $this->curl->setHeader('Authorization', 'Basic ' . base64_encode($context->getUsername() . ":" . $context->getPassword()));
                break;
            case Constants::APIKEY_IDENTIFICATION:
                if (!$context->getApiKey()) throw new RestException('Missing parameter "apiKey"');

                $this->curl->setHeader('Authorization', 'Basic ' . base64_encode("apiKey:" . $context->getApiKey()));
                break;
            case Constants::ANONYMOUS_IDENTIFICATION:
                break;
            default:
                throw new RestException("Unknown security mode");
                break;
        }
    }

    private function getStatusCode()
    {
        return $this->curl->httpStatusCode;
    }

    private function getReasonPhrase($response)
    {
        return !empty($response->infos->info[0]->value)
            ? $response->infos->info[0]->value
            : '';
    }

    /**
     * Handle dynamic static method calls into the method.
     *
     * @param  string $method
     * @param  array $parameters
     * @return mixed
     * @throws \ErrorException
     */
    public static function __callStatic($method, $parameters)
    {
        return (new static)->$method(...$parameters);
    }
}


<?php
/**
 * Zakladni objekt urceny k rodicovstvi pokročilým objektum.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2017 Vitex@hippy.cz (G)
 */

namespace Ease;

/**
 * Zakladni objekt urceny k rodicovstvi vsem pouzivanym objektum.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2012 Vitex@hippy.cz (G)
 */
class Sand extends Molecule
{
    /**
     * Default Language Code.
     *
     * @var string
     */
    public $langCode = null;

    /**
     * Common object data holder.
     *
     * @var array
     */
    public $data = null;

    /**
     * Obsahuje všechna pole souhrně považovaná za identitu. Toto pole je plněno
     * v metodě SaveObjectIdentity {volá se automaticky v EaseSand::__construct()}.
     *
     * @var array
     */
    public $identity = [];

    /**
     * Původní identita sloužící jako záloha k zrekonstruování počátečního stavu objektu.
     *
     * @var array
     */
    public $initialIdenty = [];

    /**
     * Tyto sloupecky jsou uchovavany pri operacich s identitou objektu.
     *
     * @var array
     */
    public $identityColumns = ['ObjectName',
        'keyColumn',
        'myTable',
        'MyIDSColumn',
        'MyRefIDColumn',
        'myCreateColumn',
        'myLastModifiedColumn',];

    /**
     * Key Column for Current Record
     *
     * @var string
     */
    public $keyColumn = 'id';

    /**
     * Synchronizační sloupeček. napr products_ids.
     *
     * @var string
     */
    public $myIDSColumn = null;

    /**
     * Sloupeček obsahující datum vložení záznamu do shopu.
     *
     * @var string
     */
    public $myCreateColumn = null;

    /**
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
     *
     * @var string
     */
    public $myLastModifiedColumn = null;

    /**
     * Objekt pro logování.
     *
     * @var Logger\Regent
     */
    public $logger = null;

    /**
     * Odkaz na vlastnící objekt.
     *
     * @var Sand|mixed object
     */
    public $parentObject = null;

    /**
     * Sdílený objekt frameworku.
     *
     * @var Shared
     */
    public $easeShared = null;

    /**
     * Prapředek všech objektů.
     */
    public function __construct()
    {
        parent::__construct();
        $this->initialIdenty = $this->saveObjectIdentity();
    }

    /**
     * Předá zprávy.
     *
     * @param bool $clean smazat originalni data ?
     *
     * @return array
     */
    public function getStatusMessages($clean = false)
    {
        $messages = array_merge($this->statusMessages,
            $this->logger->statusMessages,
            Shared::logger()->getStatusMessages(),
            Shared::instanced()->getStatusMessages());
        if ($clean) {
            $this->cleanMessages();
        }

        return $messages;
    }

    /**
     * Vymaže zprávy.
     */
    public function cleanMessages()
    {
        parent::cleanMessages();
        $this->logger->cleanMessages();

        return Shared::instanced()->cleanMessages();
    }

    /**
     * Nastaví novou identitu objektu.
     *
     * @param array $newIdentity
     */
    public function setObjectIdentity($newIdentity)
    {
        $changes = 0;
        $this->saveObjectIdentity();
        foreach ($this->identityColumns as $column) {
            if (isset($newIdentity[$column])) {
                $this->$column = $newIdentity[$column];
                ++$changes;
            }
        }

        return $changes;
    }

    /**
     * Uloží identitu objektu do pole $this->identity.
     *
     * @return array pole s identitou
     */
    public function saveObjectIdentity()
    {
        foreach ($this->identityColumns as $column) {
            if (isset($this->$column)) {
                $this->identity[$column] = $this->$column;
            }
        }

        return $this->identity;
    }

    /**
     * Obnoví uloženou identitu objektu.
     *
     * @param array $identity pole s identitou např. array('myTable'=>'user');
     */
    public function restoreObjectIdentity($identity = null)
    {
        if (is_null($identity)) {
            foreach ($this->identityColumns as $column) {
                if (isset($this->identity[$column])) {
                    $this->$column = $this->identity[$column];
                }
            }
        } else {
            foreach ($identity as $column) {
                if (isset($this->identity[$column])) {
                    $this->$column = $this->identity[$column];
                }
            }
        }
    }

    /**
     * Obnoví poslední použitou identitu.
     */
    public function resetObjectIdentity()
    {
        $this->identity = $this->initialIdenty;
        $this->restoreObjectIdentity();
    }

    /**
     * Z datového pole $SourceArray přemístí políčko $ColumName do pole
     * $destinationArray.
     *
     * @param array  $sourceArray      zdrojové pole dat
     * @param array  $destinationArray cílové pole dat
     * @param string $columName        název položky k převzetí
     */
    public static function divDataArray(&$sourceArray, &$destinationArray,
                                        $columName)
    {
        $result = false;
        if (array_key_exists($columName, $sourceArray)) {
            $destinationArray[$columName] = $sourceArray[$columName];
            unset($sourceArray[$columName]);

            $result = true;
        }

        return $result;
    }

    /**
     * Test for associative array.
     *
     * @param array $arr
     *
     * @return bool
     */
    public static function isAssoc(array $arr)
    {
        return array_keys($arr) !== range(0, count($arr) - 1);
    }

    /**
     * Gives you value of KEY Column
     *
     * @param array $data data z nichž se vrací hodnota klíče
     *
     * @return int key column value
     */
    public function getMyKey($data = null)
    {
        $key = null;
        if (is_null($data)) {
            $data = $this->getData();
        }
        if (isset($data) && isset($data[$this->keyColumn])) {
            $key = $data[$this->keyColumn];
        }

        return $key;
    }

    /**
     * Nastavuje hodnotu klíčového políčka pro SQL.
     *
     * @param int|string $myKeyValue
     *
     * @return bool
     */
    public function setMyKey($myKeyValue)
    {
        if (isset($this->keyColumn)) {
            $this->setDataValue($this->keyColumn, $myKeyValue);
            $result = true;
        } else {
            $result = false;
        }

        return $result;
    }

    /**
     * Gives you Current KeyColumn Name
     *
     * @return string
     */
    public function getKeyColumn()
    {
        return $this->keyColumn;
    }

    /**
     * Nastaví jméno klíčového sloupečku v shopu.
     *
     * @param string $keyColumn
     */
    public function setkeyColumn($keyColumn)
    {
        $this->keyColumn = $keyColumn;
    }

    /**
     * Vynuluje všechny pole vlastností objektu.
     */
    public function dataReset()
    {
        $this->data = [];
    }

    /**
     * Načte $data do polí objektu.
     *
     * @param array $data  asociativní pole dat
     * @param bool  $reset vyprazdnit pole před naplněním ?
     *
     * @return int počet načtených položek
     */
    public function setData($data, $reset = false)
    {
        $ret = null;
        if (!empty($data) && is_array($data) && count($data)) {
            if ($reset) {
                $this->dataReset();
            }
            if (is_array($this->data)) {
                $this->data = array_merge($this->data, $data);
            } else {
                $this->data = $data;
            }
            $ret = count($data);
        }

        return $ret;
    }

    /**
     * Vrací celé pole dat objektu.
     *
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Vrací počet položek dat objektu.
     *
     * @return int
     */
    public function getDataCount()
    {
        return count($this->data);
    }

    /**
     * Vrací hodnotu z pole dat pro MySQL.
     *
     * @param string $columnName název hodnoty/sloupečku
     *
     * @return mixed
     */
    public function getDataValue($columnName)
    {
        if (isset($this->data[$columnName])) {
            return $this->data[$columnName];
        }

        return;
    }

    /**
     * Nastaví hodnotu poli objektu.
     *
     * @param string $columnName název datové kolonky
     * @param mixed  $value      hodnota dat
     *
     * @return bool Success
     */
    public function setDataValue($columnName, $value)
    {
        $this->data[$columnName] = $value;

        return true;
    }

    /**
     * Odstrani polozku z pole dat pro MySQL.
     *
     * @param string $columnName název klíče k vymazání
     *
     * @return bool success
     */
    public function unsetDataValue($columnName)
    {
        if (array_key_exists($columnName, $this->data)) {
            unset($this->data[$columnName]);

            return true;
        }

        return false;
    }

    /**
     * Převezme data do aktuálního pole dat.
     *
     * @param array $data asociativní pole dat
     *
     * @return int
     */
    public function takeData($data)
    {
        if (is_array($this->data) && is_array($data)) {
            $this->data = array_merge($this->data, $data);
        } else {
            $this->data = $data;
        }

        return empty($data) ? null : count($data);
    }

    /**
     * Odstraní z textu diakritiku.
     *
     * @param string $text
     */
    public static function rip($text)
    {
        $convertTable = [
            'ä' => 'a',
            'Ä' => 'A',
            'á' => 'a',
            'Á' => 'A',
            'à' => 'a',
            'À' => 'A',
            'ã' => 'a',
            'Ã' => 'A',
            'â' => 'a',
            'Â' => 'A',
            'č' => 'c',
            'Č' => 'C',
            'ć' => 'c',
            'Ć' => 'C',
            'ď' => 'd',
            'Ď' => 'D',
            'ě' => 'e',
            'Ě' => 'E',
            'é' => 'e',
            'É' => 'E',
            'ë' => 'e',
            'Ë' => 'E',
            'è' => 'e',
            'È' => 'E',
            'ê' => 'e',
            'Ê' => 'E',
            'í' => 'i',
            'Í' => 'I',
            'ï' => 'i',
            'Ï' => 'I',
            'ì' => 'i',
            'Ì' => 'I',
            'î' => 'i',
            'Î' => 'I',
            'ľ' => 'l',
            'Ľ' => 'L',
            'ĺ' => 'l',
            'Ĺ' => 'L',
            'ń' => 'n',
            'Ń' => 'N',
            'ň' => 'n',
            'Ň' => 'N',
            'ñ' => 'n',
            'Ñ' => 'N',
            'ó' => 'o',
            'Ó' => 'O',
            'ö' => 'o',
            'Ö' => 'O',
            'ô' => 'o',
            'Ô' => 'O',
            'ò' => 'o',
            'Ò' => 'O',
            'õ' => 'o',
            'Õ' => 'O',
            'ő' => 'o',
            'Ő' => 'O',
            'ř' => 'r',
            'Ř' => 'R',
            'ŕ' => 'r',
            'Ŕ' => 'R',
            'š' => 's',
            'Š' => 'S',
            'ś' => 's',
            'Ś' => 'S',
            'ť' => 't',
            'Ť' => 'T',
            'ú' => 'u',
            'Ú' => 'U',
            'ů' => 'u',
            'Ů' => 'U',
            'ü' => 'u',
            'Ü' => 'U',
            'ù' => 'u',
            'Ù' => 'U',
            'ũ' => 'u',
            'Ũ' => 'U',
            'û' => 'u',
            'Û' => 'U',
            'ý' => 'y',
            'Ý' => 'Y',
            'ž' => 'z',
            'Ž' => 'Z',
            'ź' => 'z',
            'Ź' => 'Z',
        ];

        return @iconv('UTF-8', 'ASCII//TRANSLIT', strtr($text, $convertTable));
    }

    /**
     * Encrypt.
     * Šifrování.
     *
     * @param string $textToEncrypt plaintext
     * @param string $encryptKey    klíč
     *
     * @return string encrypted text
     */
    public static function easeEncrypt($textToEncrypt, $encryptKey)
    {
        $encryption_key = base64_decode($encryptKey);
        $iv             = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted      = openssl_encrypt($textToEncrypt, 'aes-256-cbc',
            $encryption_key, 0, $iv);
        return base64_encode($encrypted.'::'.$iv);
    }

    /**
     * Decrypt
     * Dešifrování.
     *
     * @param string $textToDecrypt šifrovaný text
     * @param string $encryptKey    šifrovací klíč
     *
     * @return string
     */
    public static function easeDecrypt($textToDecrypt, $encryptKey)
    {
        $encryption_key = base64_decode($encryptKey);
        list($encrypted_data, $iv) = explode('::',
            base64_decode($textToDecrypt), 2);
        return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key,
            0, $iv);
    }

    /**
     * Generování náhodného čísla.
     *
     * @param int $minimal
     * @param int $maximal
     *
     * @return float
     */
    public static function randomNumber($minimal = null, $maximal = null)
    {
        mt_srand((float) microtime() * 1000000);
        if (isset($minimal) && isset($maximal)) {
            if ($minimal >= $maximal) {
                $rand = false;
            } else {
                $rand = mt_rand($minimal, $maximal);
            }
        } else {
            $rand = mt_rand();
        }

        return $rand;
    }

    /**
     * Vrací náhodný řetězec dané délky.
     *
     * @param int $length
     *
     * @return string
     */
    public static function randomString($length = 6)
    {
        return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
            0, $length);
    }

    /**
     * Rekurzivně překóduje pole.
     *
     * @param string $in_charset
     * @param string $out_charset
     * @param array  $arr         originální pole
     *
     * @return array překódované pole
     */
    public function recursiveIconv($in_charset, $out_charset, $arr)
    {
        if (!is_array($arr)) {
            return iconv($in_charset, $out_charset, $arr);
        }
        $ret = $arr;
        array_walk_recursive($ret, [$this, 'arrayIconv'],
            [$in_charset, $out_charset]);

        return $ret;
    }

    /**
     * Pomocná funkce pro překódování vícerozměrného pole.
     *
     * @see recursiveIconv
     *
     * @param mixed  $val
     * @param string $key
     * @param mixed  $encodings
     */
    public function arrayIconv(&$val, $key, $encodings)
    {
        $val = iconv($encodings[0], $encodings[1], $val);
    }

    /**
     * Zobrazí velikost souboru v srozumitelném tvaru.
     *
     * @param int $filesize bytů
     *
     * @return string
     */
    public static function humanFilesize($filesize)
    {
        if (is_numeric($filesize)) {
            $decr   = 1024;
            $step   = 0;
            $prefix = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];

            while (($filesize / $decr) > 0.9) {
                $filesize = $filesize / $decr;
                ++$step;
            }

            return round($filesize, 2).' '.$prefix[$step];
        } else {
            return 'NaN';
        }
    }

    /**
     * Reindex Array by given key.
     *
     * @param array  $data    array to reindex
     * @param string $indexBy one of columns in array
     *
     * @return array
     */
    public static function reindexArrayBy($data, $indexBy = null)
    {
        $reindexedData = [];

        foreach ($data as $dataID => $data) {
            if (array_key_exists($indexBy, $data)) {
                $reindexedData[$data[$indexBy]] = $data;
            } else {
                throw new \Exception(sprintf('Data row does not contain column %s for reindexing',
                    $indexBy));
            }
        }

        return $reindexedData;
    }

    /**
     * Filter Only letters from string.
     * Pouze malé a velké písmena.
     *
     * @return string text bez zvláštních znaků
     */
    public static function lettersOnly($text)
    {
        return preg_replace('/[^(a-zA-Z0-9)]*/', '', $text);
    }

    /**
     * Confirm that string is serialized
     *
     * @param string $data
     *
     * @return boolean
     */
    public static function isSerialized($data)
    {
        // if it isn't a string, it isn't serialized
        if (!is_string($data)) return false;
        $data = trim($data);
        if ('N;' == $data) return true;
        if (!preg_match('/^([adObis]):/', $data, $badions)) return false;
        switch ($badions[1]) {
            case 'a' :
            case 'O' :
            case 's' :
                if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
                        return true;
                break;
            case 'b' :
            case 'i' :
            case 'd' :
                if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
                        return true;
                break;
        }
        return false;
    }
}


<?php
/**
 * Object able to contain other object in int.
 * Objekt schopný do sebe pojmou jiné objekty.
 *
 * @author     Vitex <vitex@hippy.cz>
 * @copyright  2009-2014 Vitex@hippy.cz (G)
 */

namespace Ease;

class Container extends Sand
{
    /**
     * Pole objektů a fragmentů k vykreslení.
     * Array of objects and fragments to draw
     *
     * @var array|null
     */
    public $pageParts = [];

    /**
     * Byla jiz stranka vykreslena.
     *
     * @var bool
     */
    public $drawStatus = false;

    /**
     * Is class finalized ?
     * Prošel už objekt finalizací ?
     *
     * @var bool
     */
    private $finalized = false;

    /**
     * Které objekty převzít od přebírajícího objektu.
     *
     * @var array
     */
    public $raiseItems = [];

    /**
     * Odkaz na webstránku.
     *
     * @var Page
     */
    public $webPage = null;

    /**
     * Pointer to last item added
     *
     * @var mixed
     */
    public $lastItem = null;

    /**
     * Kontejner, který může obsahovat vložené objekty, které se vykreslí.
     *
     * @param mixed $initialContent hodnota nebo EaseObjekt s metodou draw()
     */
    public function __construct($initialContent = null)
    {
        parent::__construct();
        if (!empty($initialContent)) {
            $this->addItem($initialContent);
        }
    }

    /**
     * Projde $this->raiseItems (metoda_potomka=>proměnná_rodiče) a pokud v
     * objektu najde metodu potomka, zavolá jí s parametrem
     * $this->proměnná_rodiče.
     *
     * @param object $childObject  vkládaný objekt
     * @param array  $itemsToRaise pole položek k "protlačení"
     */
    public function raise(&$childObject, $itemsToRaise = null)
    {
        if (!$itemsToRaise) {
            $itemsToRaise = $childObject->raiseItems;
        }

        foreach ($itemsToRaise as $method => $property) {
            if (method_exists($childObject, $method)) {
                if (isset($this->$property)) {
                    $childObject->$method($this->$property);
                }
            } else {
                if (isset($this->$property)) {
                    $childObject->$property = &$this->$property;
                }
            }
        }
    }

    /**
     * Vloží další element do objektu.
     *
     * @param mixed  $pageItem     hodnota nebo EaseObjekt s metodou draw()
     * @param mixed  $context      Objekt do nějž jsou prvky/položky vkládány
     * @param string $pageItemName Pod tímto jménem je objekt vkládán do stromu
     *
     * @return pointer Odkaz na vložený objekt
     */
    public static function &addItemCustom($pageItem, $context,
                                          $pageItemName = null)
    {
        $itemPointer = null;
        if (is_object($pageItem)) {
            if (method_exists($pageItem, 'draw')) {
                $duplicity = 1;
                if (is_null($pageItemName) || !strlen($pageItemName)) {
                    $pageItemName = $pageItem->getObjectName();
                }

                while (isset($context->pageParts[$pageItemName])) {
                    $pageItemName = $pageItemName.$duplicity++;
                }

                $context->pageParts[$pageItemName]               = $pageItem;
                $context->pageParts[$pageItemName]->parentObject = &$context;

                if (isset($context->pageParts[$pageItemName]->raiseItems) && is_array($context->pageParts[$pageItemName]->raiseItems)
                    && count($context->pageParts[$pageItemName]->raiseItems)
                ) {
                    $context->raise($context->pageParts[$pageItemName]);
                }
                if (method_exists($context->pageParts[$pageItemName], 'AfterAdd')) {
                    $context->pageParts[$pageItemName]->afterAdd($context);
                }
                $context->lastItem = &$context->pageParts[$pageItemName];
                $itemPointer       = &$context->pageParts[$pageItemName];
            } else {
                throw new Exception('Page Item object without draw() method: '.$pageItem);
            }
        } else {
            if (is_array($pageItem)) {
                $addedItemPointer = $context->addItems($pageItem);
                $itemPointer      = &$addedItemPointer;
            } else {
                if (!is_null($pageItem)) {
                    $context->pageParts[] = $pageItem;
                    $endPointer           = end($context->pageParts);
                    $itemPointer          = &$endPointer;
                }
            }
        }
        Shared::instanced()->registerItem($itemPointer);

        return $itemPointer;
    }

    /**
     * Include next element into current object.
     *
     * @param mixed  $pageItem     value or EaseClass with draw() method
     * @param string $pageItemName Custom 'storing' name
     *
     * @return mixed Pointer to included object
     */
    public function addItem($pageItem, $pageItemName = null)
    {
        return self::addItemCustom($pageItem, $this, $pageItemName);
    }

    /**
     * Vloží jako první element do objektu.
     *
     * @param mixed  $pageItem     hodnota nebo EaseObjekt s metodou draw()
     * @param string $pageItemName Pod tímto jménem je objekt vkládán do stromu
     *
     * @return pointer Odkaz na vložený objekt
     */
    public function &addAsFirst($pageItem, $pageItemName = null)
    {
        if (is_null($pageItemName)) {
            $pageItemName = '1st';
        }
        $swap            = is_array($this->pageParts) ? $this->pageParts : [];
        $this->emptyContents();
        $itemPointer     = $this->addItem($pageItem, $pageItemName);
        $this->pageParts = array_merge( is_array($this->pageParts) ? $this->pageParts : [], $swap);

        return $itemPointer;
    }

    /**
     * Umožní již vloženému objektu se odstranit ze stromu k vykreslení.
     */
    public function suicide()
    {
        if (isset($this->parentObject) && isset($this->parentObject->pageParts[$this->getObjectName()])) {
            unset($this->parentObject->pageParts[$this->getObjectName()]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Vrací počet vložených položek.
     * Obtain number of enclosed items in current or given object.
     *
     * @param Container $object hodnota nebo EaseObjekt s polem ->pageParts
     *
     * @return int nuber of parts enclosed
     */
    public function getItemsCount($object = null)
    {
        $itemCount = 0;
        if (is_null($object) && !empty($this->pageParts)) {
            $itemCount = count($this->pageParts);
        }
        if (is_object($object) && isset($object->pageParts)) {
            $itemCount = count($object->pageParts);
        }

        return $itemCount;
    }

    /**
     * Vloží další element za stávající.
     *
     * @param mixed $pageItem hodnota nebo EaseObjekt s metodou draw()
     *
     * @return pointer Odkaz na vložený objekt
     */
    public function &addNextTo($pageItem)
    {
        $itemPointer = $this->parentObject->addItem($pageItem);

        return $itemPointer;
    }

    /**
     * Vrací odkaz na poslední vloženou položku.
     *
     * @return EaseBrick|mixed
     */
    public function &lastItem()
    {
        $lastPart = end($this->pageParts);

        return $lastPart;
    }

    /**
     * Přidá položku do poslední vložené položky.
     *
     * @param object $pageItem hodnota nebo EaseObjekt s metodou draw()
     *
     * @return bool success
     */
    public function addToLastItem($pageItem)
    {
        return $this->lastItem->addItem($pageItem);
    }

    /**
     * Vrací první vloženou položku.
     *
     * @param Container $pageItem kontext
     */
    public function &getFirstPart($pageItem = null)
    {
        if (!$pageItem) {
            $pageItem = &$this;
        }
        if (!empty($pageItem->pageParts) && is_array($pageItem->pageParts)) {
            $firstPart = reset($pageItem->pageParts);
        } else {
            $firstPart = null;
        }

        return $firstPart;
    }

    /**
     * Insert an array of elemnts
     * Vloží pole elementů.
     *
     * @param array $itemsArray pole hodnot nebo EaseObjektů s metodou draw()
     */
    public function addItems($itemsArray)
    {
        $itemsAdded = [];
        foreach ($itemsArray as $itemID => $item) {
            $itemsAdded[$itemID] = $this->addItem($item);
        }

        return $itemsAdded;
    }

    /**
     * Vyprázní obsah objektu.
     * Empty container contents
     */
    public function emptyContents()
    {
        $this->pageParts = null;
    }

    /**
     * Contentets
     *
     * @return mixed
     */
    public function getContents(){
        return $this->pageParts;
    }

        /**
     * Projde rekurzivně všechny vložené objekty a zavolá jeich draw().
     */
    public function drawAllContents()
    {
        if (count($this->pageParts)) {
            foreach ($this->pageParts as $part) {
                if (is_object($part) && method_exists($part, 'draw')) {
                    $part->draw();
                } else {
                    echo $part;
                }
            }
        }
        $this->drawStatus = true;
    }

    /**
     * Vrací rendrovaný obsah objektů.
     *
     * @return string
     */
    public function getRendered()
    {
        $retVal = '';
        ob_start();
        $this->draw();
        $retVal .= ob_get_contents();
        ob_end_clean();

        return $retVal;
    }

    /**
     * Vykresli se, pokud již tak nebylo učiněno.
     * Draw contents not drawn yet.
     */
    public function drawIfNotDrawn()
    {
        if ($this->drawStatus === false) {
            $this->draw();
        }
    }

    /**
     * Vrací stav návěští finalizace části.
     *
     * @return bool
     */
    public function isFinalized()
    {
        return $this->finalized;
    }

    /**
     * Set label of parts finalized.
     * Nastaví návěstí finalizace části.
     *
     * @param bool $flag příznak finalizace
     */
    public function setFinalized($flag = true)
    {
        $this->finalized = $flag;
    }

    /**
     * Je element prázdný ?
     *
     * @param Container $element Ease Html Element
     *
     * @return bool prázdnost
     */
    public function isEmpty($element = null)
    {
        if (is_null($element)) {
            $element = &$this;
        }

        return !count($element->pageParts);
    }

    /**
     * Recursive draw object and its contents
     */
    public function draw()
    {
        foreach ($this->pageParts as $part) {
            if (is_object($part)) {
                if (method_exists($part, 'drawIfNotDrawn')) {
                    $part->drawIfNotDrawn();
                } else {
                    $part->draw();
                }
            } else {
                echo $part;
            }
        }
        $this->drawStatus = true;
    }

    /**
     * Render Obect (and its contents) as string.
     *
     * @return string
     */
    public function __toString()
    {
        ob_start();
        $this->draw();
        $objectOut = ob_get_contents();
        ob_end_clean();

        return $objectOut;
    }
}


<?php

namespace Ease\TWB;

class Pagination extends \Ease\Html\UlTag
{
    /**
     * Fragment adresy pro stránkování.
     *
     * @var string
     */
    public $url = '?page=';

    /**
     * Stránkování Twitter Bootrstap.
     *
     * @param int    $pages   celkový počet stránek
     * @param int    $current aktuální stránka
     * @param string $url     Fragment adresy
     */
    public function __construct($pages, $current = 0, $url = '?page=')
    {
        $this->url = $url;
        parent::__construct(null, ['class' => 'pagination']);
        if ($current == 0) {
            $this->addPage('#', Part::glyphIcon('fast-backward'), 'disabled');
        } else {
            $this->addPage(0, Part::glyphIcon('fast-backward'));
        }
        if ($current == 0) {
            $this->addPage('#', Part::glyphIcon('chevron-left'), 'disabled');
        } else {
            $this->addPage($current - 1, Part::glyphIcon('chevron-left'));
        }
        for ($page = 0; $page <= $pages - 1; ++$page) {
            //Stavajici
            if ($current == $page) {
                $this->addPage($page, $page + 1, 'active');
            } else {
                $this->addPage($page, $page + 1);
            }
        }
        if ($current >= $pages - 1) {
            $this->addPage('#', Part::glyphIcon('chevron-right'), 'disabled');
        } else {
            $this->addPage($current + 1, Part::glyphIcon('chevron-right'));
        }
        if ($current >= $pages - 1) {
            $this->addPage('#', Part::glyphIcon('fast-forward'), 'disabled');
        } else {
            $this->addPage($pages - 1, Part::glyphIcon('fast-forward'));
        }
    }

    /**
     * Přidá krok strankování.
     *
     * @param int    $page
     * @param string $label
     */
    public function addPage($page, $label = null, $style = null)
    {
        $link = $this->url.$page;
        if ($style) {
            $this->addItemSmart(new \Ease\Html\ATag($link, $label),
                ['class' => $style]);
        } else {
            $this->addItemSmart(new \Ease\Html\ATag($link, $label));
        }
    }
}


<?php
/**
 * Class to Log messages.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2016 Vitex@hippy.cz (G)
 */

namespace Ease\Logger;

class ToMemory extends \Ease\Atom
{
    /**
     * Předvolená metoda logování.
     *
     * @var string
     */
    public $logType = 'memory';

    /**
     * Adresář do kterého se zapisují logy.
     *
     * @var string dirpath
     */
    public $logPrefix = null;

    /**
     * úroveň logování.
     *
     * @var string - silent,debug
     */
    public $logLevel = 'debug';

    /**
     * Hodnoty pro obarvování logu.
     *
     * @var array
     */
    public $logStyles = [
        'notice' => 'color: black;',
        'success' => 'color: #2C5F23;',
        'message' => 'color: #2C5F23;',
        'warning' => 'color: #AB250E;',
        'error' => 'color: red;',
        'debug' => 'font-style: italic;',
        'report' => 'font-wight: bold;',
        'info' => 'color: blue;',
    ];

    /**
     * Odkaz na vlastnící objekt.
     *
     * @var EaseSand ||
     */
    public $parentObject = null;

    /**
     * ID naposledy ulozene zpravy.
     *
     * @var int unsigned
     */
    private $messageID = 0;

    /**
     * Obecné konfigurace frameworku.
     *
     * @var Shared
     */
    public $easeShared = null;

    /**
     * Saves obejct instace (singleton...).
     */
    private static $_instance = null;

    /**
     * Keep log in memory Class.
     */
    public function __construct()
    {
        $this->easeShared = \Ease\Shared::singleton();
    }

    /**
     * Pri vytvareni objektu pomoci funkce singleton (ma stejne parametry, jako
     * konstruktor) se bude v ramci behu programu pouzivat pouze jedna jeho
     * instance (ta prvni).
     *
     * @link http://docs.php.net/en/language.oop5.patterns.html Dokumentace a
     * priklad
     */
    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            $class           = __CLASS__;
            self::$_instance = new $class();
        }

        return self::$_instance;
    }

    /**
     * Zapise zapravu do logu.
     *
     * @param string $caller  název volajícího objektu
     * @param string $message zpráva
     * @param string $type    typ zprávy (success|info|error|warning|*)
     *
     * @return bool byl report zapsán ?
     */
    public function addToLog($caller, $message, $type = 'message')
    {
        ++$this->messageID;
        if ((($type != 'error') && ($this->logLevel == 'silent')) ||
            (($type == 'debug') && ($this->logLevel != 'debug'))) {
            return;
        }

        $this->statusMessages[$type][$this->messageID] = $message;

        $message = htmlspecialchars_decode(strip_tags(stripslashes($message)));

        $logLine = date(DATE_ATOM).' ('.$caller.') '.str_replace(['notice', 'message',
                'debug', 'report', 'error', 'warning', 'success', 'info', 'mail',],
                ['**', '##', '@@', '::'], $type).' '.$message."\n";
        if (!isset($this->logStyles[$type])) {
            $type = 'notice';
        }
        if ($this->logType == 'console' || $this->logType == 'both') {
            if ($this->runType == 'cgi') {
                echo $logLine;
            } else {
                echo '
logStyles[$type].'">'.$logLine."
\n";
                flush();
            }
        }

        return true;
    }

    /**
     * Oznamuje chybovou událost.
     *
     * @param string $caller     název volající funkce, nebo objektu
     * @param string $message    zpráva
     * @param mixed  $objectData data k zaznamenání
     */
    public function error($caller, $message, $objectData = null)
    {
        $this->addToLog($caller, $message, 'error');
    }

    /**
     * Vrací styl logování.
     *
     * @param string $logType typ logu warning|info|success|error|notice|*
     *
     * @return string
     */
    public function getLogStyle($logType = 'notice')
    {
        if (key_exists($logType, $this->logStyles)) {
            return $this->logStyles[$logType];
        } else {
            return '';
        }
    }

    /**
     * Do Nothing.
     */
    public function flush()
    {
        //Hotfix
    }
}