<?php

namespace Ease\Html;

/**
 * HTML webPage head class.
 *
 * @author Vitex <vitex@hippy.cz>
 */
class HeadTag extends PairTag
{
    /**
     * Javascripts to render in page.
     *
     * @var array
     */
    public $javaScripts = null;

    /**
     * Css definitions.
     *
     * @var strig
     */
    public $cascadeStyles = null;

    /**
     * Content Charset
     * Znaková sada obsahu.
     *
     * @var string
     */
    public $charSet = 'utf-8';

    /**
     * Html HEAD tag with basic contents and skin support.
     *
     * @param mixed $content vkládaný obsah
     */
    public function __construct($content = null)
    {
        parent::__construct('head', null, $content);
        $this->addItem('<meta http-equiv="Content-Type" content="text/html; charset='.$this->charSet.'" />');
    }

    /**
     * Change name directly to head.
     *
     * @param string $objectName jméno objektu
     */
    public function setObjectName($objectName = null)
    {
        parent::setObjectName('head');
    }

    /**
     * Vykreslení bloku scriptu.
     *
     * @param string $javaScript vkládaný skript
     *
     * @return string
     */
    public static function jsEnclosure($javaScript)
    {
        return '
<script>
// <![CDATA[
'.$javaScript.'
// ]]>
</script>
';
    }

    /**
     * Vloží do hlavíčky název stránky.
     */
    public function finalize()
    {
        $this->addItem('<title>'.\Ease\Shared::webPage()->pageTitle.'</title>');
    }

    /**
     * Vykreslí hlavičku HTML stránky.
     */
    public function draw()
    {
        if (isset($this->easeShared->cascadeStyles) && count($this->easeShared->cascadeStyles)) {
            $cascadeStyles = [];
            foreach ($this->easeShared->cascadeStyles as $StyleRes => $Style) {
                if ($StyleRes == $Style) {
                    $this->addItem('<link href="'.$Style.'" rel="stylesheet" type="text/css" media="'.'screen'.'" />');
                } else {
                    $cascadeStyles[] = $Style;
                }
            }
            $this->addItem(
                '<style>'.implode(
                    '
', $cascadeStyles
                ).'</style>'
            );
        }
        if (isset($this->easeShared->javaScripts) && count($this->easeShared->javaScripts)) {
            ksort($this->easeShared->javaScripts, SORT_NUMERIC);
            $ODRStack = [];
            foreach ($this->easeShared->javaScripts as $Script) {
                $ScriptType = $Script[0];
                $ScriptBody = substr($Script, 1);
                switch ($ScriptType) {
                    case '#':
                        $this->addItem(
                            '
'.'<script src="'.$ScriptBody.'"></script>'
                        );
                        break;
                    case '@':
                        $this->addItem(self::jsEnclosure($ScriptBody));
                        break;
                    case '$':
                        $ODRStack[] = $ScriptBody;
                        break;
                }
            }
            if (count($ODRStack)) {
                $this->addItem(
                    self::jsEnclosure(
                        '$(document).ready(function () { '.implode(
                            '
', $ODRStack
                        ).' });'
                    )
                );
            }
        }
        parent::draw();
    }
}


<?php

namespace NetLicensing;

use ArrayIterator;
use Countable;
use ArrayAccess;
use JsonSerializable;
use IteratorAggregate;

class Page implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
{
    /**
     * The content of this page
     * @var array
     */
    protected $content;

    /**
     * The number of the current page
     * @var int
     */
    protected $pageNumber;

    /**
     * The number of elements on the page
     * @var int
     */
    protected $itemsNumber;

    /**
     * The number of total pages
     * @var int
     */
    protected $totalPages;

    /**
     * The total amount of elements
     * @var int
     */
    protected $totalItems;

    /**
     * Page constructor.
     *
     * @param array $content
     * @param $pageNumber
     * @param $itemsNumber
     * @param $totalPages
     * @param $totalItems
     * @param $hasNext
     */
    public function __construct(array $content, $pageNumber, $itemsNumber, $totalPages, $totalItems)
    {
        $this->content = $content;
        $this->pageNumber = $pageNumber;
        $this->itemsNumber = $itemsNumber;
        $this->totalPages = $totalPages;
        $this->totalItems = $totalItems;
    }

    /**
     * Get the slice of items being paginated.
     * @return array
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Get the current page.
     *
     * @return int
     */
    public function getPageNumber()
    {
        return $this->pageNumber;
    }

    /**
     * The number of elements on the page.
     *
     * @return int
     */
    public function getItemsNumber()
    {
        return $this->itemsNumber;
    }

    /**
     * The number of total pages.
     *
     * @return int
     */
    public function getTotalPages()
    {
        return $this->totalPages;
    }

    /**
     * The total amount of elements
     *
     * @return int
     */
    public function getTotalItems()
    {
        return $this->totalItems;
    }

    /**
     * Is there a next page exists
     *
     * @return bool
     */
    public function hasNext()
    {
        return ($this->totalPages > $this->pageNumber + 1);
    }

    /**
     * Determine if the given item exists.
     *
     * @param  mixed $key
     * @return bool
     */
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->content);
    }

    /**
     * Get the item at the given offset.
     *
     * @param  mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->content[$key];
    }

    /**
     * Set the item at the given offset.
     *
     * @param  mixed $key
     * @param  mixed $value
     * @return void
     */
    public function offsetSet($key, $value)
    {
        if (is_null($key)) {
            $this->content[] = $value;
        } else {
            $this->content[$key] = $value;
        }
    }

    /**
     * Unset the item at the given key.
     *
     * @param  mixed $key
     * @return void
     */
    public function offsetUnset($key)
    {
        unset($this->content[$key]);
    }

    /**
     * Count the number of items in the collection.
     *
     * @return int
     */
    public function count()
    {
        return count($this->content);
    }

    /**
     * Get an iterator for the items.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->content);
    }

    /**
     * Get the instance as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'content' => $this->getContent(),
            'pageNumber' => $this->getPageNumber(),
            'itemsNumber' => $this->getItemsNumber(),
            'totalPages' => $this->getTotalPages(),
            'totalItems' => $this->getTotalItems(),
            'hasNext' => $this->hasNext(),
        ];
    }

    /**
     * Convert the object into something JSON serializable.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }

    /**
     * Convert the entity to its string representation.
     *
     * @return string
     */
    public function __toString()
    {
        $contentType = 'UNKNOWN';

        if ($this->content) {
            $contentType = get_class($this->content[0]);
        }

        return sprintf('Page %s of %d containing %s instances', $this->getPageNumber(), $this->getTotalPages(), $contentType);
    }
}


<?php
/**
 * Všeobecně sdílený objekt frameworku.
 * Tento objekt je automaticky přez svůj singleton instancován do každého Ease*
 * objektu.
 * Poskytuje kdykoliv přístup k často volaným objektům framworku jako například
 * uživatel, databáze, webstránka nebo logy.
 * Také obsahuje pole obecnych nastavení a funkce pro jeho obluhu.
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2018 Vitex@hippy.cz (G)
 */

namespace Ease;

/**
 * Všeobecně sdílený objekt frameworku.
 * Tento objekt je automaticky přez svůj singleton instancován do každého Ease*
 * objektu.
 * Poskytuje kdykoliv přístup k často volaným objektům framworku jako například
 * uživatel, databáze, webstránka nebo logy.
 * Také obsahuje pole obecnych nastavení a funkce pro jeho obluhu.
 *
 * @copyright 2009-2016 Vitex@hippy.cz (G)
 * @author    Vitex <vitex@hippy.cz>
 */
class Shared extends Atom
{
    /**
     * Odkaz na objekt stránky.
     *
     * @var WebPage
     */
    public $webPage = null;

    /**
     * JavaScripts.
     *
     * @var array
     */
    public $javaScripts = null;

    /**
     * Pole kaskádových stylů
     * $var array.
     */
    public $cascadeStyles = null;

    /**
     * Pole konfigurací.
     *
     * @var array
     */
    public $configuration = [];

    /**
     * Informuje zdali je objekt spuštěn v prostředí webové stránky nebo jako script.
     *
     * @var string web|cli
     */
    public $runType = null;

    /**
     * Odkaz na instanci objektu uživatele.
     *
     * @var User|Anonym
     */
    public $user = null;

    /**
     * Odkaz na objekt databáze.
     *
     * @var SQL\PDO
     */
    public $dbLink = null;

    /**
     *
     * @var Locale
     */
    public $locale = null;

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

    /**
     * Pole odkazů na všechny vložené objekty.
     *
     * @var array pole odkazů
     */
    public $allItems = [];

    /**
     * Název položky session s objektem uživatele.
     *
     * @var string
     */
    public static $userSessionName = 'User';

    /**
     * Logger live here
     * @var Logger\ToFile|Logger\ToMemory|Logger\ToSyslog
     */
    static public $log = null;

    /**
     * Array of Status Messages
     * @var array of Logger\Message
     */
    public $messages = [];

    /**
     * Inicializace sdílené třídy.
     */
    public function __construct()
    {
        $cgiMessages = [];
        $webMessages = [];
        $prefix      = defined('EASE_APPNAME') ? constant('EASE_APPNAME') : '';
        $msgFile     = sys_get_temp_dir().'/'.$prefix.'EaseStatusMessages.ser';
        if (file_exists($msgFile) && is_readable($msgFile) && filesize($msgFile)
            && is_writable($msgFile)) {
            $cgiMessages = unserialize(file_get_contents($msgFile));
            file_put_contents($msgFile, '');
        }

        if (defined('EASE_APPNAME')) {
            if (isset($_SESSION[constant('EASE_APPNAME')]['EaseMessages'])) {
                $webMessages = $_SESSION[constant('EASE_APPNAME')]['EaseMessages'];
                unset($_SESSION[constant('EASE_APPNAME')]['EaseMessages']);
            }
        } else {
            if (isset($_SESSION['EaseMessages'])) {
                $webMessages = $_SESSION['EaseMessages'];
                unset($_SESSION['EaseMessages']);
            }
        }
        $this->statusMessages = is_array($cgiMessages) ? array_merge($cgiMessages,
                $webMessages) : $webMessages;
    }

    /**
     * Pri vytvareni objektu pomoci funkce singleton (ma stejne parametry, jako konstruktor)
     * se bude v ramci behu programu pouzivat pouze jedna jeho Instance (ta prvni).
     *
     * @param string $class název třídy jenž má být zinstancována
     *
     * @link   http://docs.php.net/en/language.oop5.patterns.html Dokumentace a priklad
     *
     * @return \Ease\Shared
     */
    public static function singleton($class = null)
    {
        if (!isset(self::$_instance)) {
            if (is_null($class)) {
                $class = __CLASS__;
            }
            self::$_instance = new $class();
        }

        return self::$_instance;
    }

    /**
     * Vrací se.
     *
     * @return Shared
     */
    public static function &instanced()
    {
        $easeShared = self::singleton();

        return $easeShared;
    }

    /**
     * Nastavuje hodnotu konfiguračního klíče.
     *
     * @param string $configName  klíč
     * @param mixed  $configValue hodnota klíče
     */
    public function setConfigValue($configName, $configValue)
    {
        $this->configuration[$configName] = $configValue;
    }

    /**
     * Vrací konfigurační hodnotu pod klíčem.
     *
     * @param string $configName klíč
     *
     * @return mixed
     */
    public function getConfigValue($configName)
    {
        return array_key_exists($configName, $this->configuration) ? $this->configuration[$configName]
                : null;
    }

    /**
     * Returns database object instance.
     *
     * @return SQL\PDO
     */
    public static function &db($pdo = null)
    {
        $shared = self::instanced();
        if (is_object($pdo)) {
            $shared->dbLink = &$pdo;
        }
        if (!is_object($shared->dbLink)) {
            $shared->dbLink = self::db(SQL\PDO::singleton(is_array($pdo) ? $pdo : [
                ]));
        }

        return $shared->dbLink;
    }

    /**
     * Vrací instanci objektu logování.
     *
     * @return Logger
     */
    public static function logger()
    {
        return Logger\Regent::singleton();
    }

    /**
     * Vrací nebo registruje instanci webové stránky.
     *
     * @param WebPage $oPage objekt webstránky k zaregistrování
     *
     * @return WebPage
     */
    public static function &webPage($oPage = null)
    {
        $shared = self::instanced();
        if (is_object($oPage)) {
            $shared->webPage = &$oPage;
        }
        if (!is_object($shared->webPage)) {
            $shared->webPage = WebPage::singleton();
        }
        return $shared->webPage;
    }

    /**
     * Locale Class handler
     *
     * @param Locale $locale overriding object
     *
     * @return Locale
     */
    public static function &locale($locale = null)
    {
        $shared = self::instanced();
        if (is_object($locale)) {
            $shared->locale = &$locale;
        }
        if (!is_object($shared->locale)) {
            $shared->locale = Locale::singleton();
        }
        return $shared->locale;
    }

    /**
     * Vrací, případně i založí objekt uživatele.
     *
     * @param User|Anonym|string $user objekt nového uživatele nebo
     *                                 název třídy
     *
     * @return User
     */
    public static function &user($user = null, $userSessionName = 'User')
    {
        $efprefix = defined('EASE_APPNAME') ? constant('EASE_APPNAME') : 'EaseFramework';

        if (is_null($user) && isset($_SESSION[$efprefix][self::$userSessionName])
            && is_object($_SESSION[$efprefix][self::$userSessionName])) {
            return $_SESSION[$efprefix][self::$userSessionName];
        }

        if (!is_null($userSessionName)) {
            self::$userSessionName = $userSessionName;
        }
        if (is_object($user)) {
            $_SESSION[$efprefix][self::$userSessionName] = clone $user;
        } else {
            if (class_exists($user)) {
                $_SESSION[$efprefix][self::$userSessionName] = new $user();
            } elseif (!isset($_SESSION[$efprefix][self::$userSessionName]) || !is_object($_SESSION[$efprefix][self::$userSessionName])) {
                $_SESSION[$efprefix][self::$userSessionName] = new Anonym();
            }
        }

        return $_SESSION[$efprefix][self::$userSessionName];
    }

    /**
     * Běží php v příkazovém řádku ?
     *
     * @return bool
     */
    public static function isCli()
    {
        return PHP_SAPI == 'cli' && empty($_SERVER['REMOTE_ADDR']);
    }

    /**
     * Zaregistruje položku k finalizaci.
     *
     * @param mixed $itemPointer
     */
    public static function registerItem(&$itemPointer)
    {
        $easeShared             = self::singleton();
        $easeShared->allItems[] = $itemPointer;
    }

    /**
     * Take message to print / log
     * @param Logger\Message $message
     */
    public function takeMessage($message)
    {
        $this->messages[] = $message;
        $this->addStatusMessage($message->body, $message->type);
        $this->logger()->addToLog($message->caller, $message->body,
            $message->type);
    }

    /**
     * Write remaining messages to temporary file.
     */
    public function __destruct()
    {
        if (self::isCli()) {
            $prefix       = defined('EASE_APPNAME') ? constant('EASE_APPNAME') : '';
            $messagesFile = sys_get_temp_dir().'/'.$prefix.'EaseStatusMessages.ser';
            file_put_contents($messagesFile, serialize($this->statusMessages));
        } else {
            if (defined('EASE_APPNAME')) {
                $_SESSION[constant('EASE_APPNAME')]['EaseMessages'] = $this->statusMessages;
            } else {
                $_SESSION['EaseMessages'] = $this->statusMessages;
            }
        }
    }

    /**
     * Load Configuration values from json file $this->configFile and define UPPERCASE keys
     *
     * @param string  $configFile      Path to file with configuration
     * @param boolean $defineConstants false to do not define constants
     *
     * @return array full configuration array
     */
    public function loadConfig($configFile, $defineConstants = false)
    {
        if (!file_exists($configFile)) {
            throw new Exception('Config file '.(realpath($configFile) ? realpath($configFile)
                    : $configFile).' does not exist');
        }
        $configuration = json_decode(file_get_contents($configFile), true);
        if (empty($configuration)) {
            $this->addStatusMessage('Empty Config File '.realpath($configFile) ? realpath($configFile)
                        : $configFile, 'debug');
        } else {
            foreach ($configuration as $configKey => $configValue) {
                if ($defineConstants && (strtoupper($configKey) == $configKey) && (!defined($configKey))) {
                    define($configKey, $configValue);
                } else {
                    $this->setConfigValue($configKey, $configValue);
                }
                $this->configuration[$configKey] = $configValue;
            }
        }

        if (array_key_exists('debug', $this->configuration)) {
            $this->debug = boolval($this->configuration['debug']);
        }

        return $this->configuration;
    }

    /**
     * Initialise Gettext
     *
     * $i18n/$defaultLocale/LC_MESSAGES/$appname.mo
     *
     * @deprecated since version 1.5 - Moved to EaseBricks
     *
     * @param string $appname        name for binddomain
     * @param string $defaultLocale  locale of source code localstring
     * @param string $i18n           directory base localisation directory
     *
     * @return
     */
    public static function initializeGetText($appname, $defaultLocale = 'en_US',
                                             $i18n = '../i18n')
    {
        return self::instanced()->locale(new Locale($defaultLocale, $i18n,
                $appname));
    }

    /**
     * Add params to url
     *
     * @param string  $url      originall url
     * @param array   $addParams   value to add
     * @param boolean $override replace already existing values ?
     *
     * @return string url with parameters added
     */
    public static function addUrlParams($url, $addParams, $override = false)
    {
        $urlParts = parse_url($url);
        $urlFinal = '';
        if (array_key_exists('scheme', $urlParts)) {
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
        }
        if (array_key_exists('port', $urlParts)) {
            $urlFinal .= ':'.$urlParts['port'];
        }
        if (array_key_exists('path', $urlParts)) {
            $urlFinal .= $urlParts['path'];
        }
        if (array_key_exists('query', $urlParts)) {
            parse_str($urlParts['query'], $queryUrlParams);
            $urlParams = $override ? array_merge($queryUrlParams, $addParams) : array_merge($addParams,
                    $queryUrlParams);
        } else {
            $urlParams = $addParams;
        }

        if (!empty($urlParams)) {
            $urlFinal .= '?';
            if (is_array($urlParams)) {
                $urlFinal .= http_build_query($urlParams);
            } else {
                $urlFinal .= $urlParams;
            }
        }
        return $urlFinal;
    }

    /**
     * Turn all URLs in clickable links.
     *
     * @author Arnold Daniels <arnold@jasny.net>
     *
     * @param string $value
     * @param array  $protocols  http/https, ftp, mail, twitter
     * @param array  $attributes
     * @param string $mode       normal or all
     *
     * @return string
     */
    public static function linkify($value, $protocols = array('http', 'mail'),
                                   array $attributes = array())
    {
        // Link attributes
        $attr = '';
        foreach ($attributes as $key => $val) {
            $attr = ' '.$key.'="'.htmlentities($val).'"';
        }

        $links = array();

        // Extract existing links and tags
        $value = preg_replace_callback('~(.*?|<.*?>)~i',
            function ($match) use (&$links) {
            return '<'.array_push($links, $match[1]).'>';
        }, $value);

        // Extract text links for each protocol
        foreach ((array) $protocols as $protocol) {
            switch ($protocol) {
                case 'http':
                case 'https': $value = preg_replace_callback('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i',
                        function ($match) use ($protocol, &$links, $attr) {
                        if ($match[1]) $protocol = $match[1];
                        $link     = $match[2] ?: $match[3];
                        return '<'.array_push($links,
                                "$link").'>';
                    }, $value);
                    break;
                case 'mail': $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~',
                        function ($match) use (&$links, $attr) {
                        return '<'.array_push($links,
                                "{$match[1]}").'>';
                    }, $value);
                    break;
                case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#](\w++)~',
                        function ($match) use (&$links, $attr) {
                        return '<'.array_push($links,
                                "{$match[0]}").'>';
                    }, $value);
                    break;
                default: $value = preg_replace_callback('~'.preg_quote($protocol,
                            '~').'://([^\s<]+?)(?<![\.,:])~i',
                        function ($match) use ($protocol, &$links, $attr) {
                        return '<'.array_push($links,
                                "{$match[1]}").'>';
                    }, $value);
                    break;
            }
        }

        // Insert all link
        return preg_replace_callback('/<(\d+)>/',
            function ($match) use (&$links) {
            return $links[$match[1] - 1];
        }, $value);
    }
}


<?php

namespace Ease\Html;

/**
 * HTML table.
 *
 * @author     Vitex <vitex@hippy.cz>
 */
class TableTag extends PairTag
{
    /**
     * Hlavička tabulky.
     * @var Thead
     */
    public $tHead = null;

    /**
     * Table Body
     * @var Tbody
     */
    public $tbody = null;

    /**
     * Table Foot
     * @var Tfoot
     */
    public $tFoot = null;

    /**
     * Html Table.
     *
     * @param mixed $content    vkládaný obsah
     * @param array $properties parametry tagu
     */
    public function __construct($content = null, $properties = [])
    {
        parent::__construct('table', $properties, $content);
        $this->tHead = $this->addItem(new Thead());
        $this->tBody = $this->addItem(new Tbody());
        $this->tFoot = $this->addItem(new Tfoot());
    }

    /**
     * @param array $headerColumns položky záhlaví tabulky
     */
    public function setHeader($headerColumns)
    {
        $this->tHead->emptyContents();
        $this->addRowHeaderColumns($headerColumns);
    }

    /**
     * Vloží do tabulky obsah pole jako buňky.
     *
     * @param array $columns    pole obsahů buňek
     * @param array $properties pole vlastností dané všem buňkám
     *
     * @return TrTag odkaz na řádku tabulky
     */
    public function &addRowColumns($columns = null, $properties = [])
    {
        $tableRow = $this->tBody->addItem(new TrTag());
        if (is_array($columns)) {
            foreach ($columns as $column) {
                if (is_object($column) && method_exists($column, 'getTagType') && $column->getTagType()
                    == 'td') {
                    $tableRow->addItem($column);
                } else {
                    $tableRow->addItem(new TdTag($column, $properties));
                }
            }
        }

        return $tableRow;
    }

    /**
     * Vloží do tabulky obsah pole jako buňky.
     *
     * @param array $columns    pole obsahů buňek
     * @param array $properties pole vlastností dané všem buňkám
     *
     * @return TrTag odkaz na řádku tabulky
     */
    public function &addRowHeaderColumns($columns = null, $properties = [])
    {
        $tableRow = $this->tHead->addItem(new TrTag());
        if (is_array($columns)) {
            foreach ($columns as $column) {
                if (is_object($column) && method_exists($column, 'getTagType') && $column->getTagType()
                    == 'th') {
                    $tableRow->addItem($column);
                } else {
                    $tableRow->addItem(new ThTag($column, $properties));
                }
            }
        }

        return $tableRow;
    }

    /**
     * Insert columns into table foot
     *
     * @param array $columns    values
     * @param array $properties options to add
     *
     * @return TrTag odkaz na řádku tabulky
     */
    public function &addRowFooterColumns($columns = null, $properties = [])
    {
        $tableRow = $this->tFoot->addItem(new TrTag());
        if (is_array($columns)) {
            foreach ($columns as $column) {
                if (is_object($column) && method_exists($column, 'getTagType') && $column->getTagType()
                    == 'th') {
                    $tableRow->addItem($column);
                } else {
                    $tableRow->addItem(new ThTag($column, $properties));
                }
            }
        }

        return $tableRow;
    }

    /**
     * Is Table Empty ?
     *
     * @param null $element je zde pouze z důvodu zpětné kompatibility
     *
     * @return type
     */
    public function isEmpty($element = null)
    {
        return $this->tBody->isEmpty();
    }

    /**
     * Populate table with given data
     *
     * @param array $contents
     */
    public function populate($contents)
    {
        foreach ($contents as $cRow) {
            $this->addRowColumns($cRow);
        }
    }
}


<?php
/**
 * Obsluha MySQL.
 *
 * @deprecated since version 2.0
 *
 * @author     Vitex <vitex@hippy.cz>
 * @copyright  2012 Vitex@hippy.cz (G)
 */

namespace Ease\SQL;

/**
 * Třída pro práci s MySQL.
 *
 * @author Vitex <vitex@hippy.cz>
 */
class MySQLi extends SQL
{
    /**
     * MySQLi class instance.
     *
     * @var mysqli
     */
    public $sqlLink = null; // MS SQL link identifier

    /**
     * SQLLink result.
     *
     * @var mysqli_result
     */
    public $result    = null;
    public $status    = false; //Pripojeno ?
    public $lastQuery = '';
    public $numRows   = 0;
    public $debug     = false;
    public $keyColumn = '';
    public $data      = null;
    public $charset   = 'utf8';
    public $collate   = 'utf8_czech_ci';

    /**
     * Povolit Explain každého dotazu do logu ?
     *
     * @var bool
     */
    public $explainMode = false;

    /**
     * Nastavení vlastností přípojení.
     *
     * @var array
     */
    public $connectionSettings = [
        'NAMES' => 'utf8',
    ];

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

    /**
     * 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;
    }

    /**
     * Escapes special characters in a string for use in an SQL statement.
     *
     * @param string $text
     *
     * @return string
     */
    public function addSlashes($text)
    {
        return $this->sqlLink->real_escape_string($text);
    }

    /**
     * Připojí se k mysql databázi.
     */
    public function connect()
    {
        $this->sqlLink = new \mysqli($this->server, $this->username,
            $this->password);
        if ($this->sqlLink->connect_errno) {
            $this->addStatusMessage('Connect: error #'.$this->sqlLink->connect_errno.' '.$this->sqlLink->connect_error,
                'error');

            return false;
        } else {
            if ($this->selectDB($this->database)) {
                $this->errorText = $this->sqlLink->error;
                parent::connect();
            } else {
                return false;
            }
        }
    }

    /**
     * Změní aktuálně použitou databázi.
     *
     * @param string $dbName
     *
     * @return bool
     */
    public function selectDB($dbName = null)
    {
        parent::selectDB($dbName);
        $change = $this->sqlLink->select_db($dbName);
        if ($change) {
            $this->Database = $dbName;
        } else {
            $this->errorText   = $this->sqlLink->error;
            $this->errorNumber = $this->sqlLink->errno;
            $this->addStatusMessage('Connect: error #'.$this->errorNumber.' '.$this->errorText,
                'error');
            $this->logError();
        }

        return $change;
    }

    /**
     * Vykoná QueryRaw a vrátí výsledek.
     *
     * @param string $queryRaw
     * @param bool   $ignoreErrors
     *
     * @return SQLhandle
     */
    public function exeQuery($queryRaw, $ignoreErrors = false)
    {
        $queryRaw           = $this->sanitizeQuery($queryRaw);
        $this->lastQuery    = $queryRaw;
        $this->lastInsertID = null;
        $this->errorText    = null;
        $this->errorNumber  = null;
        $sqlAction          = trim(strtolower(current(explode(' ', $queryRaw))));

        $this->result      = $this->sqlLink->query($queryRaw);
        $this->errorNumber = $this->sqlLink->errno;
        $this->errorText   = $this->sqlLink->error;

        $this->logSqlError($ignoreErrors);

        switch ($sqlAction) {
            case 'select':
            case 'show':
                if (!$this->errorText) {
                    $this->numRows = $this->result->num_rows;
                }
                break;
            case 'insert':
                if (!$this->errorText) {
                    $this->lastInsertID = $this->sqlLink->insert_id;
                }
            case 'update':
            case 'replace':
            case 'delete':
            case 'alter':
                $this->numRows = $this->sqlLink->affected_rows;
                break;
            default:
                $this->numRows = null;
        }
        if ($this->explainMode) {
            $explainQuery = $this->sqlLink->query('EXPLAIN '.$queryRaw);
            if ($explainQuery) {
                $explainedQuery = $explainQuery->fetch_assoc();
                $this->addToLog('Explain: '.$queryRaw."\n".$this->printPreBasic($explainedQuery),
                    'explain');
            }
        }

        return $this->result;
    }

    /**
     * vraci vysledek SQL dotazu $QueryRaw jako pole (uchovavane take jako $this->Resultarray).
     *
     * @param string $queryRaw
     * @param string $keyColumnToIndex umožní vrátit pole výsledků číslovaných podle $DataRow[$KeyColumnToIndex];
     *
     * @return array
     */
    public function queryToArray($queryRaw, $keyColumnToIndex = false)
    {
        $resultArray = [];
        if ($this->exeQuery($queryRaw) && is_object($this->result)) {
            if (is_string($keyColumnToIndex)) {
                while ($dataRow = $this->result->fetch_assoc()) {
                    $resultArray[$dataRow[$keyColumnToIndex]] = $dataRow;
                }
            } else {
                if (($keyColumnToIndex === true) && isset($this->keyColumn)) {
                    while ($dataRow = $this->result->fetch_assoc()) {
                        $resultArray[$dataRow[$this->keyColumn]] = $dataRow;
                    }
                } else {
                    while ($dataRow = $this->result->fetch_assoc()) {
                        $resultArray[] = $dataRow;
                    }
                }
            }
        } else {
            return;
        }

        return $resultArray;
    }

    /**
     * vloží obsah pole $data do předvolené tabulky $this->myTable.
     *
     * @param string $data
     *
     * @return sqlresult
     */
    public function arrayToInsert($data)
    {
        return $this->exeQuery('INSERT INTO `'.$this->TableName.'` SET '.$this->arrayToQuery($data));
    }

    /**
     * upravi obsah zaznamu v predvolene tabulce $this->myTable, kde klicovy sloupec
     * $this->keyColumn je hodnota v klicovem sloupci hodnotami z pole $data.
     *
     * @param array $data  asociativní pole dat
     * @param int   $keyID id záznamu. Není li uveden použije se aktuální
     *
     * @return sqlresult
     */
    public function arrayToUpdate($data, $keyID = null)
    {
        if (empty($keyID)) {
            $idCol = $data[$this->keyColumn];
        }
        unset($data[$this->keyColumn]);

        return $this->exeQuery(SQL::$upd.$this->TableName.' SET '.$this->arrayToQuery($data).SQL::$whr.$this->keyColumn.'='.$idCol);
    }

    /**
     * z pole $data vytvori fragment SQL dotazu za WHERE (klicovy sloupec
     * $this->keyColumn je preskocen pokud neni $key false).
     *
     * @param array $data
     * @param bool  $Key
     *
     * @return string
     */
    public function arrayToQuery($data, $Key = true)
    {
        $updates = '';
        foreach ($data as $column => $value) {
            if (!strlen($column)) {
                continue;
            }
            if (($column == $this->keyColumn) && $Key) {
                continue;
            }
            switch (gettype($value)) {
                case 'integer':
                    $value = " $value ";
                    break;
                case 'float':
                case 'double':
                    $value = ' '.str_replace(',', '.', $value).' ';
                    break;
                case 'boolean':
                    if ($value) {
                        $value = ' 1 ';
                    } else {
                        $value = ' 0 ';
                    }
                    break;
                case 'null':
                    $value = ' null ';
                    break;
                case 'string':
                    if ($value != 'NOW()') {
                        if (!strstr($value, "\'")) {
                            $value = " '".str_replace("'", "\'", $value)."' ";
                        } else {
                            $value = " '$value' ";
                        }
                    }
                    break;
                default:
                    $value = " '$value' ";
            }

            $updates .= " `$column` = $value,";
        }

        return substr($updates, 0, -1);
    }

    /**
     * Generuje fragment MySQL dotazu z pole data.
     *
     * @param array  $data Pokud hodnota zacina znakem ! Je tento odstranen a generovan je negovany test
     * @param string $ldiv typ generovane podminky AND/OR
     *
     * @return sql
     */
    public function prepSelect($data, $ldiv = 'AND')
    {
        $operator     = null;
        $conditions   = [];
        $conditionsII = [];
        foreach ($data as $column => $value) {
            if (is_integer($column)) {
                $conditionsII[] = $value;
                continue;
            }
            if (($column == $this->keyColumn) && ($this->keyColumn == '')) {
                continue;
            }
            if (is_string($value) && (($value == '!=""') || ($value == "!=''"))) {
                $conditions[] = " `$column` !='' ";
                continue;
            }

            if (is_null($value)) {
                $value    = 'null';
                $operator = ' IS ';
            } else {
                if (strlen($value) && ($value[0] == '!')) {
                    $operator = ' != ';
                    $value    = substr($value, 1);
                } else {
                    if (($value == '!null') || (strtoupper($value) == 'IS NOT null')) {
                        $value    = 'null';
                        $operator = 'IS NOT';
                    } else {
                        if (is_null($operator)) {
                            $operator = ' = ';
                        }
                    }
                }
                if (is_bool($value)) {
                    if ($value === null) {
                        $value .= ' null,';
                    } elseif ($value) {
                        $value = ' 1';
                    } else {
                        $value = ' 0';
                    }
                } elseif (!is_string($value)) {
                    $value = " $value";
                } else {
                    if (strtoupper($value) == 'NOW()') {
                        $value = " 'NOW()'";
                    } else {
                        if ($value != 'null') {
                            $value = " '".addslashes($value)."'";
                        }
                    }
                    if ($operator == ' != ') {
                        $operator = ' NOT LIKE ';
                    } else {
                        if (is_null($operator)) {
                            $operator = ' LIKE ';
                        }
                    }
                }
            }

            $conditions[] = " `$column` $operator $value ";
        }

        return trim(implode($ldiv, $conditions).' '.implode(' ', $conditionsII));
    }

    /**
     * Vrací 1 pokud tabulka v databázi existuje.
     *
     * @param string $tableName
     *
     * @return int
     */
    public function tableExist($tableName = null)
    {
        if (!parent::tableExist($tableName)) {
            return;
        }
        $this->exeQuery("SHOW TABLES LIKE '".$tableName."'");
        if ($this->numRows) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Vrací počet řádek v tabulce.
     *
     * @param string $tableName
     *
     * @return int
     */
    public function getTableNumRows($tableName = null)
    {
        if (!$tableName) {
            $tableName = $this->TableName;
        }
        $TableRowsCount = $this->queryToArray(SQL::$sel.'count(*) AS NumRows FROM `'.$this->easeAddSlashes($tableName).'`');

        return $TableRowsCount[0]['NumRows'];
    }

    /**
     * Vyprázdní tabulku.
     *
     * @param string $tableName
     *
     * @return bool success
     */
    public function truncateTable($tableName)
    {
        $this->exeQuery('TRUNCATE '.$tableName);
        if (!$this->getTableNumRows($tableName)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Close database connect
     * Ukončí připojení k databázi.
     *
     * @return boolean
     */
    public function close()
    {
        if (is_resource($this->sqlLink)) {
            return mysqli_close($this->sqlLink);
        } else {
            return $this->sqlLink->close();
        }
    }

    /**
     * Virtuální funkce.
     */
    public function __destruct()
    {
        return;
    }
}


<?php
/**
 * Simple html page class.
 *
 * @author     Vitex <vitex@hippy.cz>
 * @copyright  2009-2014 Vitex@hippy.cz (G)
 */

namespace Ease;

/**
 * Objekt určený k "pojmutí" obsahu - sám nemá žádnou viditelnou část.
 *
 * @author Vitex <vitex@hippy.cz>
 */
class Page extends Container
{
    /**
     * Saves obejct instace (singleton...).
     */
    private static $_instance = null;

    /**
     * Odkaz na základní objekt stránky.
     *
     * @var EaseWebPage
     */
    public $webPage = null;

    /**
     * Které objekty převzít od přebírajícího objektu.
     *
     * @var array
     */
    public $raiseItems = ['SetUpUser' => 'User', 'webPage', 'OutputFormat'];

    /**
     * Odkaz na naposledy přidaný element.
     *
     * @var object
     */
    public $lastItem = null;

    /**
     * Specifikuje preferovaný účel zobrazení například mail.
     *
     * @var string
     */
    public $outputFormat = null;

    /**
     * Is page closed for adding new contents ?
     *
     * @var bool
     */
    public $pageClosed = false;

    /**
     * Pri vytvareni objektu pomoci funkce singleton (ma stejne parametry, jako konstruktor)
     * se bude v ramci behu programu pouzivat pouze jedna jeho instance (ta prvni).
     *
     * @param EaseUser $user objekt uživatele k přiřazení
     *
     * @link   http://docs.php.net/en/language.oop5.patterns.html Dokumentace a priklad
     *
     * @return EaseWebPage
     */
    public static function singleton($user = null)
    {
        if (!isset(self::$_instance)) {
            $class           = __CLASS__;
            self::$_instance = new $class($user);
        }

        return self::$_instance;
    }

    /**
     * Vloží javascript do stránky.
     *
     * @param string $javaScript      JS code
     * @param string $position        končná pozice: '+','-','0','--',...
     * @param bool   $inDocumentReady vložit do DocumentReady bloku ?
     *
     * @return int
     */
    public function addJavaScript($javaScript, $position = null,
                                  $inDocumentReady = true)
    {
        return \Ease\Shared::webPage()->addJavaScript($javaScript, $position,
                $inDocumentReady);
    }

    /**
     * Includuje Javascript do stránky.
     *
     * @param string $javaScriptFile soubor s javascriptem
     * @param string $position       končná pozice: '+','-','0','--',...
     *
     * @return string
     */
    public function includeJavaScript($javaScriptFile, $position = null)
    {
        return \Ease\Shared::webPage()->includeJavaScript($javaScriptFile,
                $position);
    }

    /**
     * Add another CSS definition to stack.
     *
     * @param string $css css definice
     *
     * @return bool
     */
    public function addCSS($css)
    {
        return \Ease\Shared::webPage()->addCSS($css);
    }

    /**
     * Include an CSS file call into page.
     *
     * @param string $cssFile  cesta k souboru vkládanému do stránky
     * @param bool   $fwPrefix přidat prefix frameworku (obvykle /Ease/) ?
     * @param string $media    médium screen|print|braile apod ...
     *
     * @return int
     */
    public function includeCss($cssFile, $fwPrefix = false, $media = 'screen')
    {
        return \Ease\Shared::webPage()->includeCss($cssFile, $fwPrefix, $media);
    }

    /**
     * Perform http redirect
     * Provede http přesměrování.
     *
     * @param string $url adresa přesměrování
     */
    public function redirect($url)
    {
        $messages = Shared::instanced()->statusMessages;
        if (count($messages)) {
            $_SESSION['EaseMessages'] = $messages;
        }
        if (headers_sent()) {
            $this->addJavaScript('window.location = "'.$url.'"', 0, false);
        } else {
            header('Location: '.$url);
        }
        $this->pageClosed = true;
    }

    /**
     * Vrací požadovanou adresu.
     *
     * @return string
     */
    public static function getUri()
    {
        return $_SERVER['REQUEST_URI'];
    }

    /**
     * Returns the current URL. This is instead of PHP_SELF which is unsafe.
     *
     * @param bool $dropqs whether to drop the querystring or not. Default true
     *
     * @return string the current URL or NULL for php-cli
     */
    public static function phpSelf($dropqs = true)
    {
        $url = null;
        if (php_sapi_name() != 'cli') {

            $schema = 'http';
            if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) {
                $schema .= 's';
            }
            $url = sprintf('%s://%s%s', $schema, $_SERVER['SERVER_NAME'],
                $_SERVER['REQUEST_URI']);

            $parts = parse_url($url);

            $port   = $_SERVER['SERVER_PORT'];
            $scheme = $parts['scheme'];
            $host   = $parts['host'];
            if (isset($parts['path'])) {
                $path = $parts['path'];
            } else {
                $path = null;
            }
            if (isset($parts['query'])) {
                $qs = $parts['query'];
            } else {
                $qs = null;
            }
            $port || $port = ($scheme == 'https') ? '443' : '80';

            if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port
                != '80')
            ) {
                $host = "$host:$port";
            }
            $url = "$scheme://$host$path";
            if (!$dropqs) {
                return "{$url}?{$qs}";
            } else {
                return $url;
            }
        }
    }

    /**
     * Nepřihlášeného uživatele přesměruje na přihlašovací stránku.
     *
     * @param string $loginPage adresa přihlašovací stránky
     */
    public function onlyForLogged($loginPage = 'login.php', $message = null)
    {
        $user = Shared::user();
        if (!method_exists($user, 'isLogged') || !$user->isLogged()) {
            if (!empty($message)) {
                Shared::user()->addStatusMessage(_('Sign in first please'),
                    'warning');
            }
            $this->redirect($loginPage);
            $this->pageClosed = true;
        }
    }

    /**
     * Include next element into current page (if not closed).
     *
     * @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)
    {
        $result = null;
        if ($this->pageClosed === false) {
            $result = parent::addItem($pageItem, $pageItemName);
        }

        return $result;
    }

    /**
     * Vrací pole $_REQUEST.
     *
     * @return array
     */
    public function getRequestValues()
    {
        return $_REQUEST;
    }

    /**
     * Is page called by Form Post ?
     *
     * @return bool
     */
    public static function isPosted()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Ošetří proměnou podle jejího očekávaného typu.
     *
     * @param mixed  $value      hodnota
     * @param string $sanitizeAs typ hodnoty int|string|float|null
     *
     * @return mixed
     */
    public static function sanitizeAsType($value, $sanitizeAs)
    {
        $sanitized = null;
        switch ($sanitizeAs) {
            case 'string':
                $sanitized = (string) $value;
                break;
            case 'int':
                $sanitized = strlen($value) ? (int) $value : null;
                break;
            case 'float':
                $sanitized = (float) $value;
                break;
            case 'bool':
            case 'boolean':
                switch ($value) {
                    case 'FALSE':
                    case 'false':
                        $sanitized = false;
                        break;
                    case 'true':
                    case 'TRUE':
                        $sanitized = true;
                        break;
                    default:
                        $sanitized = boolval($value);
                        break;
                }
                break;
            case 'null':
            default:
                $sanitized = $value;
                break;
        }

        return $sanitized;
    }

    /**
     * Vrací hodnotu klíče prametru volání stránky.
     *
     * @param string $field      klíč POST nebo GET
     * @param string $sanitizeAs ošetřit vrácenou hodnotu jako float|int|string
     *
     * @return mixed
     */
    public function getRequestValue($field, $sanitizeAs = null)
    {
        $value = null;
        if (isset($_REQUEST[$field])) {
            $value = empty($sanitizeAs) ? $_REQUEST[$field] : self::sanitizeAsType($_REQUEST[$field],
                    $sanitizeAs);
        }
        return $value;
    }

    /**
     * Vrací hodnotu klíče pramatru volání stránky.
     *
     * @param string $field      klíč GET
     * @param string $sanitizeAs ošetřit vrácenou hodnotu jako float|int|string
     *
     * @return string
     */
    public static function getGetValue($field, $sanitizeAs = null)
    {
        $value = null;
        if (isset($_GET[$field])) {
            $value = empty($sanitizeAs) ? $_GET[$field] : self::sanitizeAsType($_GET[$field],
                    $sanitizeAs);
        }
        return $value;
    }

    /**
     * Vrací hodnotu klíče pramatru volání stránky.
     *
     * @param string $field      klíč POST
     * @param string $sanitizeAs ošetřit vrácenou hodnotu jako float|int|string
     *
     * @return string
     */
    public static function getPostValue($field, $sanitizeAs = null)
    {
        $value = null;
        if (isset($_POST[$field])) {
            $value = empty($sanitizeAs) ? $_POST[$field] : self::sanitizeAsType($_POST[$field],
                    $sanitizeAs);
        }
        return $value;
    }

    /**
     * Byla stránka zobrazena po odeslání formuláře metodou POST ?
     *
     * @category requestValue
     *
     * @return bool
     */
    public static function isFormPosted()
    {
        return isset($_POST) && count($_POST);
    }

    /**
     * Nastaví formát výstupu.
     *
     * @param string $outputFormat výstupní formát, např Mail nebo Print
     */
    public function setOutputFormat($outputFormat)
    {
        $this->outputFormat = $outputFormat;
        foreach ($this->pageParts as $part) {
            $this->raise($part, ['OutputFormat']);
        }
    }

    /**
     * Vrací formát výstupu.
     */
    public function getOutputFormat()
    {
        return $this->outputFormat;
    }

    /**
     * Převezme hlášky z pole nebo objektu.
     *
     * @param mixed $msgSource zdroj zpráv - pole nebo EaseObjekt
     * @param array $denyQues  neprevezme tyto typy
     *
     * @return int počet převzatých hlášek
     */
    public function takeStatusMessages($msgSource, $denyQues = null)
    {
        if (is_array($msgSource) && count($msgSource)) {
            $allMessages = [];
            foreach ($msgSource as $quee => $messages) {
                if (is_array($denyQues) && in_array($quee, $denyQues)) {
                    continue;
                }
                foreach ($messages as $mesgID => $message) {
                    $allMessages[$mesgID][$quee] = $message;
                }
            }
            ksort($allMessages);
            foreach ($allMessages as $message) {
                $quee = key($message);
                $this->addStatusMessage(reset($message), $quee);
            }

            return count($msgSource);
        }
        if (is_object($msgSource)) {
            if (isset($msgSource->statusMessages) && count($msgSource->statusMessages)) {
                $msgTaken = count($msgSource->statusMessages);
                $this->addStatusMessages($msgSource->getStatusMessages(true));

                return $msgTaken;
            } else {
                if (isset($msgSource->webPage) && isset($msgSource->webPage->statusMessages)
                    && count($msgSource->webPage->statusMessages)) {
                    $msgTaken                           = count($msgSource->webPage->statusMessages);
                    $this->statusMessages               = array_merge($this->statusMessages,
                        $msgSource->webPage->statusMessages);
                    $msgSource->webPage->statusMessages = [];

                    return $msgTaken;
                }
            }
        }

        return 0;
    }

    /**
     * Vrací pole jako parametry URL.
     *
     * @param array  $params
     * @param string $baseUrl
     */
    public static function arrayToUrlParams($params, $baseUrl = '')
    {
        if (strstr($baseUrl, '?')) {
            return $baseUrl.'&'.http_build_query($params);
        } else {
            return $baseUrl.'?'.http_build_query($params);
        }
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: minhao
 * Date: 2016-01-09
 * Time: 18:08
 */

namespace Oasis\SlimApp;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SlimAppCompilerPass implements CompilerPassInterface
{
    protected $classname;

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

    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        if ($container->hasParameter('default.namespace')) {
            $defaultNamespaces = $container->getParameter('default.namespace');
            if (is_string($defaultNamespaces)) {
                $defaultNamespaces = [$defaultNamespaces];
            }

            foreach ($container->getDefinitions() as $id => $definition) {

                // We need to prepare 'app' service
                if ($id == 'app') {
                    $definition->setClass($this->classname);
                    $definition->setFactory([$this->classname, 'app']);
                    continue;
                }

                if (($class = $definition->getClass())
                    && !class_exists($class)
                    && !class_exists("\\" . $class)
                ) {
                    foreach ($defaultNamespaces as $ns) {
                        $ns         = trim($ns, "\\");
                        $class      = trim($class, "\\");
                        $full_class = "$ns\\$class";
                        if (class_exists($full_class)) {
                            $definition->setClass($full_class);

                            break;
                        }
                    }
                }

                if (($factory = $definition->getFactory())
                    && is_array($factory)
                    && (0 !== strpos($factory[0], "@"))
                    && !class_exists($class = $factory[0])
                    && !class_exists("\\" . $class)
                ) {
                    foreach ($defaultNamespaces as $ns) {
                        $ns         = trim($ns, "\\");
                        $class      = trim($class, "\\");
                        $full_class = "$ns\\$class";
                        if (class_exists($full_class)) {
                            $definition->setFactory([$full_class, $factory[1]]);
                            break;
                        }
                    }
                }
            }
        }
    }
}


<?php
/**
 * Základní pojící element všech objektů v EaseFrameWorku. Jeho hlavní schopnost je:
 * Pojímat do sebe zprávy.
 *
 * @category Common
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2019 Vitex@hippy.cz (G)
 * @license http://URL GPL-2
 *
 * PHP 7
 */

namespace Ease;

/**
 * Basic Class of EasePHP
 *
 * @author Vítězslav Dvořák <info@vitexsoftware.cz>
 */
class Atom
{
    /**
     * Version of EasePHP Framework
     *
     * @var string
     */
    static public $frameworkVersion = '1.19';

    /**
     * Udržuje v sobě jméno objektu.
     *
     * @var string
     */
    public $objectName = 'EaseSand';

    /**
     * Flag debugovacího režimu.
     *
     * @var bool
     */
    public $debug = false;

    /**
     * Pole informaci urcenych k logovani inebo zobrazovanych uzivateli.
     *
     * @var array
     */
    public $statusMessages = [];

    /**
     * Pocet uchovavanych zprav.
     *
     * @var int
     */
    public $messageCount = 0;

    /**
     * Vrací jméno objektu.
     *
     * @return string
     */
    public function getObjectName()
    {
        return get_class();
    }

    /**
     * Add message to stack to show or write to file
     * Přidá zprávu do zásobníku pro zobrazení uživateli inbo do logu.
     *
     * @param string $message text zpravy
     * @param string $type    fronta
     */
    public function addStatusMessage($message, $type = 'info')
    {
        ++$this->messageCount;
        $this->statusMessages[$type][$this->messageCount] = $message;
    }

    /**
     * Přidá zprávy z pole uživateli do zásobníku.
     *
     * @param array $statusMessages pole zpráv
     *
     * @return int Počet zpráv přidaných do fronty
     */
    public function addStatusMessages($statusMessages)
    {
        if (is_array($statusMessages) && count($statusMessages)) {
            $allMessages = [];
            foreach ($statusMessages as $quee => $messages) {
                foreach ($messages as $mesgID => $message) {
                    $allMessages[$mesgID][$quee] = $message;
                }
            }
            ksort($allMessages);
            foreach ($allMessages as $message) {
                $quee = key($message);
                $this->addStatusMessage(reset($message), $quee);
            }

            return count($statusMessages);
        }

        return;
    }

    /**
     * Vymaže zprávy.
     */
    public function cleanMessages()
    {
        $this->messageCount   = 0;
        $this->statusMessages = [];
    }

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

            return $statusMessages;
        } else {
            return $this->statusMessages;
        }
    }

    /**
     * Prevezme si zpravy z vnějšího zdroje.
     *
     * @param array $statusMessages pole zpráv např. $OUser->StatusMessages
     */
    public function takeStatusMessages($statusMessages)
    {
        if (is_object($statusMessages) && isset($statusMessages->statusMessages)) {
            return $this->addStatusMessages($statusMessages->statusMessages);
        } else {
            return $this->addStatusMessages($statusMessages);
        }
    }

    /**
     * Returns PATH modified for current operating system.
     *
     * @param string $path
     *
     * @return string
     */
    public static function sysFilename($path)
    {
        return str_replace(['\\', '/'], constant('DIRECTORY_SEPARATOR'), $path);
    }

    /**
     * Magická funkce pro všechny potomky.
     *
     * @return string
     */
    public function __toString()
    {
        return '';
    }

    /**
     * Default Draw method.
     *
     * @return string
     */
    public function draw()
    {
        if (method_exists($this, '__toString')) {
            return $this->__toString();
        }
    }
}


<?php

namespace Ease\TWB4;

/**
 * Stránka TwitterBootstrap4.
 *
 * @author     Vítězslav Dvořák <vitex@hippy.cz>
 * @copyright  2017 Vitex@vitexsoftware.cz (G)
 *
 * @link       http://twitter.github.com/bootstrap/index.html
 */
class WebPage extends \Ease\WebPage
{
    /**
     * Boostrap URL Strart path with ./ to use local one.
     *
     * @var string relative path/url
     */
    public $mainStyle = 'bootstrap4/css/bootstrap.css';

    /**
     * Stránka s podporou pro twitter bootstrap.
     *
     * @param string   $pageTitle
     */
    public function __construct($pageTitle = null)
    {
        parent::__construct($pageTitle);
        $this->includeCss($this->mainStyle, ($this->mainStyle[0] != '.'));
        $this->head->addItem(
            '<meta charset="utf-8">'.
            '<meta name="viewport" content="width=device-width,initial-scale=1.0">'
        );
    }

    /**
     * Vrací zprávy uživatele.
     *
     * @param string $what info|warning|error|success
     *
     * @return string
     */
    public function getStatusMessagesAsHtml($what = null)
    {
        /*
         * Session Singleton Problem hack
         */
        if (!count($this->easeShared->statusMessages)) {
            return '';
        }
        $htmlFargment = '';

        $allMessages = [];
        foreach ($this->easeShared->statusMessages as $quee => $messages) {
            foreach ($messages as $msgID => $message) {
                $allMessages[$msgID][$quee] = $message;
            }
        }
        ksort($allMessages);
        foreach ($allMessages as $messages) {
            $messageType = key($messages);

            if (is_array($what)) {
                if (!in_array($messageType, $what)) {
                    continue;
                }
            }

            foreach ($messages as $message) {
                if (is_object($this->logger)) {
                    if (!isset($this->logger->logStyles[$messageType])) {
                        $messageType = 'notice';
                    }
                    if ($messageType == 'error') {
                        $messageType = 'danger';
                    }
                    $htmlFargment .= '
'.$message.'
'."\n";
                } else {
                    $htmlFargment .= '
'.$message.'
'."\n";
                }
            }
        }

        return $htmlFargment;
    }
}


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

namespace NetLicensing;

/**
 * PHP representation of the ProductModule Service. See NetLicensingAPI for details:
 * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services
 *
 * @package NetLicensing
 */
class ProductModuleService
{
    /**
     * Creates new product module object with given properties.See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Createproductmodule
     *
     * determines the vendor on whose behalf the call is performed
     * @param Context $context
     *
     * parent product to which the new product module is to be added
     * @param string $productNumber
     *
     * non-null properties will be taken for the new object, null properties will either stay null, or will
     * be set to a default value, depending on property.
     * @param ProductModule $productModule
     *
     * the newly created product module object
     * @return ProductModule|null
     * @throws MalformedArgumentsException
     * @throws RestException
     * @throws \ErrorException
     */
    public static function create(Context $context, $productNumber, ProductModule $productModule)
    {
        CheckUtils::paramNotEmpty($productNumber, Constants::PRODUCT_NUMBER);

        $productModule->setProperty(Constants::PRODUCT_NUMBER, $productNumber);

        $response = NetLicensingService::getInstance()
            ->post($context, Constants::PRODUCT_MODULE_ENDPOINT_PATH, $productModule->asPropertiesMap());

        $createdProductModule = null;

        if (!empty($response->items->item[0])) {
            $createdProductModule = ItemToProductModuleConverter::convert($response->items->item[0]);
            $createdProductModule->exists = true;
        }

        return $createdProductModule;
    }

    /**
     * Gets product module by its number.See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Getproductmodule
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * the product module number
     * @param string $number
     *
     * return the product module object
     * @return ProductModule|null
     * @throws MalformedArgumentsException
     * @throws RestException
     * @throws \ErrorException
     */
    public static function get(Context $context, $number)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $response = NetLicensingService::getInstance()
            ->get($context, Constants::PRODUCT_MODULE_ENDPOINT_PATH . '/' . $number);

        $productModule = null;

        if (!empty($response->items->item[0])) {
            $productModule = ItemToProductModuleConverter::convert($response->items->item[0]);
            $productModule->exists = true;
        }

        return $productModule;
    }

    /**
     * Returns all product modules of a vendor.See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Productmoduleslist
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * reserved for the future use, must be omitted / set to NULL
     * @param string $filter
     *
     * array of product modules entities or empty array if nothing found.
     * @return Page
     * @throws RestException
     * @throws \ErrorException
     */
    public static function getList(Context $context, $filter = null)
    {
        $queryParams = (!is_null($filter)) ? [Constants::FILTER => $filter] : [];

        $response = NetLicensingService::getInstance()
            ->get($context, Constants::PRODUCT_MODULE_ENDPOINT_PATH, $queryParams);

        $productModules = [];
        $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) {
                $productModule = ItemToProductModuleConverter::convert($item);
                $productModule->exists = true;

                $productModules[] = $productModule;
            }
        }

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

    /**
     * Updates product module properties.See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Updateproductmodule
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * product module number
     * @param string $number
     *
     * non-null properties will be updated to the provided values, null properties will stay unchanged.
     * @param \NetLicensing\ProductModule $productModule
     *
     * updated product module.
     * @return ProductModule|null
     * @throws MalformedArgumentsException
     * @throws RestException
     * @throws \ErrorException
     */
    public static function update(Context $context, $number, ProductModule $productModule)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $response = NetLicensingService::getInstance()
            ->post($context, Constants::PRODUCT_MODULE_ENDPOINT_PATH . '/' . $number, $productModule->asPropertiesMap());

        $updatedProductModule = null;

        if (!empty($response->items->item[0])) {
            $updatedProductModule = ItemToProductModuleConverter::convert($response->items->item[0]);
            $updatedProductModule->exists = true;
        }

        return $updatedProductModule;
    }

    /**
     * Deletes product module.See NetLicensingAPI for details:
     * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Deleteproductmodule
     *
     * determines the vendor on whose behalf the call is performed
     * @param \NetLicensing\Context $context
     *
     * product module number
     * @param string $number
     *
     * if true, any entities that depend on the one being deleted will be deleted too
     * @param bool $forceCascade
     *
     * @return bool
     * @throws MalformedArgumentsException
     * @throws \ErrorException
     * @throws RestException
     */
    public static function delete(Context $context, $number, $forceCascade = false)
    {
        CheckUtils::paramNotEmpty($number, Constants::NUMBER);

        $queryParams[Constants::CASCADE] = ((bool)$forceCascade) ? 'true' : 'false';

        return NetLicensingService::getInstance()
            ->delete($context, Constants::PRODUCT_MODULE_ENDPOINT_PATH . '/' . $number, $queryParams);
    }
}


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

namespace NetLicensing;

use Curl\Curl;

class NetLicensingCurl extends Curl
{
    public $data;
    public $query;

    /**
     * Build Post Data
     *
     * @access public
     * @param  $data
     *
     * @return array|string
     */
    public function buildPostData($data)
    {
        $this->data = $data;

        $query = parent::buildPostData($data);

        foreach ($data as $key => $value) {
            if (is_array($value)) $query = preg_replace('/&' . $key . '%5B%5D=/simU', '&' . $key . '=', $query);
        }

        $this->query = $query;

        return $query;
    }

    public function toArray()
    {
        return [
            'error' => $this->error,
            'errorCode' => $this->errorCode,
            'errorMessage' => $this->errorMessage,
            'curlError' => $this->curlError,
            'curlErrorCode' => $this->curlErrorCode,
            'curlErrorMessage' => $this->curlErrorMessage,
            'httpError' => $this->httpError,
            'httpStatusCode' => $this->httpStatusCode,
            'httpErrorMessage' => $this->httpErrorMessage,
            'baseUrl' => $this->baseUrl,
            'url' => $this->url,
            'effectiveUrl' => $this->effectiveUrl,
            'requestHeaders' => $this->requestHeaders,
            'responseHeaders' => $this->responseHeaders,
            'rawResponseHeaders' => $this->rawResponseHeaders,
            'response' => $this->response,
            'rawResponse' => $this->rawResponse,
            'data' => $this->data,
            'query' => $this->query,
        ];
    }
}


<?php
/**
 * Twitter Bootrstap Row.
 */

namespace Ease\TWB;

class Row extends \Ease\Html\DivTag
{

    /**
     * Twitter Bootrstap Row.
     *
     * @param mixed $content Prvotní obsah
     */
    public function __construct($content = null)
    {
        parent::__construct($content, ['class' => 'row']);
    }

    /**
     * Vloží do řádku políčko.
     * Add Column into Row.
     *
     * @link   http://getbootstrap.com/css/#grid
     *
     * @param int    $size       Velikost políčka 1 - 12
     * @param mixed  $content    Obsah políčka
     * @param string $target     Typ zařízení xs|sm|md|lg
     * @param array  $properties Další vlastnosti tagu
     *
     * @return Col Column contains $content
     */
    public function &addColumn($size, $content = null, $target = 'md',
                               $properties = [])
    {
        $added = $this->addItem(new Col($size, $content, $target, $properties));

        return $added;
    }
}


<?php
/**
 * Internationalization helpers
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2018 Vitex@hippy.cz (G)
 */

namespace Ease;

/**
 * Ease Locale support
 *
 * @author vitex
 */
class Locale
{
    /**
     * @var Locale Singleton is stored here
     */
    public static $_instance;

    /**
     * Current Used locale code
     * @var string
     */
    public static $localeUsed = null;

    /**
     * i18n files location
     * @var string dirpath
     */
    public static $i18n = null;

    /**
     * GetText Domain
     * @var string
     */
    public static $textDomain = null;

    /**
     * All Language Codes => languages
     * @var array
     */
    public static $alllngs = [
        "af_NA" => "Afrikaans (Namibia)",
        "af_ZA" => "Afrikaans (South Africa)",
        "af" => "Afrikaans",
        "ak_GH" => "Akan (Ghana)",
        "ak" => "Akan",
        "sq_AL" => "Albanian (Albania)",
        "sq" => "Albanian",
        "am_ET" => "Amharic (Ethiopia)",
        "am" => "Amharic",
        "ar_DZ" => "Arabic (Algeria)",
        "ar_BH" => "Arabic (Bahrain)",
        "ar_EG" => "Arabic (Egypt)",
        "ar_IQ" => "Arabic (Iraq)",
        "ar_JO" => "Arabic (Jordan)",
        "ar_KW" => "Arabic (Kuwait)",
        "ar_LB" => "Arabic (Lebanon)",
        "ar_LY" => "Arabic (Libya)",
        "ar_MA" => "Arabic (Morocco)",
        "ar_OM" => "Arabic (Oman)",
        "ar_QA" => "Arabic (Qatar)",
        "ar_SA" => "Arabic (Saudi Arabia)",
        "ar_SD" => "Arabic (Sudan)",
        "ar_SY" => "Arabic (Syria)",
        "ar_TN" => "Arabic (Tunisia)",
        "ar_AE" => "Arabic (United Arab Emirates)",
        "ar_YE" => "Arabic (Yemen)",
        "ar" => "Arabic",
        "hy_AM" => "Armenian (Armenia)",
        "hy" => "Armenian",
        "as_IN" => "Assamese (India)",
        "as" => "Assamese",
        "asa_TZ" => "Asu (Tanzania)",
        "asa" => "Asu",
        "az_Cyrl" => "Azerbaijani (Cyrillic)",
        "az_Cyrl_AZ" => "Azerbaijani (Cyrillic, Azerbaijan)",
        "az_Latn" => "Azerbaijani (Latin)",
        "az_Latn_AZ" => "Azerbaijani (Latin, Azerbaijan)",
        "az" => "Azerbaijani",
        "bm_ML" => "Bambara (Mali)",
        "bm" => "Bambara",
        "eu_ES" => "Basque (Spain)",
        "eu" => "Basque",
        "be_BY" => "Belarusian (Belarus)",
        "be" => "Belarusian",
        "bem_ZM" => "Bemba (Zambia)",
        "bem" => "Bemba",
        "bez_TZ" => "Bena (Tanzania)",
        "bez" => "Bena",
        "bn_BD" => "Bengali (Bangladesh)",
        "bn_IN" => "Bengali (India)",
        "bn" => "Bengali",
        "bs_BA" => "Bosnian (Bosnia and Herzegovina)",
        "bs" => "Bosnian",
        "bg_BG" => "Bulgarian (Bulgaria)",
        "bg" => "Bulgarian",
        "my_MM" => "Burmese (Myanmar [Burma])",
        "my" => "Burmese",
        "ca_ES" => "Catalan (Spain)",
        "ca" => "Catalan",
        "tzm_Latn" => "Central Morocco Tamazight (Latin)",
        "tzm_Latn_MA" => "Central Morocco Tamazight (Latin, Morocco)",
        "tzm" => "Central Morocco Tamazight",
        "chr_US" => "Cherokee (United States)",
        "chr" => "Cherokee",
        "cgg_UG" => "Chiga (Uganda)",
        "cgg" => "Chiga",
        "zh_Hans" => "Chinese (Simplified Han)",
        "zh_Hans_CN" => "Chinese (Simplified Han, China)",
        "zh_Hans_HK" => "Chinese (Simplified Han, Hong Kong SAR China)",
        "zh_Hans_MO" => "Chinese (Simplified Han, Macau SAR China)",
        "zh_Hans_SG" => "Chinese (Simplified Han, Singapore)",
        "zh_Hant" => "Chinese (Traditional Han)",
        "zh_Hant_HK" => "Chinese (Traditional Han, Hong Kong SAR China)",
        "zh_Hant_MO" => "Chinese (Traditional Han, Macau SAR China)",
        "zh_Hant_TW" => "Chinese (Traditional Han, Taiwan)",
        "zh" => "Chinese",
        "kw_GB" => "Cornish (United Kingdom)",
        "kw" => "Cornish",
        "hr_HR" => "Croatian (Croatia)",
        "hr" => "Croatian",
        "cs_CZ" => "Czech (Czech Republic)",
        "cs" => "Czech",
        "da_DK" => "Danish (Denmark)",
        "da" => "Danish",
        "nl_BE" => "Dutch (Belgium)",
        "nl_NL" => "Dutch (Netherlands)",
        "nl" => "Dutch",
        "ebu_KE" => "Embu (Kenya)",
        "ebu" => "Embu",
        "en_AS" => "English (American Samoa)",
        "en_AU" => "English (Australia)",
        "en_BE" => "English (Belgium)",
        "en_BZ" => "English (Belize)",
        "en_BW" => "English (Botswana)",
        "en_CA" => "English (Canada)",
        "en_GU" => "English (Guam)",
        "en_HK" => "English (Hong Kong SAR China)",
        "en_IN" => "English (India)",
        "en_IE" => "English (Ireland)",
        "en_JM" => "English (Jamaica)",
        "en_MT" => "English (Malta)",
        "en_MH" => "English (Marshall Islands)",
        "en_MU" => "English (Mauritius)",
        "en_NA" => "English (Namibia)",
        "en_NZ" => "English (New Zealand)",
        "en_MP" => "English (Northern Mariana Islands)",
        "en_PK" => "English (Pakistan)",
        "en_PH" => "English (Philippines)",
        "en_SG" => "English (Singapore)",
        "en_ZA" => "English (South Africa)",
        "en_TT" => "English (Trinidad and Tobago)",
        "en_UM" => "English (U.S. Minor Outlying Islands)",
        "en_VI" => "English (U.S. Virgin Islands)",
        "en_GB" => "English (United Kingdom)",
        "en_US" => "English (United States)",
        "en_ZW" => "English (Zimbabwe)",
        "en" => "English",
        "eo" => "Esperanto",
        "et_EE" => "Estonian (Estonia)",
        "et" => "Estonian",
        "ee_GH" => "Ewe (Ghana)",
        "ee_TG" => "Ewe (Togo)",
        "ee" => "Ewe",
        "fo_FO" => "Faroese (Faroe Islands)",
        "fo" => "Faroese",
        "fil_PH" => "Filipino (Philippines)",
        "fil" => "Filipino",
        "fi_FI" => "Finnish (Finland)",
        "fi" => "Finnish",
        "fr_BE" => "French (Belgium)",
        "fr_BJ" => "French (Benin)",
        "fr_BF" => "French (Burkina Faso)",
        "fr_BI" => "French (Burundi)",
        "fr_CM" => "French (Cameroon)",
        "fr_CA" => "French (Canada)",
        "fr_CF" => "French (Central African Republic)",
        "fr_TD" => "French (Chad)",
        "fr_KM" => "French (Comoros)",
        "fr_CG" => "French (Congo - Brazzaville)",
        "fr_CD" => "French (Congo - Kinshasa)",
        "fr_CI" => "French (Côte d’Ivoire)",
        "fr_DJ" => "French (Djibouti)",
        "fr_GQ" => "French (Equatorial Guinea)",
        "fr_FR" => "French (France)",
        "fr_GA" => "French (Gabon)",
        "fr_GP" => "French (Guadeloupe)",
        "fr_GN" => "French (Guinea)",
        "fr_LU" => "French (Luxembourg)",
        "fr_MG" => "French (Madagascar)",
        "fr_ML" => "French (Mali)",
        "fr_MQ" => "French (Martinique)",
        "fr_MC" => "French (Monaco)",
        "fr_NE" => "French (Niger)",
        "fr_RW" => "French (Rwanda)",
        "fr_RE" => "French (Réunion)",
        "fr_BL" => "French (Saint Barthélemy)",
        "fr_MF" => "French (Saint Martin)",
        "fr_SN" => "French (Senegal)",
        "fr_CH" => "French (Switzerland)",
        "fr_TG" => "French (Togo)",
        "fr" => "French",
        "ff_SN" => "Fulah (Senegal)",
        "ff" => "Fulah",
        "gl_ES" => "Galician (Spain)",
        "gl" => "Galician",
        "lg_UG" => "Ganda (Uganda)",
        "lg" => "Ganda",
        "ka_GE" => "Georgian (Georgia)",
        "ka" => "Georgian",
        "de_AT" => "German (Austria)",
        "de_BE" => "German (Belgium)",
        "de_DE" => "German (Germany)",
        "de_LI" => "German (Liechtenstein)",
        "de_LU" => "German (Luxembourg)",
        "de_CH" => "German (Switzerland)",
        "de" => "German",
        "el_CY" => "Greek (Cyprus)",
        "el_GR" => "Greek (Greece)",
        "el" => "Greek",
        "gu_IN" => "Gujarati (India)",
        "gu" => "Gujarati",
        "guz_KE" => "Gusii (Kenya)",
        "guz" => "Gusii",
        "ha_Latn" => "Hausa (Latin)",
        "ha_Latn_GH" => "Hausa (Latin, Ghana)",
        "ha_Latn_NE" => "Hausa (Latin, Niger)",
        "ha_Latn_NG" => "Hausa (Latin, Nigeria)",
        "ha" => "Hausa",
        "haw_US" => "Hawaiian (United States)",
        "haw" => "Hawaiian",
        "he_IL" => "Hebrew (Israel)",
        "he" => "Hebrew",
        "hi_IN" => "Hindi (India)",
        "hi" => "Hindi",
        "hu_HU" => "Hungarian (Hungary)",
        "hu" => "Hungarian",
        "is_IS" => "Icelandic (Iceland)",
        "is" => "Icelandic",
        "ig_NG" => "Igbo (Nigeria)",
        "ig" => "Igbo",
        "id_ID" => "Indonesian (Indonesia)",
        "id" => "Indonesian",
        "ga_IE" => "Irish (Ireland)",
        "ga" => "Irish",
        "it_IT" => "Italian (Italy)",
        "it_CH" => "Italian (Switzerland)",
        "it" => "Italian",
        "ja_JP" => "Japanese (Japan)",
        "ja" => "Japanese",
        "kea_CV" => "Kabuverdianu (Cape Verde)",
        "kea" => "Kabuverdianu",
        "kab_DZ" => "Kabyle (Algeria)",
        "kab" => "Kabyle",
        "kl_GL" => "Kalaallisut (Greenland)",
        "kl" => "Kalaallisut",
        "kln_KE" => "Kalenjin (Kenya)",
        "kln" => "Kalenjin",
        "kam_KE" => "Kamba (Kenya)",
        "kam" => "Kamba",
        "kn_IN" => "Kannada (India)",
        "kn" => "Kannada",
        "kk_Cyrl" => "Kazakh (Cyrillic)",
        "kk_Cyrl_KZ" => "Kazakh (Cyrillic, Kazakhstan)",
        "kk" => "Kazakh",
        "km_KH" => "Khmer (Cambodia)",
        "km" => "Khmer",
        "ki_KE" => "Kikuyu (Kenya)",
        "ki" => "Kikuyu",
        "rw_RW" => "Kinyarwanda (Rwanda)",
        "rw" => "Kinyarwanda",
        "kok_IN" => "Konkani (India)",
        "kok" => "Konkani",
        "ko_KR" => "Korean (South Korea)",
        "ko" => "Korean",
        "khq_ML" => "Koyra Chiini (Mali)",
        "khq" => "Koyra Chiini",
        "ses_ML" => "Koyraboro Senni (Mali)",
        "ses" => "Koyraboro Senni",
        "lag_TZ" => "Langi (Tanzania)",
        "lag" => "Langi",
        "lv_LV" => "Latvian (Latvia)",
        "lv" => "Latvian",
        "lt_LT" => "Lithuanian (Lithuania)",
        "lt" => "Lithuanian",
        "luo_KE" => "Luo (Kenya)",
        "luo" => "Luo",
        "luy_KE" => "Luyia (Kenya)",
        "luy" => "Luyia",
        "mk_MK" => "Macedonian (Macedonia)",
        "mk" => "Macedonian",
        "jmc_TZ" => "Machame (Tanzania)",
        "jmc" => "Machame",
        "kde_TZ" => "Makonde (Tanzania)",
        "kde" => "Makonde",
        "mg_MG" => "Malagasy (Madagascar)",
        "mg" => "Malagasy",
        "ms_BN" => "Malay (Brunei)",
        "ms_MY" => "Malay (Malaysia)",
        "ms" => "Malay",
        "ml_IN" => "Malayalam (India)",
        "ml" => "Malayalam",
        "mt_MT" => "Maltese (Malta)",
        "mt" => "Maltese",
        "gv_GB" => "Manx (United Kingdom)",
        "gv" => "Manx",
        "mr_IN" => "Marathi (India)",
        "mr" => "Marathi",
        "mas_KE" => "Masai (Kenya)",
        "mas_TZ" => "Masai (Tanzania)",
        "mas" => "Masai",
        "mer_KE" => "Meru (Kenya)",
        "mer" => "Meru",
        "mfe_MU" => "Morisyen (Mauritius)",
        "mfe" => "Morisyen",
        "naq_NA" => "Nama (Namibia)",
        "naq" => "Nama",
        "ne_IN" => "Nepali (India)",
        "ne_NP" => "Nepali (Nepal)",
        "ne" => "Nepali",
        "nd_ZW" => "North Ndebele (Zimbabwe)",
        "nd" => "North Ndebele",
        "nb_NO" => "Norwegian Bokmål (Norway)",
        "nb" => "Norwegian Bokmål",
        "nn_NO" => "Norwegian Nynorsk (Norway)",
        "nn" => "Norwegian Nynorsk",
        "nyn_UG" => "Nyankole (Uganda)",
        "nyn" => "Nyankole",
        "or_IN" => "Oriya (India)",
        "or" => "Oriya",
        "om_ET" => "Oromo (Ethiopia)",
        "om_KE" => "Oromo (Kenya)",
        "om" => "Oromo",
        "ps_AF" => "Pashto (Afghanistan)",
        "ps" => "Pashto",
        "fa_AF" => "Persian (Afghanistan)",
        "fa_IR" => "Persian (Iran)",
        "fa" => "Persian",
        "pl_PL" => "Polish (Poland)",
        "pl" => "Polish",
        "pt_BR" => "Portuguese (Brazil)",
        "pt_GW" => "Portuguese (Guinea-Bissau)",
        "pt_MZ" => "Portuguese (Mozambique)",
        "pt_PT" => "Portuguese (Portugal)",
        "pt" => "Portuguese",
        "pa_Arab" => "Punjabi (Arabic)",
        "pa_Arab_PK" => "Punjabi (Arabic, Pakistan)",
        "pa_Guru" => "Punjabi (Gurmukhi)",
        "pa_Guru_IN" => "Punjabi (Gurmukhi, India)",
        "pa" => "Punjabi",
        "ro_MD" => "Romanian (Moldova)",
        "ro_RO" => "Romanian (Romania)",
        "ro" => "Romanian",
        "rm_CH" => "Romansh (Switzerland)",
        "rm" => "Romansh",
        "rof_TZ" => "Rombo (Tanzania)",
        "rof" => "Rombo",
        "ru_MD" => "Russian (Moldova)",
        "ru_RU" => "Russian (Russia)",
        "ru_UA" => "Russian (Ukraine)",
        "ru" => "Russian",
        "rwk_TZ" => "Rwa (Tanzania)",
        "rwk" => "Rwa",
        "saq_KE" => "Samburu (Kenya)",
        "saq" => "Samburu",
        "sg_CF" => "Sango (Central African Republic)",
        "sg" => "Sango",
        "seh_MZ" => "Sena (Mozambique)",
        "seh" => "Sena",
        "sr_Cyrl" => "Serbian (Cyrillic)",
        "sr_Cyrl_BA" => "Serbian (Cyrillic, Bosnia and Herzegovina)",
        "sr_Cyrl_ME" => "Serbian (Cyrillic, Montenegro)",
        "sr_Cyrl_RS" => "Serbian (Cyrillic, Serbia)",
        "sr_Latn" => "Serbian (Latin)",
        "sr_Latn_BA" => "Serbian (Latin, Bosnia and Herzegovina)",
        "sr_Latn_ME" => "Serbian (Latin, Montenegro)",
        "sr_Latn_RS" => "Serbian (Latin, Serbia)",
        "sr" => "Serbian",
        "sn_ZW" => "Shona (Zimbabwe)",
        "sn" => "Shona",
        "ii_CN" => "Sichuan Yi (China)",
        "ii" => "Sichuan Yi",
        "si_LK" => "Sinhala (Sri Lanka)",
        "si" => "Sinhala",
        "sk_SK" => "Slovak (Slovakia)",
        "sk" => "Slovak",
        "sl_SI" => "Slovenian (Slovenia)",
        "sl" => "Slovenian",
        "xog_UG" => "Soga (Uganda)",
        "xog" => "Soga",
        "so_DJ" => "Somali (Djibouti)",
        "so_ET" => "Somali (Ethiopia)",
        "so_KE" => "Somali (Kenya)",
        "so_SO" => "Somali (Somalia)",
        "so" => "Somali",
        "es_AR" => "Spanish (Argentina)",
        "es_BO" => "Spanish (Bolivia)",
        "es_CL" => "Spanish (Chile)",
        "es_CO" => "Spanish (Colombia)",
        "es_CR" => "Spanish (Costa Rica)",
        "es_DO" => "Spanish (Dominican Republic)",
        "es_EC" => "Spanish (Ecuador)",
        "es_SV" => "Spanish (El Salvador)",
        "es_GQ" => "Spanish (Equatorial Guinea)",
        "es_GT" => "Spanish (Guatemala)",
        "es_HN" => "Spanish (Honduras)",
        "es_419" => "Spanish (Latin America)",
        "es_MX" => "Spanish (Mexico)",
        "es_NI" => "Spanish (Nicaragua)",
        "es_PA" => "Spanish (Panama)",
        "es_PY" => "Spanish (Paraguay)",
        "es_PE" => "Spanish (Peru)",
        "es_PR" => "Spanish (Puerto Rico)",
        "es_ES" => "Spanish (Spain)",
        "es_US" => "Spanish (United States)",
        "es_UY" => "Spanish (Uruguay)",
        "es_VE" => "Spanish (Venezuela)",
        "es" => "Spanish",
        "sw_KE" => "Swahili (Kenya)",
        "sw_TZ" => "Swahili (Tanzania)",
        "sw" => "Swahili",
        "sv_FI" => "Swedish (Finland)",
        "sv_SE" => "Swedish (Sweden)",
        "sv" => "Swedish",
        "gsw_CH" => "Swiss German (Switzerland)",
        "gsw" => "Swiss German",
        "shi_Latn" => "Tachelhit (Latin)",
        "shi_Latn_MA" => "Tachelhit (Latin, Morocco)",
        "shi_Tfng" => "Tachelhit (Tifinagh)",
        "shi_Tfng_MA" => "Tachelhit (Tifinagh, Morocco)",
        "shi" => "Tachelhit",
        "dav_KE" => "Taita (Kenya)",
        "dav" => "Taita",
        "ta_IN" => "Tamil (India)",
        "ta_LK" => "Tamil (Sri Lanka)",
        "ta" => "Tamil",
        "te_IN" => "Telugu (India)",
        "te" => "Telugu",
        "teo_KE" => "Teso (Kenya)",
        "teo_UG" => "Teso (Uganda)",
        "teo" => "Teso",
        "th_TH" => "Thai (Thailand)",
        "th" => "Thai",
        "bo_CN" => "Tibetan (China)",
        "bo_IN" => "Tibetan (India)",
        "bo" => "Tibetan",
        "ti_ER" => "Tigrinya (Eritrea)",
        "ti_ET" => "Tigrinya (Ethiopia)",
        "ti" => "Tigrinya",
        "to_TO" => "Tonga (Tonga)",
        "to" => "Tonga",
        "tr_TR" => "Turkish (Turkey)",
        "tr" => "Turkish",
        "uk_UA" => "Ukrainian (Ukraine)",
        "uk" => "Ukrainian",
        "ur_IN" => "Urdu (India)",
        "ur_PK" => "Urdu (Pakistan)",
        "ur" => "Urdu",
        "uz_Arab" => "Uzbek (Arabic)",
        "uz_Arab_AF" => "Uzbek (Arabic, Afghanistan)",
        "uz_Cyrl" => "Uzbek (Cyrillic)",
        "uz_Cyrl_UZ" => "Uzbek (Cyrillic, Uzbekistan)",
        "uz_Latn" => "Uzbek (Latin)",
        "uz_Latn_UZ" => "Uzbek (Latin, Uzbekistan)",
        "uz" => "Uzbek",
        "vi_VN" => "Vietnamese (Vietnam)",
        "vi" => "Vietnamese",
        "vun_TZ" => "Vunjo (Tanzania)",
        "vun" => "Vunjo",
        "cy_GB" => "Welsh (United Kingdom)",
        "cy" => "Welsh",
        "yo_NG" => "Yoruba (Nigeria)",
        "yo" => "Yoruba",
        "zu_ZA" => "Zulu (South Africa)",
        "zu" => "Zulu"
    ];

    /**
     * Prepare use of localization
     *
     * @param string $setLocale  en_US|cs_CZ|..
     * @param string $i18n       directory ( /usr/lib/locale/ in Debian )
     * @param string $textDomain we want use $i18n/$setLocale/LC_ALL/$textDomain.mo
     */
    public function __construct($setLocale = null, $i18n = '../i18n',
                                $textDomain = null)
    {
        if (is_null($setLocale)) {
            $setLocale = self::getPreferedLocale();
        }
        if (is_null($textDomain)) {
            if (is_null(self::$textDomain)) {
                if (defined('EASE_APPNAME')) {
                    $textDomain = strtolower(constant('EASE_APPNAME'));
                }
            } else {
                $textDomain = self::$textDomain;
            }
        }
        self::$i18n = $i18n;
        self::initializeGetText($textDomain, $setLocale, $i18n);
    }

    /**
     * Prefered Locale Code - 1) Requested 2) Session 3) Browser for WebPage or
     *                        getenv('LC_ALL') for CLI
     *
     * @return string locale code
     */
    public static function getPreferedLocale()
    {
//        $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
        if (php_sapi_name() == 'cli') {
            $locale = getenv('LC_ALL');
        } else {
            $reqLocale = self::requestLocale();
            if (is_null($reqLocale)) {
                $sesLocale = self::sessionLocale();
                if (is_null($sesLocale)) {
                    $locale = self::browserLocale();
                } else {
                    $locale = $sesLocale;
                }
            } else {
                $locale = $reqLocale;
            }
        }
        return $locale;
    }

    /**
     * Session by page GET or POST request with 'locale' field
     *
     * @return string Locale Code
     */
    public static function requestLocale()
    {
        return isset($_REQUEST) && array_key_exists('locale', $_REQUEST) ? $_REQUEST['locale']
                : null;
    }

    /**
     * Locale code saved to session field $_SESSION['locale']
     *
     * @return string locale code
     */
    public static function sessionLocale()
    {
        return isset($_SESSION) && array_key_exists('locale', $_SESSION) ? $_SESSION['locale']
                : null;
    }

    /**
     * Locale code by browser default language
     *
     * @return string locale code
     */
    public static function browserLocale()
    {
        return self::langToLocale(self::autodetected());
    }

    /**
     * List of availble locales
     *
     * @return array locales availble
     */
    public function availble()
    {
        $locales = [];
        $d       = dir(self::$i18n);
        while (false !== ($entry   = $d->read())) {
            if (($entry[0] != '.') && file_exists(self::$i18n.'/'.$entry.'/LC_MESSAGES/'.self::$textDomain.'.mo')) {
                $locales[$entry] = _(self::$alllngs[$entry]);
            }
        }
        $d->close();
        return $locales;
    }

    /**
     * Store GetText Domain
     * @param string $textDomain
     */
    public static function setTextDomain($textDomain)
    {
        self::$textDomain = $textDomain;
    }

    /**
     * Initialise Gettext
     *
     * $i18n/$defaultLocale/LC_MESSAGES/$appname.mo
     *
     * @param string $appname        name for binddomain
     * @param string $defaultLocale  locale of source code localstring
     * @param string $i18n           directory base localisation directory
     *
     * @return
     */
    public static function initializeGetText($appname, $defaultLocale = 'en_US',
                                             $i18n = '../i18n')
    {
        self::setTextDomain($appname);
        return self::useLocale($defaultLocale);
    }

    /**
     * Find Locale Code for browser language
     *
     * @param string $lang browser lan en|cs|..
     *
     * @return string locale code
     */
    public static function langToLocale($lang)
    {
        $defaultLocale = 'C';
        $langs         = [];
        foreach (self::$alllngs as $langCode => $language) {
            $langs[$langCode] = [strstr($langCode, '_') ? substr($langCode, 0,
                    strpos($langCode, '_')) : $langCode, $language];
        }
        foreach ($langs as $code => $langInfo) {
            if ($lang == $langInfo[0]) {
                $defaultLocale = $code;
                break;
            }
        }
        return $defaultLocale;
    }

    /**
     * Use Effective locale to requested
     *
     * @param string $localeCode locale code to use
     *
     * @return string used locale code
     */
    public static function useLocale($localeCode)
    {
        \setlocale(LC_ALL, $localeCode);
        \bind_textdomain_codeset(self::$textDomain, 'UTF-8');
        \putenv("LC_ALL=$localeCode");
        if (file_exists(self::$i18n)) {
            \bindtextdomain(self::$textDomain, self::$i18n);
        }
        \textdomain(self::$textDomain);
        if (isset($_SESSION)) {
            $_SESSION['locale'] = $localeCode;
        }
        self::$localeUsed = $localeCode;
    }

    /**
     * Try to autodetect default language
     *
     * @return string lang code
     */
    static public function autodetected()
    {
        return array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER) && function_exists('\locale_accept_from_http')
                ? \locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']) : null;
    }

    /**
     * Common instance of Locale class
     *
     * @return \Ease\Locale
     */
    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            $class           = __CLASS__;
            self::$_instance = new $class();
        }
        return self::$_instance;
    }
}


<?php
/**
 * EasePHP FrameWork
 *
 * @author Vítězslav Dvořák <info@vitexsoftware.cz>
 * @copyright 2018 Vitex@hippy.cz (G)
 */

namespace Ease\Logger;

/**
 * Logogger To SQL Class.
 *
 *
  CREATE TABLE `log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` varchar(255) NOT NULL COMMENT 'info|warning|error|..',
  `when` datetime NOT NULL COMMENT 'log time',
  `sender` varchar(255) NOT NULL COMMENT 'Message is Produced by',
  `message` varchar(255) NOT NULL COMMENT 'Logged message itself',
  PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8
 *
 * @author    Vitex <vitex@hippy.cz>
 * @copyright 2009-2012 Vitex@hippy.cz (G)
 */
class ToSQL extends ToStd implements Loggingable
{

    use \Ease\SQL\Orm;
    /**
     * Předvolená metoda logování.
     *
     * @var string
     */
    public $logType = 'sql';

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

    /**
     * Logovací třída.
     *
     * @param string $logName table used to save logsu
     */
    public function __construct($logName = null)
    {
        $this->keyColumn = 'id';
        $this->takemyTable(empty($logName) ? 'log' : $logName );
    }

    /**
     * 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 null|boolean byl report zapsán ?
     */
    public function addToLog($caller, $message, $type = 'message')
    {
        ++$this->messageID;
        if (($this->logLevel == 'silent') && ($type != 'error')) {
            return;
        }
        if (($this->logLevel != 'debug') && ($type == 'debug')) {
            return;
        }

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

        $this->insertToSQL([
            'status' => $type,
            'when' => 'NOW()',
            'sender' => $caller,
            'message' => $message]);

        $this->output($type, $logLine);
    }
}