From 0f4b2fb722662a897d8fc48e4d775740f3507402 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 23 Mar 2018 12:35:10 +0300 Subject: [PATCH 01/42] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 6 ++--- src/Connection/HttpResponse.php | 10 ++++---- src/Controller/Component.php | 38 ++++++++++++++++++++++++++--- src/Controller/Front.php | 6 ++--- src/Controller/Request.php | 8 ++++-- src/Controller/Service.php | 5 +++- src/Database/IdGenerator.php | 2 +- src/Database/PDOStatement.php | 2 +- src/Excel/DataTime.php | 2 +- src/Excel/Number.php | 2 +- src/Excel/Table.php | 4 +-- src/Filter/Login.php | 1 + src/Functions.php | 9 ++++--- src/Numbers.php | 3 ++- src/Path.php | 19 +++++++++------ src/Primitive.php | 6 ++--- src/Tools/Drawing.php | 3 ++- src/Tools/SQLStatementExtractor.php | 4 +-- src/Tools/String.php | 4 +-- src/Tools/TemplateImage.php | 19 +++++++++------ src/Validator/Rule/Code.php | 3 ++- src/Validator/Rule/Count.php | 2 +- src/Validator/Rule/Date.php | 1 + src/Validator/Rule/Time.php | 2 +- src/config.php | 1 + 25 files changed, 109 insertions(+), 53 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 467175e..e56b2d1 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -58,17 +58,17 @@ class Collection implements ArrayAccess public function getInt($key, $default = 0) { - return intval($this->get($key, $default)); + return (int)$this->get($key, $default); } public function getString($key, $default = '') { - return ((string) $this->get($key, $default)); + return (string)$this->get($key, $default); } public function getNat($key, $default = 1) { - $result = intval($this->get($key, $default)); + $result = (int)$this->get($key, $default); return (($result > 0) ? $result : $default); } diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 9e94c9f..df08cbc 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -36,12 +36,12 @@ class Connection_HttpResponse if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { //$this->data = substr($this->response, $this->offset); - $line = hexdec($this->getLine()); + $index = hexdec($this->getLine()); $chunk = array(); - while ($line > 0) { - $chunk [] = substr($this->response, $this->offset, $line); - $this->offset += $line; - $line = hexdec($this->getLine()); + while ($index > 0) { + $chunk [] = substr($this->response, $this->offset, $index); + $this->offset += $index; + $index = hexdec($this->getLine()); } $this->data = implode("", $chunk); diff --git a/src/Controller/Component.php b/src/Controller/Component.php index efc3cdf..dce2076 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -38,6 +38,23 @@ class ComponentRequest { } } +class FakeTemplate { + public $_data = []; + public $_name = ''; + + function __construct($name) { + $this->_name = $name; + } + + function __set($key, $value) { + $this->_data[$key] = $value; + } + + function execute() { + return $this->_data; + } +} + /** * Класс компонента */ @@ -56,6 +73,7 @@ class Controller_Component public /*.Settings.*/$registry; public /*.Database.*/$db; public /*.Collection.*/$parameter; + public $output = 'html'; public $module; public $item_module; @@ -86,6 +104,10 @@ class Controller_Component public function getView($name) { + if ($this->output == 'json') { + return new FakeTemplate($name); + } + // /*.Settings.*/$registry = $this->registry; $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); @@ -164,8 +186,18 @@ class Controller_Component return $result; } + function findFile($pathList, $name) { + foreach($pathList as $item) { + $filename = Path::join($item, $name); + if (file_exists($filename)) { + return $filename; + } + } + return null; + } + function getInfo() { - $filename = Path::join($this->viewPath[0], 'install.json'); + $filename = $this->findFile($this->viewPath, 'install.json'); if (file_exists($filename)) { $settings = json_decode(File::getContents($filename), true); return $settings; @@ -262,13 +294,13 @@ class Controller_Component } $params = new Collection(); - $params->import(array_merge($_GET, $arguments)); + $params->import($arguments); $component->parameter = $params; $component->template = $params->get('template', false); $editor = $component->getEditUrl(); if ($editor) { - if(class_exists("Controller_Site")){ //Если мы в CMS2 + if(class_exists("Controller_Site")) { //Если мы в CMS2 $instance = Controller_Site::getInstance(); $instance->componentsConfig[] = $editor; } else { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index af064ad..772d177 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -40,7 +40,7 @@ class Controller_Front extends Controller_Action * @param request $request Имя модуля * @return string */ - public function loadModule($name, Collection $request, $controller = false) + public function loadModule($name, Collection $request, $controller = null) { if ($this->isLoaded($name)) { $module = $this->modules[$name]; @@ -93,13 +93,13 @@ class Controller_Front extends Controller_Action $this->default = $name; } - public function execute(HTTPRequest $request) + public function execute(HttpRequest $request) { $name = explode("_", $request->get($this->_param, $this->default)); if (count($name) >= 2) { $controller = $name[1]; } else { - $controller = false; + $controller = null; } try{ return $this->loadModule($name[0], $request, $controller); diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 01822e1..1ac7be4 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,13 +1,17 @@ r = $request; $this->id = $id; } - function get($name) { + function get($name, $def) { $v = $this->r->get($name); + $id = $this->id; if ($id && is_array($v)) { return isset($v[$id]) ? $v[$id] : $def; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 46f96aa..64b8a59 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -5,12 +5,15 @@ */ class Controller_Service { - public $viewPath = array(); + public $viewPath = []; + public $webPath = []; public $registry; // Registry->getInstance public $template; public $templatePath; public $COMPONENTS_WEB; + public $db; + public function getTemplatePath($name) { return Path::join($this->viewPath[0], 'templates', 'modern', $name); diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 045ec86..41ee235 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -21,6 +21,6 @@ class Database_IdGenerator { } else { $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); } - return intval($result['nextval']); + return (int)$result['nextval']; } } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 1274e6e..e74a244 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -66,7 +66,7 @@ class Database_PDOStatement extends PDOStatement implements IteratorAggregate } function getInt($name) { - return intval($this->fields[$name]); + return (int)$this->fields[$name]; } function getBlob($name) { diff --git a/src/Excel/DataTime.php b/src/Excel/DataTime.php index 0536cbd..8e590d0 100644 --- a/src/Excel/DataTime.php +++ b/src/Excel/DataTime.php @@ -6,7 +6,7 @@ class Excel_DateTime function __construct($value) { - $this->value = intval($value); + $this->value = (int)$value; } function getString() diff --git a/src/Excel/Number.php b/src/Excel/Number.php index 66dd6b6..5d212fe 100644 --- a/src/Excel/Number.php +++ b/src/Excel/Number.php @@ -6,7 +6,7 @@ class Excel_Number function __construct($value) { - $this->value = intval($value); + $this->value = (int)$value; } function getString() diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 162c823..63e2f80 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -50,7 +50,7 @@ class Excel_Table function __construct() { - $this->name = "Page " . intval(self::$index ++); + $this->name = "Page " . ((int)self::$index ++); } /** @@ -230,7 +230,7 @@ class Excel_Table } else { $doc->writeAttribute('ss:Type', "Number"); } - $doc->writeCData($this->encode($value)); + $doc->writeCdata($this->encode($value)); } $doc->endElement(); $doc->endElement(); diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 70ad01d..df3476d 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -13,6 +13,7 @@ class Filter_Login extends Filter_Filter const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; public $mode = 'ajax'; + public $user; //AJAX-Реквесты для которых не требуется авторизация, потребовалось для сбора статистики public $whiteRequestList = [['module' => "requiredcontent", "action" => "getcount"], diff --git a/src/Functions.php b/src/Functions.php index 3f888e7..61b9123 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -53,7 +53,8 @@ class __partial { function apply() { $params = func_get_args(); $result = array(); - for($i = 0, $j = 0; $i < count($this->params); $i++) { + $count = count($this->params); + for($i = 0, $j = 0; $i < $count; $i++) { if ($this->params[$i] == __) { $result [] = $params[$j]; $j++; @@ -77,7 +78,8 @@ class __compose { function apply () { $params = func_get_args (); $result = call_user_func_array($this->fns[0], $params); - for ($i = 1; $i < count($this->fns); $i++) { + $count = count($this->fns); + for ($i = 1; $i < $count; $i++) { $result = call_user_func($this->fns[$i], $result); } return $result; @@ -306,7 +308,8 @@ class Functions { assert(is_int($length)); $result = array(); - for($i = 0; $i < count($array); $i += $length) { + $count = count($array); + for($i = 0; $i < $count; $i += $length) { $result [] = array_slice($array, $i, $length); } return $result; diff --git a/src/Numbers.php b/src/Numbers.php index c0a39c7..9001e4a 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -15,7 +15,8 @@ class Numbers static function prefix($prefix, array $array, $key = false) { $result = array(); - for ($i = 0; $i < count($array); $i++) { + $count = count($array); + for ($i = 0; $i < $count; $i++) { $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i]; } return $result; diff --git a/src/Path.php b/src/Path.php index ba78789..1116448 100644 --- a/src/Path.php +++ b/src/Path.php @@ -160,8 +160,9 @@ class Path // Сравнение двух путей на равентство public function equal(/*.Path.*/ $path) { - if (count($this->path) == count($path->path)) { - for ($i = 0; $i < count($this->path); $i++) { + $count = count($this->path); + if ($count == count($path->path)) { + for ($i = 0; $i < $count; $i++) { if ($this->path[$i] != $path->path[$i]) { return false; } @@ -207,8 +208,9 @@ class Path if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; - if (count($path->path) > count($this->path)) { - for ($i = 0; $i < count($this->path); $i++) { + $count = count($this->path); + if (count($path->path) > $count) { + for ($i = 0; $i < $count; $i++) { if ($path->path[$i] != $this->path[$i]) { return false; } @@ -252,15 +254,18 @@ class Path $list_path = $list->getParts(); $result = array(); - for ($i = 0; $i < count($list_path); $i++) { + $count = count($list_path); + for ($i = 0; $i < $count; $i++) { if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { break; } } - for($j = $i; $j < count($list_path); $j++) { + $list_count = count($list_path); + for($j = $i; $j < $list_count; $j++) { array_push($result, '..'); } - for($j = $i; $j < count($self_path); $j++) { + $self_count = count($self_path); + for($j = $i; $j < $self_count; $j++) { array_push($result, $self_path[$j]); } return implode("/", $result); diff --git a/src/Primitive.php b/src/Primitive.php index aec45fd..e911916 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -48,9 +48,9 @@ class Primitive { if (!empty($tmp)) { if (count($tmp) != 3) return $result; - $year = intval($tmp[2]); - $month = intval($tmp[1]); - $day = intval($tmp[0]); + $year = (int)$tmp[2]; + $month = (int)$tmp[1]; + $day = (int)$tmp[0]; if ($month != 0 && $day != 0 && $year != 0) { if (checkdate($month, $day, $year)) { diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index e13a323..e3dc6b0 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -40,7 +40,8 @@ class Tools_Drawing $first_word = true; $last_width = 0; - for ($i = 0; $i < count($words); $i++) { + $count = count($words); + for ($i = 0; $i < $count; $i++) { $item = $words[$i]; $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); $line_width = $dimensions[2] - $dimensions[0]; diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 739f6c7..61a54a3 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -111,7 +111,7 @@ class Tools_SQLStatementExtractor { if ($check === "" || $check === $string) { return true; } else { - return (strpos($string, $check) === 0) ? true : false; + return (strpos($string, $check) === 0); } } @@ -125,7 +125,7 @@ class Tools_SQLStatementExtractor { if ($check === "" || $check === $string) { return true; } else { - return (strpos(strrev($string), strrev($check)) === 0) ? true : false; + return (strpos(strrev($string), strrev($check)) === 0); } } diff --git a/src/Tools/String.php b/src/Tools/String.php index bd6c2de..ab3bab5 100644 --- a/src/Tools/String.php +++ b/src/Tools/String.php @@ -15,7 +15,7 @@ class Tools_String { if ($in_subarr > 0) { // already in sub-array? $subarr[$in_subarr][] = $tok; if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component - $res[] = strToArray(implode(',', $subarr[$in_subarr])); + $res[] = self::strToArray(implode(',', $subarr[$in_subarr])); $in_subarr--; } } elseif ($tok{0} === '{') { // we're inside a new sub-array @@ -25,7 +25,7 @@ class Tools_String { $subarr[$in_subarr] = array(); $subarr[$in_subarr][] = $tok; } else { - $res[] = strToArray($tok); + $res[] = self::strToArray($tok); } } else { // not sub-array $val = trim($tok, '"'); // remove " (surrounding strings) diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 6ce9a33..f6509ca 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -33,13 +33,16 @@ class Tools_TemplateImage protected $data = array(); protected $base = "c:\\windows\\fonts\\"; protected $image; - protected $prepare = true; + protected $_prepare = true; public $debug = false; - function __construct ($template = false) + public $resource; + public $filename; + + function __construct ($template = null) { // assert(is_string($src)); - if($template) { + if ($template) { $this->data = $template; } } @@ -116,7 +119,7 @@ class Tools_TemplateImage return ""; } - function imageText($text, $value) + function imageText($text, /*.stdClass.*/$value) { assert(is_string($text)); @@ -134,7 +137,7 @@ class Tools_TemplateImage } if ($value->valign[0]) { - $valign = Drawing::ALIGN_TOP; + $valign = Tools_Drawing::ALIGN_TOP; } elseif ($value->valign[1]) { $valign = Tools_Drawing::ALIGN_CENTER; } else { @@ -159,7 +162,7 @@ class Tools_TemplateImage { $width = imagesx($this->image); $height = imagesy($this->image); - if($new_height == false) { + if ($new_height == null) { $new_height = ceil($height * $new_width / $width); } @@ -171,8 +174,8 @@ class Tools_TemplateImage } function prepare() { - if($this->prepare) { - $this->prepare = false; + if($this->_prepare) { + $this->_prepare = false; foreach ($this->data as $value) { $this->imageText($value->text, $value); // break; } diff --git a/src/Validator/Rule/Code.php b/src/Validator/Rule/Code.php index 2bcfbf8..1928685 100644 --- a/src/Validator/Rule/Code.php +++ b/src/Validator/Rule/Code.php @@ -25,7 +25,8 @@ class Validator_Rule_Code extends Validator_Rule_Abstract $name = $this->field; if (is_array($_POST[$name . '_code_genre'])) { - for($n = 0; $n < count($_POST[$name . '_code_genre']); $n++) { + $count = count($_POST[$name . '_code_genre']); + for($n = 0; $n < $count; $n++) { $code = array( $_POST[$name . '_code_genre'][$n], $_POST[$name . '_code_f'][$n], diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 2afd612..47686b8 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -6,7 +6,7 @@ class Validator_Rule_Count extends Validator_Rule_Abstract { public $size = 1; - public $max = false; + public $max = null; public function getErrorMsg() { diff --git a/src/Validator/Rule/Date.php b/src/Validator/Rule/Date.php index be8e17e..166907a 100644 --- a/src/Validator/Rule/Date.php +++ b/src/Validator/Rule/Date.php @@ -15,6 +15,7 @@ class Validator_Rule_Date extends Validator_Rule_Abstract public function isValid(Collection $container, $status = null) { $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/"; + $matches = []; return (preg_match($pattern, $container->get($this->field), $matches) && checkdate($matches[2], $matches[1], $matches[3])); } diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 05a7a46..a64655c 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -23,7 +23,7 @@ class Validator_Rule_Time extends Validator_Rule_Abstract { $tmp = explode($this->split, $container->get($this->field), 2); if ($tmp) { - if (self::checktime ($tmp[0], $tmp[1])) { + if (self::checktime ((int)$tmp[0], (int)$tmp[1])) { return true; } } diff --git a/src/config.php b/src/config.php index 3bbc19a..86c7dfb 100644 --- a/src/config.php +++ b/src/config.php @@ -1,6 +1,7 @@ Date: Tue, 27 Mar 2018 12:23:58 +0300 Subject: [PATCH 02/42] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D1=8F=D0=B5=D0=BC=D1=81=D1=8F=20=D0=BE=D1=82=20=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D1=85=20=D0=BA?= =?UTF-8?q?=D0=BB=D0=B0=D1=81=D1=81=D0=BE=D0=B2=20=D0=B8=20=D1=81=D0=B8?= =?UTF-8?q?=D0=BD=D0=B3=D0=BB=D1=82=D0=BE=D0=BD=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 4 +-- src/Controller/Front.php | 53 +++++++++------------------- src/Filter/Login.php | 46 +++++++++---------------- src/Filter/UserAccess.php | 69 ------------------------------------- src/Registry.php | 24 ------------- src/Role/User.php | 69 +++++++++++++++++++++++++++++++++++++ src/Settings.php | 4 +-- src/Shortcut.php | 66 ----------------------------------- src/Tales.php | 72 +++++++++++++++++++++++++++++++++++++++ src/config.php | 8 ----- src/tales.php | 71 -------------------------------------- 11 files changed, 177 insertions(+), 309 deletions(-) delete mode 100644 src/Filter/UserAccess.php delete mode 100644 src/Registry.php create mode 100644 src/Role/User.php delete mode 100644 src/Shortcut.php create mode 100644 src/Tales.php delete mode 100644 src/config.php delete mode 100644 src/tales.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 6045d5b..f67f515 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -304,12 +304,12 @@ class Controller_Action /** * Добавление widget к отображению */ - public function addChild(/*Widget*/ $section, $node) + public function addChild(/*Widgets_Widget*/ $section, $node) { $this->childNodes[$section] = $node; } - public function setValue(/*Widget*/ $name, $value) + public function setValue(/*Widgets_Widget*/ $name, $value) { $this->ctrlValues[$name] = $value; } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index af064ad..d88b8f8 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -18,15 +18,12 @@ class Controller_Front extends Controller_Action * @param Settings $_registry * @param Shortcut $_shortcut */ - public function __construct(Settings $_registry, $_shortcut) // $db, $installer, $shortcut + public function __construct($db, $settings, $default) // $db, $installer, $shortcut { parent::__construct(); - $registry = $_registry; - $this->_registry = $_registry; - $this->_shortcut = $_shortcut; // $cc->newShortcut(); - - $dsn = $registry->readKey(array('system', 'dsn')); - $this->db = Database::getConnection($dsn); // $cc->newConnection(); + $this->settings = $settings; + $this->db = $db; + $this->default = $default; } public function isLoaded($name) @@ -47,34 +44,24 @@ class Controller_Front extends Controller_Action return $module->access->execute($request); } - if ($controller) { - $moduleFile = Shortcut::getUrl($this->shortcut, $name, $controller); // ModuleLoader (2) - } else { - $moduleFile = Shortcut::getUrl($this->shortcut, $name, $name); // ModuleLoader (2) - } + $basePath = $this->settings['system']->readKey(['path', 'modules']); + $moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name); $module = $this->loadClass($moduleFile, null, 'Module_'); if ($module) { // Инициализация модуля - $module->viewPath = Shortcut::getUrl('modulepath', $name); + $modPath = Path::join($basePath, $name); + $module->viewPath = $modPath; $module->name = $name; - - $module->param = $this->param; // - $module->_registry = $this->_registry; - $module->_shortcut = $this->_shortcut; - - $module->iconPath = $this->iconPath; // -> Registry - $module->themePath = $this->themePath; // -> Registry - $module->jsPath = $this->jsPath; // -> Registry + $module->settings = $this->settings; $module->db = $this->db; - // Не для всех приложений нужно вести лог действий // Ведение лога - $logger = $this->loadClass(__DIR__ . '/../Filter/ActionLogger.php', $module, 'Filter_'); - $logger->before = $this->loadSettings(Shortcut::getUrl('logger', $name)); + $logger = new Filter_ActionLogger($module); + $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом - $module->access = $this->loadClass(__DIR__ . '/../Filter/ActionAccess.php', $logger, 'Filter_'); - $module->access->access = $this->loadSettings(Shortcut::getUrl('access', $name)); + $module->access = new Filter_ActionAccess($logger); + $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); $module->setUp(); @@ -85,27 +72,19 @@ class Controller_Front extends Controller_Action return null; // throw new FileNotFoundException(); } - public function setParameter($shortcut, $param, $name) - { - $this->shortcut = $shortcut; - // Параметр - $this->_param = $param; - $this->default = $name; - } - public function execute(HTTPRequest $request) { - $name = explode("_", $request->get($this->_param, $this->default)); + $name = explode("_", $request->get('module', $this->default)); if (count($name) >= 2) { $controller = $name[1]; } else { $controller = false; } - try{ + try { return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json'){ + if($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 70ad01d..4f3b294 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -14,11 +14,11 @@ class Filter_Login extends Filter_Filter const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; public $mode = 'ajax'; - //AJAX-Реквесты для которых не требуется авторизация, потребовалось для сбора статистики - public $whiteRequestList = [['module' => "requiredcontent", "action" => "getcount"], - ['module' => "requiredcontent", "action" => "teststructure"], - ['module' => "requiredcontent", "action" => "specialdump"] - ]; + function __construct($processor, $role, $whitelist = []) { + parent::__construct($processor); + $this->role = $role; + $this->whitelist = $whitelist; + } /** * Проверка авторизации * @return Boolean Авторизовани пользователь или нет @@ -27,29 +27,18 @@ class Filter_Login extends Filter_Filter { // Авторизация session_start(); - $db = $this->getConnection(); - Filter_UserAccess::setUp($db); // Соединение switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': $login = $request->get('login'); $password = $request->get('password'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { - $userPassword = $result->getString('password'); - if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { - $s = new Settings(PARENT_PATH . '/settings.json'); - $s->read(); - $dsn = $s->readKey(array('system', 'dsn')); - - $db = Database::getConnection($dsn); - $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); - $userPassword = $user['password']; - } + $userPassword = $this->role->getUserPassword($result); // Извлечнеие пользователя из родительской CMS, для проверки пароля if (md5($password) == $userPassword) { // password - $this->enter($db, $result); + $this->enter($result); return true; } } @@ -62,7 +51,7 @@ class Filter_Login extends Filter_Filter case 'enter': $login = $request->get('login'); $password = $request->get('sid'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { @@ -76,7 +65,7 @@ class Filter_Login extends Filter_Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = Filter_UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = $role->getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } @@ -89,8 +78,7 @@ class Filter_Login extends Filter_Filter return false; } - private function getBrowserSign() - { + private function getBrowserSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; //$signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); $signParts = array(); @@ -101,15 +89,15 @@ class Filter_Login extends Filter_Filter return md5($rawSign); } - private function enter($db, $result) + private function enter($result) { $this->user = $result; $random = rand(0, 1024 * 1024); - $db->executeQuery("UPDATE users SET sid = '$random' WHERE id_user = " . $result->getInt('id_user')); + $this->role->setSID($random, $result); - $_SESSION["group"] = $result->getInt('access'); - $_SESSION["access"] = $result->getInt('id_user'); // id_user - $_SESSION["random"] = $random; // id_user + // $_SESSION["group"] = $result->getInt('access'); + $_SESSION["access"] = $result->getInt('id_user'); + $_SESSION["random"] = $random; $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = $this->getBrowserSign(); $_SESSION["time"] = time(); } @@ -122,7 +110,6 @@ class Filter_Login extends Filter_Filter $result = array(); $result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname'); $result['email'] = $this->user->getString('email'); - $result['site'] = 187; $result['hash'] = sha1(self::SESSION_BROWSER_SIGN_SECRET . $this->user->getString('email')); return json_encode($result); } else { @@ -164,7 +151,6 @@ class Filter_Login extends Filter_Filter /* --------------------- * Проверка на попадание реквеста в белый список */ - public function requestIsWhite(Collection $request, $whiteRequestList){ $module = $request->get('module'); $action = $request->get('action'); diff --git a/src/Filter/UserAccess.php b/src/Filter/UserAccess.php deleted file mode 100644 index ce27a66..0000000 --- a/src/Filter/UserAccess.php +++ /dev/null @@ -1,69 +0,0 @@ -executeQuery(); - if ($result->next()) { - self::$access = $GROUPS[$result->getString('access')]; - self::$name = $result->getString('login'); - self::$id = $result->getInt('id_user'); - self::$password = $result->getString('password'); - self::$fullname = implode(' ', array( - $result->getString('surname'), - $result->getString('firstname'), - $result->getString('patronymic'))); - return $result; - } - return null; - } - - public static function getUserByLogin($login) - { - $stmt = self::$db->prepareStatement("SELECT * FROM users WHERE login = ?"); - $stmt->setString(1, $login); - $result = self::getUserByQuery($stmt); - if ($result) { - $time = time(); - $id = self::$id; - self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа - } - return $result; - } - - public static function getUserById($id) - { - $stmt = self::$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); - $stmt->setInt(1, $_SESSION ['access']); - $result = self::getUserByQuery($stmt); - if ($result) { - $lasttime = $result->getInt('lasttime'); - $time = time(); - if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии - $id = self::$id; - self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа - } - return $result; - } -} diff --git a/src/Registry.php b/src/Registry.php deleted file mode 100644 index 5a2d871..0000000 --- a/src/Registry.php +++ /dev/null @@ -1,24 +0,0 @@ - - -/** - * http://www.patternsforphp.com/wiki/Registry - * http://www.patternsforphp.com/wiki/Singleton - * http://www.phppatterns.com/docs/design/the_registry?s=registry - */ - -class Registry extends Settings -{ - static $instance = null; - - /** - */ - static public function getInstance () - { - if (self::$instance == null) { - self::$instance = new Registry(); - } - return self::$instance; - } -} diff --git a/src/Role/User.php b/src/Role/User.php new file mode 100644 index 0000000..18f229b --- /dev/null +++ b/src/Role/User.php @@ -0,0 +1,69 @@ +db = $db; + } + + public function getUserByQuery(Database_Statement $stmt) + { + global $GROUPS; + $result = $stmt->executeQuery(); + if ($result->next()) { + $this->access = $GROUPS[$result->getString('access')]; + $this->name = $result->getString('login'); + $this->id = $result->getInt('id_user'); + $this->password = $result->getString('password'); + $this->fullname = implode(' ', array( + $result->getString('surname'), + $result->getString('firstname'), + $result->getString('patronymic'))); + return $result; + } + return null; + } + + public static function getUserByLogin($login) + { + $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE login = ?"); + $stmt->setString(1, $login); + $result = $this->getUserByQuery($stmt); + if ($result) { + $time = time(); + $id = $this->id; + $this->$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа + } + return $result; + } + + public static function getUserById($id) + { + $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); + $stmt->setInt(1, $_SESSION ['access']); + $result = $this->getUserByQuery($stmt); + if ($result) { + $lasttime = $result->getInt('lasttime'); + $time = time(); + if ($time - $lasttime > $this->LIFE_TIME) return null; // Вышло время сессии + $id = $this->$id; + $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа + } + return $result; + } +} diff --git a/src/Settings.php b/src/Settings.php index 661cbb2..cbbf9fa 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -34,7 +34,7 @@ class Settings extends Collection if ($this->format == 'json') { $settings = json_decode(File::getContents($this->file), true); } else { - include ($this->file); + $settings = include ($this->file); } if (!is_array($settings)) { @@ -165,7 +165,7 @@ class Settings extends Collection $result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else { $result = var_export($this->data, true); - $result = ""; + $result = ""; } file_put_contents (($file) ? $file : $this->file, $result); } diff --git a/src/Shortcut.php b/src/Shortcut.php deleted file mode 100644 index 4e24046..0000000 --- a/src/Shortcut.php +++ /dev/null @@ -1,66 +0,0 @@ -list[$prefix] = $path; - } - - /** - * - */ - public function addVar($name, $value) - { - $this->variables['$' . $name] = $value; - } - - /** - * Возвращает путь по имени ярлыка - */ - static function getUrl($prefix, $name = null, $name1 = null) - { - $shortcut = self::getInstance(); - - $names = $shortcut->variables; - if ($name) { - $names['$name'] = $name; - } - if ($name1) { - $names['$name1'] = $name1; - } - - if (isset($shortcut->list[$prefix])) { - return strtr($shortcut->list[$prefix], $names); - } - return null; - } - - static function expand($path) - { - $shortcut = self::getInstance(); - $names = $shortcut->variables; - return strtr($path, $names); - } - -} diff --git a/src/Tales.php b/src/Tales.php new file mode 100644 index 0000000..fb919b6 --- /dev/null +++ b/src/Tales.php @@ -0,0 +1,72 @@ +execute($req); + + echo ""; + return $result; + } + + + static function register() { + /* Регистрация нового префикса для подключения компонента */ + $tales = PHPTAL_TalesRegistry::getInstance(); + $tales->registerPrefix('component', array('Component_Tales', 'component')); + $tales->registerPrefix('date', array('DateTime_Tales', 'date')); + $tales->registerPrefix('time', array('DateTime_Tales', 'time')); + } +} diff --git a/src/config.php b/src/config.php deleted file mode 100644 index 3bbc19a..0000000 --- a/src/config.php +++ /dev/null @@ -1,8 +0,0 @@ -execute($req); - - echo ""; - return $result; -} - - -/* Регистрация нового префикса для подключения компонента */ -$tales = PHPTAL_TalesRegistry::getInstance(); -$tales->registerPrefix('component', array('Component_Tales', 'component')); -$tales->registerPrefix('date', array('DateTime_Tales', 'date')); -$tales->registerPrefix('time', array('DateTime_Tales', 'time')); - From e9f7c239902a2b8320a670bfbbd5f24e2fd0c416 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 27 Mar 2018 17:31:49 +0300 Subject: [PATCH 03/42] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D1=83=D0=BB=D0=B8=20c?= =?UTF-8?q?=20namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Adapter.php | 2 + src/Arr.php | 2 + src/Collection.php | 2 + src/Controller/Front.php | 4 +- src/Controller/Service.php | 2 +- src/Database.php | 2 +- src/Database/PDOStatement.php | 7 +++- src/Functions.php | 4 +- src/Layout/Manager.php | 4 +- src/Tales.php | 72 +++++++++++++++++++++++++++++++++++ src/tales.php | 71 ---------------------------------- 11 files changed, 92 insertions(+), 80 deletions(-) create mode 100644 src/Tales.php delete mode 100644 src/tales.php diff --git a/src/Adapter.php b/src/Adapter.php index 42bd4ab..5af0d7b 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -1,5 +1,7 @@ shortcut, $name, $name); // ModuleLoader (2) } - $module = $this->loadClass($moduleFile, null, 'Module_'); + $ucname = ucfirst($name); + $moduleClass = "Module\\$ucname\\$ucname"; + $module = new $moduleClass();//$this->loadClass($moduleFile, null, 'Module\\'); if ($module) { // Инициализация модуля $module->viewPath = Shortcut::getUrl('modulepath', $name); diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 64b8a59..43f0802 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -46,7 +46,7 @@ class Controller_Service return $model; } - public function options($key, $val, $res) { + public function options($key, $val, /*.Database_PDOStatement.*/$res) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 415619d..2d5e8ad 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,6 @@ -require_once "Database/PDOStatement.php"; +namespace ctiso; /** * Класс оболочка для PDO для замены Creole diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index e74a244..b780ae3 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,13 +1,16 @@ addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } - public function checkGet($request, $get) + public function checkGet(/*.HttpRequest.*/$request, $get) { if (is_array($get)) { foreach ($get as $key => $value) { @@ -42,7 +42,7 @@ class Layout_Manager extends Filter_Filter return true; } - public function checkXHR($request, $get) + public function checkXHR(/*.HttpRequest.*/$request, $get) { return $request->isAjax() && $this->checkGet($request, $get); } diff --git a/src/Tales.php b/src/Tales.php new file mode 100644 index 0000000..fb919b6 --- /dev/null +++ b/src/Tales.php @@ -0,0 +1,72 @@ +execute($req); + + echo ""; + return $result; + } + + + static function register() { + /* Регистрация нового префикса для подключения компонента */ + $tales = PHPTAL_TalesRegistry::getInstance(); + $tales->registerPrefix('component', array('Component_Tales', 'component')); + $tales->registerPrefix('date', array('DateTime_Tales', 'date')); + $tales->registerPrefix('time', array('DateTime_Tales', 'time')); + } +} diff --git a/src/tales.php b/src/tales.php deleted file mode 100644 index 2c9bc91..0000000 --- a/src/tales.php +++ /dev/null @@ -1,71 +0,0 @@ -execute($req); - - echo ""; - return $result; -} - - -/* Регистрация нового префикса для подключения компонента */ -$tales = PHPTAL_TalesRegistry::getInstance(); -$tales->registerPrefix('component', array('Component_Tales', 'component')); -$tales->registerPrefix('date', array('DateTime_Tales', 'date')); -$tales->registerPrefix('time', array('DateTime_Tales', 'time')); - From 32ec09a66ae5c3c84cb216347712f39ae46e1ca2 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 27 Mar 2018 17:40:33 +0300 Subject: [PATCH 04/42] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20namespace=20=D0=B8=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81?= =?UTF-8?q?=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Adapter.php | 1 + src/Arr.php | 1 + src/Collection.php | 3 ++- src/Connection/HttpRequest.php | 5 ++++- src/Connection/HttpResponse.php | 4 +++- src/Controller/Action.php | 19 +++++++++++++++---- src/Controller/Component.php | 23 ++++++++++++++++++----- src/Controller/Front.php | 10 +++++++++- src/Controller/Installer.php | 13 +++++++++---- src/Controller/Request.php | 4 +++- src/Controller/Service.php | 5 ++++- src/Controller/State.php | 11 +++++++---- src/Database.php | 8 ++++++-- src/Database/IdGenerator.php | 5 ++++- src/Database/JsonInstall.php | 7 +++++-- src/Database/Manager.php | 10 ++++++++-- src/Database/PDOStatement.php | 4 ++++ src/Database/Statement.php | 5 ++++- src/Database/StatementIterator.php | 5 ++++- src/Excel/DataTime.php | 4 +++- src/Excel/Document.php | 6 +++++- src/Excel/Number.php | 4 +++- src/Excel/Table.php | 4 +++- src/File.php | 3 +++ src/Filter/ActionAccess.php | 8 ++++++-- src/Filter/ActionLogger.php | 9 +++++++-- src/Filter/Authorization.php | 4 +++- src/Filter/Filter.php | 5 ++++- src/Filter/Login.php | 20 ++++++++++++++------ src/Filter/UserAccess.php | 8 ++++++-- src/Form/Color.php | 5 ++++- src/Form/Date.php | 5 ++++- src/Form/Field.php | 4 +++- src/Form/Form.php | 26 +++++++++++++++++--------- src/Form/Input.php | 5 ++++- src/Form/OptionFactory.php | 17 +++++++++++------ src/Form/Select.php | 5 ++++- src/Form/SelectMany.php | 5 ++++- src/Form/SelectOne.php | 5 ++++- src/Form/TextArea.php | 5 ++++- src/Form/ViewState.php | 4 +++- src/Functions.php | 18 ++++++++++-------- src/HttpRequest.php | 5 +++++ src/Layout/Empty.php | 6 +++++- src/Layout/Manager.php | 13 +++++++++---- src/Mail.php | 4 ++++ src/MailAlt.php | 3 +++ src/Model/Factory.php | 5 ++++- src/Numbers.php | 2 ++ src/Path.php | 2 ++ src/Primitive.php | 2 ++ src/Registry.php | 3 +++ src/Security.php | 2 ++ src/Session.php | 2 ++ src/Settings.php | 5 +++++ src/Setup.php | 8 ++++++-- src/Shortcut.php | 2 ++ src/SortRecord.php | 2 ++ src/Tales.php | 11 +++++++++-- src/Tools/Drawing.php | 4 +++- src/Tools/Image.php | 4 +++- src/Tools/SQLStatementExtractor.php | 5 ++++- src/Tools/String.php | 4 +++- src/Tools/TemplateImage.php | 19 +++++++++++-------- src/UTF8.php | 2 ++ src/UserMessageException.php | 3 +++ src/Validator/Rule/Abstract.php | 5 ++++- src/Validator/Rule/Alpha.php | 6 +++++- src/Validator/Rule/Code.php | 6 +++++- src/Validator/Rule/Count.php | 6 +++++- src/Validator/Rule/Date.php | 6 +++++- src/Validator/Rule/Email.php | 6 +++++- src/Validator/Rule/EmailList.php | 6 +++++- src/Validator/Rule/FileName.php | 7 ++++++- src/Validator/Rule/IsFile.php | 6 +++++- src/Validator/Rule/Match.php | 6 +++++- src/Validator/Rule/Notnull.php | 6 +++++- src/Validator/Rule/Numeric.php | 6 +++++- src/Validator/Rule/Time.php | 6 +++++- src/Validator/Rule/Unique.php | 6 +++++- src/Validator/Validator.php | 6 +++++- src/View/Composite.php | 6 +++++- src/View/List.php | 5 ++++- src/View/Page.php | 12 +++++++++--- src/View/Pages.php | 4 +++- src/View/Plain.php | 4 +++- src/View/Top.php | 5 ++++- src/View/View.php | 5 ++++- src/ZipFile.php | 3 +++ src/config.php | 3 +++ src/process.php | 2 ++ src/tabletree.php | 3 +++ 92 files changed, 454 insertions(+), 128 deletions(-) diff --git a/src/Adapter.php b/src/Adapter.php index 5af0d7b..2ba68f9 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -1,5 +1,6 @@ viewPath, 'help', $name . '.suggest'); @@ -141,7 +152,7 @@ class Controller_Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Model_Factory($this->db, $this->_registry); + $this->factory = new Factory($this->db, $this->_registry); } return $this->factory->getModel($name); } @@ -364,7 +375,7 @@ class Controller_Action function _getActionPath() { - return new Controller_State('index'); + return new State('index'); } // Тоже убрать в метод Controller_Model diff --git a/src/Controller/Component.php b/src/Controller/Component.php index dce2076..830cd59 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -1,5 +1,18 @@ db, $this->registry); + $form = new Form(); + $options = new OptionFactory($this->db, $this->registry); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); @@ -301,7 +314,7 @@ class Controller_Component $editor = $component->getEditUrl(); if ($editor) { if(class_exists("Controller_Site")) { //Если мы в CMS2 - $instance = Controller_Site::getInstance(); + $instance = Site::getInstance(); $instance->componentsConfig[] = $editor; } else { global $componentsConfig; @@ -356,7 +369,7 @@ class Controller_Component */ function addRequireJsPath($name, $path, $shim = null) { - Controller_Site::addRequireJsPath($name, $path, $shim); + Site::addRequireJsPath($name, $path, $shim); } function actionIndex(/*.ComponentRequest.*/ $request) { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 8c4ee74..7d805a8 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -4,7 +4,15 @@ * Первичный контроллер контроллер страниц * @package system.controller */ -class Controller_Front extends Controller_Action +namespace ctiso\Controller; +use ctiso\Controller\Action, + ctiso\Settings, + ctiso\Database, + ctiso\Collection, + ctiso\Shortcut, + ctiso\HttpRequest; + +class Front extends Action { /** @var Shortcut */ diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index d20a93d..a5a55fa 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -1,6 +1,11 @@ db_manager); + $json_installer = new JsonInstall($this->db_manager); foreach ($sql as $version => $install) { if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) { $file = Path::join(call_user_func($this->installPath, $name), "sql", $install); @@ -58,7 +63,7 @@ class Controller_Installer function uninstall($name){ $uninstall = $this->getUninstallFile($name); if (file_exists($uninstall)) { - $json_installer = new Database_JsonInstall($this->db_manager); + $json_installer = new JsonInstall($this->db_manager); $json_installer->install($uninstall,null); } $this->_registry->removeKey($name); @@ -108,7 +113,7 @@ class Controller_Installer } function install($dbinit_path, $dbfill_path = null) { - $json_installer = new Database_JsonInstall($this->db_manager); + $json_installer = new JsonInstall($this->db_manager); $json_installer->install($dbinit_path, $dbfill_path); } } diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 1ac7be4..50a3039 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,6 +1,8 @@ states [$state->getAction()] = $state; return $this; @@ -49,7 +52,7 @@ class Controller_State return false; } - function makeTitle(Controller_Action $module) + function makeTitle(Action $module) { foreach ($this->titles as $item) { $module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]); diff --git a/src/Database.php b/src/Database.php index 2d5e8ad..f3d0800 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,10 @@ + namespace ctiso; +use PDO, + ctiso\Database\Statement, + ctiso\Database\IdGenerator; /** * Класс оболочка для PDO для замены Creole @@ -64,7 +68,7 @@ class Database extends PDO public function prepareStatement($query) { - return new Database_Statement($query, $this); + return new Statement($query, $this); } // Для совместимости со старым представлением баз данных CIS @@ -161,7 +165,7 @@ class Database extends PDO } function getIdGenerator() { - return new Database_IdGenerator($this); + return new IdGenerator($this); } /** diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 41ee235..5ae4664 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -1,6 +1,9 @@ db_manager = $db_manager; } diff --git a/src/Database/Manager.php b/src/Database/Manager.php index ec354c7..a0e46a5 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,6 +1,12 @@ db->executeQuery($stmt); } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index b780ae3..c284683 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,6 +1,10 @@ access[$action]) || in_array(Filter_UserAccess::$access, $this->access[$action])); + return (!isset($this->access[$action]) || in_array(UserAccess::$access, $this->access[$action])); } function execute(HttpRequest $request) { diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index a71d5f5..b6da23c 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -1,6 +1,11 @@ getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . Filter_UserAccess::$name . "\n"); + fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . UserAccess::$name . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 5afd556..56ebc4d 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -1,6 +1,8 @@ getConnection(); - Filter_UserAccess::setUp($db); // Соединение + UserAccess::setUp($db); // Соединение switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': $login = $request->get('login'); $password = $request->get('password'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = UserAccess::getUserByLogin($login); // Поиск по логину if ($result) { $userPassword = $result->getString('password'); - if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { + if (UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { $s = new Settings(PARENT_PATH . '/settings.json'); $s->read(); $dsn = $s->readKey(array('system', 'dsn')); @@ -63,7 +71,7 @@ class Filter_Login extends Filter_Filter case 'enter': $login = $request->get('login'); $password = $request->get('sid'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = UserAccess::getUserByLogin($login); // Поиск по логину if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { @@ -77,7 +85,7 @@ class Filter_Login extends Filter_Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = Filter_UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } diff --git a/src/Filter/UserAccess.php b/src/Filter/UserAccess.php index ce27a66..509b9b6 100644 --- a/src/Filter/UserAccess.php +++ b/src/Filter/UserAccess.php @@ -1,7 +1,11 @@ executeQuery(); diff --git a/src/Form/Color.php b/src/Form/Color.php index c7c0d2d..17a9caf 100644 --- a/src/Form/Color.php +++ b/src/Form/Color.php @@ -3,6 +3,9 @@ /** * Поле с цветом */ -class Form_Color extends Form_Field +namespace ctiso\Form; +use ctiso\Form\Field; + +class Color extends Field { } \ No newline at end of file diff --git a/src/Form/Date.php b/src/Form/Date.php index 42f8b00..3b1c526 100644 --- a/src/Form/Date.php +++ b/src/Form/Date.php @@ -2,5 +2,8 @@ /** * Поле с датой */ -class Form_Date extends Form_Field { +namespace ctiso\Form; +use ctiso\Form\Field; + +class Date extends Field { } \ No newline at end of file diff --git a/src/Form/Field.php b/src/Form/Field.php index bb756cb..1e1dd47 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -2,7 +2,9 @@ /** * Элемент формы */ -class Form_Field +namespace ctiso\Form; + +class Field { public $hidden = false; public $name; diff --git a/src/Form/Form.php b/src/Form/Form.php index 47a1854..02e6e7e 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -4,7 +4,15 @@ * При рендеринге каждому классу соответствует шаблон (см. themes/maxim/templates/macros.html) */ -class TCheckbox extends Form_Field +namespace ctiso\Form; +use ctiso\Form\Field, + ctiso\Form\Select, + ctiso\Form\Input, + ctiso\View\View, + ctiso\Validator\Validator, + ctiso\HttpRequest; + +class TCheckbox extends Field { public $checked = false; function setValue($value) @@ -14,7 +22,7 @@ class TCheckbox extends Form_Field } } -class TQuestionType extends Form_Select +class TQuestionType extends Select { function setValue($value) { @@ -26,29 +34,29 @@ class TQuestionType extends Form_Select } } -class TDateTime extends Form_Input { +class TDateTime extends Input { } /** * Поле для ввода пароля */ -class TSecret extends Form_Field { +class TSecret extends Field { } -class TUpload extends Form_Field { +class TUpload extends Field { } -class THidden extends Form_Input { +class THidden extends Input { public $hidden = true; } -class TComponentBrowserInput extends Form_Input { +class TComponentBrowserInput extends Input { } /** * Форма для ввода */ -class Form_Form extends View_View { +class Form extends View { public $field = array(); //Поля формы public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам @@ -163,7 +171,7 @@ class Form_Form extends View_View { /** * Устанавливает ошибки после проверки */ - function setError(Validator_Validator $validator) + function setError(Validator $validator) { foreach ($validator->getErrorMsg() as $name => $error) { diff --git a/src/Form/Input.php b/src/Form/Input.php index 855bec2..b2d4e68 100644 --- a/src/Form/Input.php +++ b/src/Form/Input.php @@ -3,5 +3,8 @@ /** * Поле ввода Input */ -class Form_Input extends Form_Field { +namespace ctiso\Form; +use ctiso\Form\Field; + +class Input extends Field { } \ No newline at end of file diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 41a8447..70904bb 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -1,6 +1,11 @@ registry = $registry; } - function create(Form_Select $field, $input) { + function create(Select $field, $input) { if (isset($input['options.resid'])) { $type = $input['options.resid']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); } else if (isset($input['options.res'])) { $type = $input['options.res']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); } else if (isset($input['options.all_res'])) { $type = $input['options.all_res']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); } else if (isset($input['options.db'])) { @@ -39,7 +44,7 @@ class Form_OptionFactory { } elseif (isset($input['options.pair'])) { $field->options = $this->optionsPair($input['options.pair']); } elseif (isset($input['options.model'])) { - $factory = new Model_Factory($this->db, $this->registry); + $factory = new Factory($this->db, $this->registry); $model = $factory->getModel($input['options.model']); $field->options = $model->getAllAsOptions(); } else { diff --git a/src/Form/Select.php b/src/Form/Select.php index 6a3f7a1..3a4ec2c 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -1,6 +1,9 @@ value = $value; diff --git a/src/Form/ViewState.php b/src/Form/ViewState.php index 777618b..c9c6831 100644 --- a/src/Form/ViewState.php +++ b/src/Form/ViewState.php @@ -4,7 +4,9 @@ * http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html * Управление состоянием между страницами */ -class Form_ViewState // extends Collection +namespace ctiso\Form; + +class ViewState // extends Collection { private $values = array(); diff --git a/src/Functions.php b/src/Functions.php index 63c131e..fc1d5a8 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -8,7 +8,9 @@ /** * Эмуляция каррированой функции */ -class __right { +namespace ctiso; + +class right { protected $params; protected $fn; @@ -24,7 +26,7 @@ class __right { } } -class __left { +class left { protected $params; protected $fn; @@ -41,7 +43,7 @@ class __left { } define('__', '_ARGUMENT_PLACE_'); -class __partial { +class partial { protected $params; protected $fn; @@ -69,7 +71,7 @@ class __partial { /** * Композиция функций */ -class __compose { +class compose { protected $fns; function __construct($list) { $this->fns = array_reverse($list); @@ -89,7 +91,7 @@ class __compose { class Functions { static function partial($_rest) { - $closure = new __partial(func_get_args()); + $closure = new partial(func_get_args()); return array($closure, 'apply'); } @@ -102,7 +104,7 @@ class Functions { * @return array[int]mixed */ static function compose($_rest) { - $closure = new __compose(func_get_args()); + $closure = new compose(func_get_args()); return array($closure, 'apply'); } @@ -112,7 +114,7 @@ class Functions { * @return array[int]mixed */ static function rcurry($_rest) { - $closure = new __right(func_get_args ()); + $closure = new right(func_get_args ()); return array($closure, 'apply'); } @@ -122,7 +124,7 @@ class Functions { * @return array[int]mixed */ static function lcurry($_rest) { - $closure = new __left(func_get_args ()); + $closure = new left(func_get_args ()); return array($closure, 'apply'); } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 7693177..21efe01 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -3,6 +3,11 @@ /** * Неверный запрос */ +namespace ctiso; +use Exception, + ctiso\Collection, + ctiso\Session; + class WrongRequestException extends Exception { } diff --git a/src/Layout/Empty.php b/src/Layout/Empty.php index a7f99b8..202f0d2 100644 --- a/src/Layout/Empty.php +++ b/src/Layout/Empty.php @@ -3,7 +3,11 @@ /** * Самый простой макет */ -class Layout_Empty extends Filter_Filter +namespace ctiso\Layout; +use ctiso\Filter\Filter, + ctiso\HttpRequest; + +class Empty extends Filter { function execute(HttpRequest $request) { diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 33b934a..63ccb0a 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -4,7 +4,12 @@ * Выбор макета страницы. * Выбор оформления страницы осуществляется если было совпадение с каким либо условием */ -class Layout_Manager extends Filter_Filter +namespace ctiso\Layout; +use ctiso\Filter\Filter, + ctiso\Functions, + ctiso\HttpRequest; + +class Manager extends Filter { // Массив условий с их макетами protected $condition = array(); @@ -17,7 +22,7 @@ class Layout_Manager extends Filter_Filter * addConditionGet(array('module' => 'personal'), 'personal') * addConditionGet(array('module' => 'login'), 'login') */ - public function addConditionGet($get, Filter_Filter $layout) + public function addConditionGet($get, Filter $layout) { $this->addCondition(Functions::rcurry(array($this, 'checkGet'), $get), $layout); } @@ -25,7 +30,7 @@ class Layout_Manager extends Filter_Filter /** * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax */ - public function addConditionXHR($get, Filter_Filter $layout) + public function addConditionXHR($get, Filter $layout) { $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } @@ -52,7 +57,7 @@ class Layout_Manager extends Filter_Filter * @parma $get function(HttpRequest) Функция * @parma $layout Layout Макет */ - public function addCondition($get, Filter_Filter $layout) + public function addCondition($get, Filter $layout) { $this->condition [] = array($get, $layout); } diff --git a/src/Mail.php b/src/Mail.php index 1f4eda4..20cdb7c 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -4,6 +4,10 @@ * Класс для работы с почтой * http://en.wikipedia.org/wiki/MIME */ +namespace ctiso; +use ctiso\Path, + Exception; + class Mail { public $_from; diff --git a/src/MailAlt.php b/src/MailAlt.php index 99b296d..138ae94 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -1,5 +1,8 @@ executeActions('install'); * */ +namespace ctiso; +use ZipArchive, + ctiso\Tools\SQLStatementExtractor; + class Setup { protected $actions = array(); @@ -198,7 +202,7 @@ class Setup */ function batchSQLZip(/*.Database.*/ $conn, $file) { - $stmtList = Tools_SQLStatementExtractor::extract($this->zip->getFromName($file)); + $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { $conn->executeQuery ($stmt); } @@ -206,7 +210,7 @@ class Setup static function batchSQL(/*.Database.*/ $conn, $file) { - $stmtList = Tools_SQLStatementExtractor::extractFile($file); + $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { $conn->executeQuery ($stmt); } diff --git a/src/Shortcut.php b/src/Shortcut.php index 4e24046..09da63f 100644 --- a/src/Shortcut.php +++ b/src/Shortcut.php @@ -3,6 +3,8 @@ /** * Класс для короткого доступа к файлам / папкам */ +namespace ctiso; + class Shortcut { static $instance = null; diff --git a/src/SortRecord.php b/src/SortRecord.php index 24c054b..030bb52 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -1,5 +1,7 @@ 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); static $listfonts = array( @@ -129,22 +132,22 @@ class Tools_TemplateImage $color = intval(substr($value->color, 1), 16); if ($value->align[0]) { - $align = Tools_Drawing::ALIGN_LEFT; + $align = Drawing::ALIGN_LEFT; } elseif ($value->align[2]) { - $align = Tools_Drawing::ALIGN_RIGHT; + $align = Drawing::ALIGN_RIGHT; } else { - $align = Tools_Drawing::ALIGN_CENTER; + $align = Drawing::ALIGN_CENTER; } if ($value->valign[0]) { - $valign = Tools_Drawing::ALIGN_TOP; + $valign = Drawing::ALIGN_TOP; } elseif ($value->valign[1]) { - $valign = Tools_Drawing::ALIGN_CENTER; + $valign = Drawing::ALIGN_CENTER; } else { - $valign = Tools_Drawing::ALIGN_BOTTOM; + $valign = Drawing::ALIGN_BOTTOM; } - Tools_Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, + Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, $value->width, $value->height, $align, $valign); } diff --git a/src/UTF8.php b/src/UTF8.php index 3cc68b8..fe97742 100644 --- a/src/UTF8.php +++ b/src/UTF8.php @@ -1,5 +1,7 @@ Date: Tue, 27 Mar 2018 18:10:46 +0300 Subject: [PATCH 05/42] =?UTF-8?q?=D0=9D=D0=B0=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D0=B9=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20composer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 4 ++-- src/Controller/Front.php | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index de9a023..4c325c2 100644 --- a/composer.json +++ b/composer.json @@ -8,8 +8,8 @@ } ], "autoload": { - "psr-0": { - "": "src/" + "psr-4": { + "ctiso\\": "src/" } } } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 7d805a8..9b5e718 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -111,11 +111,12 @@ class Front extends Action } else { $controller = null; } + try{ return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json'){ + if ($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; From f0414885543232bf0f4e80fc5eb286f79f5cd9ae Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 12:43:06 +0300 Subject: [PATCH 06/42] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D1=8F=D0=B5=D0=BC=D1=81=D1=8F=20=D0=BE=D1=82=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D0=B0=D0=BD=D1=82=20=D0=B8=20=D0=B3=D0=BB?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 21 +++++++++++++-------- src/Controller/Front.php | 23 ++++++++++++----------- src/Database.php | 2 +- src/Database/PDOStatement.php | 6 ++---- src/Filter/ActionLogger.php | 12 ++++++------ src/Filter/Filter.php | 2 +- src/Filter/Login.php | 2 +- src/HttpRequest.php | 1 + src/Layout/{Empty.php => Blank.php} | 2 +- src/Layout/Manager.php | 1 + 10 files changed, 39 insertions(+), 33 deletions(-) rename src/Layout/{Empty.php => Blank.php} (90%) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 300eb99..d833f55 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -52,7 +52,6 @@ class Action public $param = array(); // Параметры для ссылки public /*.Registry.*/$_registry; // Ссылка на реестр - public $_shortcut; public $modulePrefix = ''; public $iconPath = ''; @@ -69,10 +68,12 @@ class Action } public function loadConfig($name) { - $filename = Shortcut::getUrl('config', $name); + $basePath = $this->settings['base']; + + $filename = Path::join($basePath, 'modules', $name); $settings = []; if (file_exists($filename)) { - include($filename); + $settings = include($filename); } else { throw new Exception('Невозможно загрузить файл настроек ' . $name); } @@ -86,7 +87,8 @@ class Action public function installPath($name) { - return Path::join(CMS_PATH, "modules", $name); + $basePath = $this->settings['base']; + return Path::join($basePath, "modules", $name); } public function addSuggest(View $view, $name) @@ -110,13 +112,16 @@ class Action * @param $viewClass String * @return View_Composite */ - public function getView($name, $viewClass = 'View_Composite') + public function getView($name, $viewClass = 'ctiso\\View\\Composite') { $file = $name . self::TEMPLATE_EXTENSION; + $basePath = $this->settings['base']; + $webPath = $this->settings['web']; + $list = array( - Path::join($this->viewPath, TEMPLATES, $this->viewPathPrefix) => Path::join(WWW_PATH, "modules", $this->name, TEMPLATES, $this->viewPathPrefix), - Path::join(CMS_PATH, "templates") => Path::join(WWW_PATH, "templates") + Path::join($this->viewPath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), + Path::join($basePath, "templates") => Path::join($webPath, "templates") ); // Поиск файла для шаблона @@ -127,7 +132,7 @@ class Action /*.View_Composite.*/$tpl = new $viewClass($template); - $assets = Path::join(enableHttps(WWW_PATH), "assets", "css"); + $assets = Path::join($webPath, "assets", "css"); $tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы $tpl->set('media', $this->themePath); // Путь к файлам текущей темы $tpl->set('assets', $assets); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index f2ff867..5453892 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -11,28 +11,26 @@ use ctiso\Controller\Action, ctiso\Collection, ctiso\Filter\ActionAccess, ctiso\Filter\ActionLogger, - ctiso\Path; + ctiso\Path, ctiso\UserMessageException, ctiso\HttpRequest; class Front extends Action { - /** @var Shortcut */ - protected $shortcut; // Ярлык к модулю protected $_param; // Параметр по которому выбирается модуль protected $default; // Значение параметра по умолчанию protected $modules = array(); /** - * @param Settings $_registry - * @param Shortcut $_shortcut + * @param Settings $settings */ - public function __construct($db, $settings, $default) { + public function __construct($db, $settings, $user, $default) { parent::__construct(); $this->settings = $settings; $this->db = $db; + $this->user = $user; $this->default = $default; } @@ -52,23 +50,26 @@ class Front extends Action $module = $this->modules[$name]; return $module->access->execute($request); } + + $system = $this->settings['system']; - $basePath = $this->settings['system']->readKey(['path', 'modules']); - $moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name); + $moulesPath = $system->readKey(['path', 'modules']); + $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); + $moduleFile = Path::join($this->settings['base'], $moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); - $moduleClass = "Module\\$ucname\\$ucname"; + $moduleClass = "Modules\\$ucname\\$ucname"; $module = new $moduleClass(); if ($module) { // Инициализация модуля - $modPath = Path::join($basePath, $name); + $modPath = Path::join($moulesPath, $name); $module->viewPath = $modPath; $module->name = $name; // $module->settings = $this->settings; $module->db = $this->db; // Ведение лога - $logger = new ActionLogger($module); + $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом $module->access = new ActionAccess($logger); diff --git a/src/Database.php b/src/Database.php index f3d0800..cd196f8 100644 --- a/src/Database.php +++ b/src/Database.php @@ -17,7 +17,7 @@ class Database extends PDO { parent::__construct($dsn, $username, $password); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Database_PDOStatement', array())); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); } public function getDSN() diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index c284683..48e591a 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,11 +1,9 @@ processor = $processor; - $this->file = fopen(Shortcut::getUrl('access.log'), "a"); + $this->user = $user; + $this->file = fopen($logPath, "a"); } function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . UserAccess::$name . "\n"); + fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . $this->user->name . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 233a9f3..b61b5c8 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -19,7 +19,7 @@ class Filter return $this->processor->execute($request); } - public function getView($name, $class = 'View_Top') + public function getView($name, $class = 'ctiso\\View\\Top') { return $this->processor->getView($name, $class); } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 92f0b47..6e5f242 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -74,7 +74,7 @@ class Login extends Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = $role->getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = $this->role->getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 21efe01..f88fb0c 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -5,6 +5,7 @@ */ namespace ctiso; use Exception, + ArrayAccess, ctiso\Collection, ctiso\Session; diff --git a/src/Layout/Empty.php b/src/Layout/Blank.php similarity index 90% rename from src/Layout/Empty.php rename to src/Layout/Blank.php index 202f0d2..f731df3 100644 --- a/src/Layout/Empty.php +++ b/src/Layout/Blank.php @@ -7,7 +7,7 @@ namespace ctiso\Layout; use ctiso\Filter\Filter, ctiso\HttpRequest; -class Empty extends Filter +class Blank extends Filter { function execute(HttpRequest $request) { diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 63ccb0a..884fb3b 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -67,6 +67,7 @@ class Manager extends Filter */ public function execute(HttpRequest $request) { +// print_r($request->get('mode')); foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { $layout = $condition[1]; From 0b66a724846f85fd10c73d5a07e0563b1f8da8c1 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 17:02:20 +0300 Subject: [PATCH 07/42] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database.php | 19 +++++++++++-------- src/Role/User.php | 6 ++++-- src/Tales.php | 9 +++++---- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/Database.php b/src/Database.php index cd196f8..0a8e103 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,7 +1,15 @@ -namespace ctiso; +namespace { + if(!function_exists('sqliteLower')){ + function sqliteLower($str) { + return mb_strtolower($str, 'UTF-8'); + } + } +} + +namespace ctiso { use PDO, ctiso\Database\Statement, ctiso\Database\IdGenerator; @@ -45,13 +53,7 @@ class Database extends PDO $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); - - if(!function_exists('sqliteLower')){ - function sqliteLower($str) { - return mb_strtolower($str, 'UTF-8'); - } - $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); - } + $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); } $connection->dsn = $dsn; return $connection; @@ -183,3 +185,4 @@ class Database extends PDO return null; } } +} \ No newline at end of file diff --git a/src/Role/User.php b/src/Role/User.php index 53dd441..d287543 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -1,6 +1,6 @@ db = $db; + $this->groups = $groups; } public function setDB(Database $db) { diff --git a/src/Tales.php b/src/Tales.php index 32b0533..c3f2155 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -8,9 +8,10 @@ use PHPTAL_Php_TalesInternal, ctiso\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest, + PHPTAL_Tales, PHPTAL_TalesRegistry; -class Tales_DateTime_ implements PHPTAL_Tales +class Tales_DateTime implements PHPTAL_Tales { static public function date($expression, $nothrow = false) { return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")"; @@ -68,8 +69,8 @@ class Tales { /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); - $tales->registerPrefix('component', array('ctiso\\Component_Tales', 'component')); - $tales->registerPrefix('date', array('ctiso\\DateTime_Tales', 'date')); - $tales->registerPrefix('time', array('ctiso\\DateTime_Tales', 'time')); + $tales->registerPrefix('component', array('ctiso\\Tales_Component', 'component')); + $tales->registerPrefix('date', array('ctiso\\Tales_DateTime', 'date')); + $tales->registerPrefix('time', array('ctiso\\Tales_DateTime', 'time')); } } From bef71657770712200f364775aab62f083efdfc9f Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 19:06:30 +0300 Subject: [PATCH 08/42] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B8=D0=BD=D0=B8=D1=86=D0=B8=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8E=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 43 ++++++++++++++++++++------------------- src/Controller/Front.php | 7 ++++--- src/Filter/Login.php | 1 - src/Role/User.php | 21 ++++++++++++------- 4 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index d833f55..e549f9a 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -28,15 +28,14 @@ class Action const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const ACTION_PREFIX = "action"; // Префикс для функций действий - public $jsPath; // Глобальный путь к скриптам - public $themePath; // Глобальный путь к текущей теме - // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля - public $viewPath = null; // Путь к шаблонам контроллера - public $viewPathPrefix = null; // Путь к шаблонам контроллера - public $moduleTitle = ""; + public $modulePath = null; // Путь к модулю + public $moduleTitle = ''; + public $modulePrefix = ''; + + public $viewPathPrefix = null; // Путь к шаблонам контроллера /** * Соединение с базой данных @@ -49,11 +48,10 @@ class Action private $factory = null; // Ссылка на обьект создания модели private $helpers = array(); // Помошники для действий - public $param = array(); // Параметры для ссылки + public $param = array(); // Параметры для ссылки - public /*.Registry.*/$_registry; // Ссылка на реестр - public $modulePrefix = ''; - public $iconPath = ''; + public /*.Settings.*/$settings; // Ссылка на настройки + public $user; // Обьект пользователя // Для Widgets public $view = null; @@ -94,7 +92,7 @@ class Action public function addSuggest(View $view, $name) { $suggest = array(); - $file = Path::join($this->viewPath, 'help', $name . '.suggest'); + $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { include($file); $view->suggestions = $suggest; @@ -103,7 +101,8 @@ class Action function findIcon($icon, $size) { - return Path::join($this->iconPath, $size . 'x' . $size, $icon . '.png'); + $webPath = $this->settings['web']; + return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } /** @@ -120,7 +119,7 @@ class Action $webPath = $this->settings['web']; $list = array( - Path::join($this->viewPath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), + Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), Path::join($basePath, "templates") => Path::join($webPath, "templates") ); @@ -132,17 +131,19 @@ class Action /*.View_Composite.*/$tpl = new $viewClass($template); - $assets = Path::join($webPath, "assets", "css"); - $tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы - $tpl->set('media', $this->themePath); // Путь к файлам текущей темы - $tpl->set('assets', $assets); - $tpl->set('script', $this->jsPath); // Путь к файлам скриптов + $stylePath = Path::join($webPath, "assets", "css"); + $iconsPath = Path::join($webPath, 'icons'); + $scriptPath = Path::join($webPath, 'assets'); + + $tpl->set('icons', $iconsPath); // Путь к файлам текущей темы + $tpl->set('assets', $stylePath); + $tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('template', $path); // Путь к файлам текущего шаблона $tpl->setAlias(array( - 'assets' => $assets, - 'icons' => $this->iconPath, - 'script' => $this->jsPath, + 'assets' => $stylePath, + 'icons' => $iconsPath, + 'script' => $scriptPath, // Для media и template поиск происходит как для файлов шаблонов 'media' => $list, 'template' => $list diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 5453892..b9fa014 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -53,9 +53,9 @@ class Front extends Action $system = $this->settings['system']; - $moulesPath = $system->readKey(['path', 'modules']); + $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); - $moduleFile = Path::join($this->settings['base'], $moulesPath, $name, 'classes', $controller ? $controller : $name); + $moduleFile = Path::join($moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); $moduleClass = "Modules\\$ucname\\$ucname"; @@ -63,11 +63,12 @@ class Front extends Action if ($module) { // Инициализация модуля $modPath = Path::join($moulesPath, $name); - $module->viewPath = $modPath; + $module->modulePath = $modPath; $module->name = $name; // $module->settings = $this->settings; $module->db = $this->db; + $module->user = $this->user; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 6e5f242..eb94070 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -41,7 +41,6 @@ class Login extends Filter $login = $request->get('login'); $password = $request->get('password'); - $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { $userPassword = $this->role->getUserPassword($result); diff --git a/src/Role/User.php b/src/Role/User.php index d287543..f199363 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -43,31 +43,38 @@ class User return null; } - public static function getUserByLogin($login) + function getUserPassword($result) { + return $result->get('password'); + } + + public function getUserByLogin($login) { - $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE login = ?"); + $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt->setString(1, $login); $result = $this->getUserByQuery($stmt); if ($result) { $time = time(); $id = $this->id; - $this->$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа + $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа } return $result; } - public static function getUserById($id) + public function getUserById($id) { - $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); + $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); $stmt->setInt(1, $_SESSION ['access']); $result = $this->getUserByQuery($stmt); if ($result) { $lasttime = $result->getInt('lasttime'); $time = time(); - if ($time - $lasttime > $this->LIFE_TIME) return null; // Вышло время сессии - $id = $this->$id; + if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии + $id = $this->id; $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа } return $result; } + + function setSID() { + } } From ee06f1febbe4d40b102d0a6e249fd99e3b26c32a Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 3 Apr 2018 14:35:20 +0300 Subject: [PATCH 09/42] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 48 ++++++------------------ src/Model/Factory.php | 3 +- src/Tools/{String.php => StringUtil.php} | 2 +- src/Url.php | 13 +++++++ 4 files changed, 26 insertions(+), 40 deletions(-) rename src/Tools/{String.php => StringUtil.php} (99%) create mode 100644 src/Url.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index e549f9a..750b25e 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -4,6 +4,7 @@ namespace ctiso\Controller; use ctiso\Shortcut, Exception, ctiso\Path, + ctiso\Url, ctiso\View\View, ctiso\Model\Factory, ctiso\HttpRequest, @@ -11,14 +12,6 @@ use ctiso\Shortcut, ctiso\Settings, ctiso\Controller\State; -function forceUrl($name) -{ - if (is_callable($name)) { - return call_user_func($name); - } - return $name; -} - /** * Контроллер страниц */ @@ -158,7 +151,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->_registry); + $this->factory = new Factory($this->db, $this->settings['registry']); } return $this->factory->getModel($name); } @@ -170,7 +163,7 @@ class Action * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * @param $request Обьект запроса */ - public function preprocess(HttpRequest $request) + public function preProcess(HttpRequest $request) { $action = self::ACTION_PREFIX . ucfirst($request->getAction()); if (!method_exists($this, $action)) { @@ -186,7 +179,7 @@ class Action public function execute(HttpRequest $request) { - $result = $this->preprocess($request); + $result = $this->preProcess($request); if (!empty($result)) { $this->view = $result; } @@ -206,15 +199,6 @@ class Action return ""; } - public function postUrl($name, $param) - { - $uri = array_merge(array('module' => - strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), "action" => $name), - $this->param, $param); - - return "?" . http_build_query($uri); - } - /** * Генерация ссылки c учетом прав пользователя на ссылки * @param string $name Действие @@ -227,24 +211,14 @@ class Action /*.Filter_ActionAccess.*/$access = $this->access; if ($access == null || $access->checkAction($name)) { - return Functions::lcurry(array($this, 'postUrl'), $name, $param); - } - return null; - } + $param = array_merge(array( + 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), + "action" => $name + ), $param); - public function fUrl($name, array $param = array()) - { - return forceUrl($this->nUrl($name, $param)); - } - - /** - * Добавляет параметр для всех ссылок создаваемых функцией nUrl, aUrl - */ - public function addParameter($name, $value) - { - if ($value) { - $this->param [$name] = $value; + return new Url($param); } + return new Url(); } /** @@ -259,7 +233,7 @@ class Action */ public function aUrl($name, array $param = array()) { - return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); // FIXME + return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); } /** diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 38ed7b7..868da5a 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -8,7 +8,6 @@ class Factory static $shortcut = "model"; public $db; public $_registry; - public $_shortcut; public function __construct (/*.Database.*/ $db, Settings $_registry = null) { @@ -23,7 +22,7 @@ class Factory */ public function getModel ($name) { - $modelName = "Mapper_" . $name; + $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); $model->db = $this->db; $model->factory = $this; diff --git a/src/Tools/String.php b/src/Tools/StringUtil.php similarity index 99% rename from src/Tools/String.php rename to src/Tools/StringUtil.php index bda7385..8d07048 100644 --- a/src/Tools/String.php +++ b/src/Tools/StringUtil.php @@ -2,7 +2,7 @@ namespace ctiso\Tools; -class String { +class StringUtil { // from creole static function strToArray($str) { diff --git a/src/Url.php b/src/Url.php new file mode 100644 index 0000000..3137d16 --- /dev/null +++ b/src/Url.php @@ -0,0 +1,13 @@ +parts = $parts; + } + + function toString() { + return '?' . http_build_query($this->parts); + } +} \ No newline at end of file From 524b27936a0d2febd01a32bd9dc7bdf5f098d2ba Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 13 Apr 2018 17:59:57 +0300 Subject: [PATCH 10/42] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20na?= =?UTF-8?q?mespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ComponentRequest.php | 35 ++++++++++++++ src/Controller/Action.php | 36 +++++++------- src/Controller/Component.php | 48 +++++-------------- src/Controller/Front.php | 2 +- src/Controller/Request.php | 1 + src/Controller/Service.php | 5 +- src/Database.php | 18 ++++--- src/Database/PDOStatement.php | 3 +- src/Database/Statement.php | 5 +- src/Database/StatementIterator.php | 4 +- src/Excel/Table.php | 2 +- src/Filter/ActionAccess.php | 4 +- src/Filter/ActionLogger.php | 2 +- src/Filter/Filter.php | 6 ++- src/Filter/Login.php | 5 +- src/Form/OptionFactory.php | 2 +- src/Model/Factory.php | 3 +- src/Setup.php | 2 +- src/Tales.php | 4 +- src/Tools/TemplateImage.php | 2 +- src/Url.php | 2 + .../Rule/{Abstract.php => AbstractRule.php} | 4 +- src/Validator/Rule/Alpha.php | 4 +- src/Validator/Rule/Code.php | 4 +- src/Validator/Rule/Count.php | 4 +- src/Validator/Rule/Date.php | 4 +- src/Validator/Rule/Email.php | 4 +- src/Validator/Rule/EmailList.php | 4 +- src/Validator/Rule/FileName.php | 4 +- src/Validator/Rule/IsFile.php | 4 +- src/Validator/Rule/Match.php | 4 +- src/Validator/Rule/Notnull.php | 4 +- src/Validator/Rule/Numeric.php | 4 +- src/Validator/Rule/Time.php | 4 +- src/Validator/Rule/Unique.php | 4 +- src/Validator/Validator.php | 3 +- src/View/{List.php => ListView.php} | 2 +- src/View/Page.php | 7 ++- src/View/Top.php | 2 +- 39 files changed, 141 insertions(+), 120 deletions(-) create mode 100644 src/ComponentRequest.php rename src/Validator/Rule/{Abstract.php => AbstractRule.php} (92%) rename src/View/{List.php => ListView.php} (89%) diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php new file mode 100644 index 0000000..3d56041 --- /dev/null +++ b/src/ComponentRequest.php @@ -0,0 +1,35 @@ +component_id = $c; + $this->r = $r; + } + + function get($key, $default = null) { + if ($key == 'active_page') { + return $this->r->get($key); + } + if ($arr = $this->r->get($key)) { + if (is_array($arr)) { + return Arr::get($arr, $this->component_id, $default); + } else { + return $arr; + } + } + return $default; + } + + function getAction() { + return $this->r->getAction(); + } +} \ No newline at end of file diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 750b25e..ca3a547 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -10,6 +10,8 @@ use ctiso\Shortcut, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, + ctiso\View\Composite, + ctiso\View\View, ctiso\Controller\State; /** @@ -82,18 +84,15 @@ class Action return Path::join($basePath, "modules", $name); } - public function addSuggest(View $view, $name) - { + public function addSuggest(View $view, $name) { $suggest = array(); $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { - include($file); - $view->suggestions = $suggest; + $view->suggestions = include($file); } } - function findIcon($icon, $size) - { + function findIcon($icon, $size) { $webPath = $this->settings['web']; return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } @@ -122,7 +121,7 @@ class Action if(file_exists($template)) { break; } } - /*.View_Composite.*/$tpl = new $viewClass($template); + /*.Composite.*/$tpl = new $viewClass($template); $stylePath = Path::join($webPath, "assets", "css"); $iconsPath = Path::join($webPath, 'icons'); @@ -170,7 +169,7 @@ class Action $action = "actionIndex"; } $view = $this->forward($action, $request); - if ($view instanceof View_View) { + if ($view instanceof View) { $view->active_module = get_class($this); $view->module_action = $action; } @@ -208,7 +207,7 @@ class Action */ public function nUrl($name, array $param = array()) { - /*.Filter_ActionAccess.*/$access = $this->access; + /*.ActionAccess.*/$access = $this->access; if ($access == null || $access->checkAction($name)) { $param = array_merge(array( @@ -295,12 +294,12 @@ class Action /** * Добавление widget к отображению */ - public function addChild(/*Widgets_Widget*/ $section, $node) + public function addChild($section, $node) { $this->childNodes[$section] = $node; } - public function setValue(/*Widgets_Widget*/ $name, $value) + public function setValue($name, $value) { $this->ctrlValues[$name] = $value; } @@ -308,7 +307,7 @@ class Action /** * Добавление дочернего отображения к текущему отображению */ - public function addView(/*CompositeView*/ $section, $node) + public function addView($section, $node) { $this->childViews[$section] = $node; } @@ -322,7 +321,7 @@ class Action if ($this->view instanceof View_View) { $this->view->assignValues($this->ctrlValues); - /*.Widgets_Widget.*/$node = null; + /*.Composite.*/$node = null; foreach ($this->childNodes as $name => $node) { $node->make($this); $this->view->setView($name, $node->view); @@ -335,8 +334,7 @@ class Action return $this->view; } - function getPageId(HttpRequest $request) - { + function getPageId(HttpRequest $request) { $pageId = time(); $request->session()->set('page', $pageId); return $pageId; @@ -353,19 +351,17 @@ class Action return $result; } - function _getActionPath() - { + function _getActionPath() { return new State('index'); } // Тоже убрать в метод Controller_Model - function getActionPath(HttpRequest $request, $action = null) - { + function getActionPath(HttpRequest $request, $action = null) { $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } function redirect($action) { - header('location: ' . $this->fUrl($action)); + header('location: ' . $action->toString()); exit(); } } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 1fcc8a8..1e94b27 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -2,16 +2,19 @@ namespace ctiso\Controller; use ctiso\HttpRequest, + ctiso\ComponentRequest, ctiso\Arr, ctiso\Path, - PHPTAL, - PHPTAL_PreFilter_Normalize, ctiso\File, ctiso\Form\Form, ctiso\Form\OptionFactory, ctiso\Database, + ctiso\Database\PDOStatement, ctiso\Collection, - ctiso\Controller\Site; + ctiso\Settings, + App\Controller\Site, + PHPTAL, + PHPTAL_PreFilter_Normalize; function replaceContent($match) { $result = Tales\Component::phptal_component(htmlspecialchars_decode($match[3])); @@ -22,35 +25,6 @@ function applyComponents($text) { return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'replaceContent', $text); } -class ComponentRequest { - public $component_id; - public $component_title; - public $r; - - function __construct($c, HttpRequest $r) { - $this->component_id = $c; - $this->r = $r; - } - - function get($key, $default = null) { - if ($key == 'active_page') { - return $this->r->get($key); - } - if ($arr = $this->r->get($key)) { - if (is_array($arr)) { - return Arr::get($arr, $this->component_id, $default); - } else { - return $arr; - } - } - return $default; - } - - function getAction() { - return $this->r->getAction(); - } -} - class FakeTemplate { public $_data = []; public $_name = ''; @@ -183,7 +157,7 @@ class Component return $model; } - public function options($key, $val, /*.Database_PDOStatement.*/$res) { + public function options($key, $val, /*.PDOStatement.*/$res) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val)); @@ -221,7 +195,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.View_Composite.*/$view) + public function setParameters(/*.Composite.*/$view) { $form = new Form(); $options = new OptionFactory($this->db, $this->registry); @@ -234,7 +208,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, Database $db, /*.Registry.*/ $registry) + static function loadComponent($expression, Database $db, /*.Settings.*/ $registry) { $expression = htmlspecialchars_decode($expression); @@ -254,7 +228,7 @@ class Component $path = Path::join (BASE_PATH, 'components', $name, $name . '.php'); $className = 'Component_' . $name; - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; if (file_exists($path)) { require_once ($path); @@ -313,7 +287,7 @@ class Component $editor = $component->getEditUrl(); if ($editor) { - if(class_exists("Controller_Site")) { //Если мы в CMS2 + if (class_exists("Controller_Site")) { //Если мы в CMS2 $instance = Site::getInstance(); $instance->componentsConfig[] = $editor; } else { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index b9fa014..9e55c82 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -98,7 +98,7 @@ class Front extends Action return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json') { + if ($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 50a3039..e67ed7d 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,6 +1,7 @@ next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 0a8e103..bd013e0 100644 --- a/src/Database.php +++ b/src/Database.php @@ -12,6 +12,7 @@ namespace { namespace ctiso { use PDO, ctiso\Database\Statement, + ctiso\Database\PDOStatement, ctiso\Database\IdGenerator; /** @@ -61,7 +62,7 @@ class Database extends PDO public function executeQuery($query, $values=null) { - /*.Database_PDOStatement.*/$stmt = $this->prepare($query); + /*.PDOStatement.*/$stmt = $this->prepare($query); $stmt->execute($values); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -79,7 +80,7 @@ class Database extends PDO */ public function fetchAllArray($query, $values = null) { - /*.Database_PDOStatement.*/$sth = $this->prepare($query); + /*.PDOStatement.*/$sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetchAll(PDO::FETCH_ASSOC); @@ -90,7 +91,7 @@ class Database extends PDO */ public function fetchOneArray($query, $values = null) { - /*.Database_PDOStatement.*/$sth = $this->prepare($query); + /*.PDOStatement.*/$sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetch(PDO::FETCH_ASSOC); @@ -180,9 +181,12 @@ class Database extends PDO return $result['nextval']; } - function close() - { + function prepare($query) { + /*.PDOStatement.*/$result = $this->prepare($query); + return $result; + } + + function close() { return null; } -} -} \ No newline at end of file +}} diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 48e591a..7d5b3fe 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -3,6 +3,7 @@ namespace ctiso\Database; use ctiso\Database\StatementIterator, + ctiso\Tools\StringUtil, PDO; class PDOStatement extends \PDOStatement implements \IteratorAggregate @@ -91,7 +92,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate } function getArray($name) { - return strToArray($this->fields[$name]); + return StringUtil::strToArray($this->fields[$name]); } function getRecordCount() { diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 69d7cf2..f47278f 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -4,7 +4,8 @@ * Класс оболочка для PDOStatement для замены Creole */ namespace ctiso\Database; -use PDO; +use PDO, + ctiso\Database; class Statement { @@ -50,7 +51,7 @@ class Statement if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; } - /*.Database_PDOStatement.*/$stmt = $this->conn->prepare($this->query); + /*.PDOStatement.*/$stmt = $this->conn->prepare($this->query); foreach ($this->binds as $bind) { list($n, $value, $type) = $bind; $stmt->bindValue($n, $value, (int) $type); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 02a5c3a..6286a6d 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -3,7 +3,7 @@ namespace ctiso\Database; use PDO; -class StatementIterator implements Iterator +class StatementIterator implements \Iterator { private $result; @@ -11,7 +11,7 @@ class StatementIterator implements Iterator private $fetchmode; private $row_count; - public function __construct(/*.Database_PDOStatement.*/ $rs) { + public function __construct(/*.PDOStatement.*/ $rs) { $this->result = $rs; $this->row_count = $rs->getRecordCount(); } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index bb28499..1861a36 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -4,6 +4,7 @@ * Клетка таблицы */ namespace ctiso\Excel; +use XMLWriter; class TableCell { @@ -310,4 +311,3 @@ class Table $doc->endElement(); } } - diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 0bb031c..da01325 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -12,7 +12,7 @@ class ActionAccess public $access = array(); public $processor; - function __construct(/*.Filter_Filter.*/$processor) { + function __construct(/*.Filter.*/$processor) { $this->processor = $processor; } @@ -23,7 +23,7 @@ class ActionAccess */ function checkAction($action) { // Импликация !! http://ru.wikipedia.org/wiki/Импликация - return (!isset($this->access[$action]) || in_array(UserAccess::$access, $this->access[$action])); + return (!isset($this->access[$action]) || in_array($this->user->access, $this->access[$action])); } function execute(HttpRequest $request) { diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 4718da8..d7da199 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -11,7 +11,7 @@ class ActionLogger public $action; public $processor; - function __construct(/*.Filter_Filter.*/$processor, $logPath, $user) { + function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; $this->file = fopen($logPath, "a"); diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index b61b5c8..864e898 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -4,12 +4,14 @@ * Попытка реализовать фильтр для запросов */ namespace ctiso\Filter; -use ctiso\HttpRequest; + +use ctiso\Controller\Action, + ctiso\HttpRequest; class Filter { public $processor; - public function __construct(/*.Controller_Action.*/$processor) + public function __construct(/*.Action.*/$processor) { $this->processor = $processor; } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index eb94070..851e966 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -19,8 +19,11 @@ class Login extends Filter { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + public $mode = 'ajax'; public $user; + public $role; + public $whitelist; function __construct($processor, $role, $whitelist = []) { parent::__construct($processor); @@ -63,7 +66,7 @@ class Login extends Filter if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { - $this->enter($db, $result); + $this->enter($result); return true; } } diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 70904bb..42ae288 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -2,7 +2,7 @@ namespace ctiso\Form; use ctiso\Form\Select, - ctiso\Model\Resources, + App\Model\Resources, ctiso\Model\Factory; class OptionFactory { diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 868da5a..2e57587 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -1,7 +1,8 @@ stack[count($this->stack) - 1]; + /*.\SimpleXMLElement.*/$item = $this->stack[count($this->stack) - 1]; $root = $item->children(); foreach ($root as $node) { diff --git a/src/Tales.php b/src/Tales.php index c3f2155..58a341d 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -5,7 +5,7 @@ */ namespace ctiso; use PHPTAL_Php_TalesInternal, - ctiso\Controller\Site, + App\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest, PHPTAL_Tales, @@ -48,7 +48,7 @@ class Tales { */ static function phptal_component ($expression) { $begin = floatval(microtime(true)); - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; if (class_exists("ctiso\\Controller\\Site")) { //Если мы в CMS2 $component = Site::loadComponent($expression); diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index fbde7c1..fad2434 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -122,7 +122,7 @@ class TemplateImage return ""; } - function imageText($text, /*.stdClass.*/$value) + function imageText($text, /*.\stdClass.*/$value) { assert(is_string($text)); diff --git a/src/Url.php b/src/Url.php index 3137d16..f52baec 100644 --- a/src/Url.php +++ b/src/Url.php @@ -3,6 +3,8 @@ namespace ctiso; class Url { + public $parts; + function __construct($parts = []) { $this->parts = $parts; } diff --git a/src/Validator/Rule/Abstract.php b/src/Validator/Rule/AbstractRule.php similarity index 92% rename from src/Validator/Rule/Abstract.php rename to src/Validator/Rule/AbstractRule.php index 15e6cb9..4ab8307 100644 --- a/src/Validator/Rule/Abstract.php +++ b/src/Validator/Rule/AbstractRule.php @@ -1,9 +1,9 @@ Rule_Abstract + public function skip(/*.AbstractRule.*/$rule, /*.Collection.*/$container) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); diff --git a/src/View/List.php b/src/View/ListView.php similarity index 89% rename from src/View/List.php rename to src/View/ListView.php index 45ca726..16945ff 100644 --- a/src/View/List.php +++ b/src/View/ListView.php @@ -3,7 +3,7 @@ namespace ctiso\View; use ctiso\View\View; -class List extends View +class ListView extends View { function execute() { diff --git a/src/View/Page.php b/src/View/Page.php index 2c0a4ab..10e40ec 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - ctiso\Controller\Site, + App\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest; @@ -54,10 +54,9 @@ class Page extends View function replaceContent($match, $offset) { //$result = phptal_component($match, $offset); - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; - - if(class_exists("Controller_Site")){ //Если мы в CMS2 + if (class_exists("App\\Controller\\Site")) { //Если мы в CMS2 $component = Site::loadComponent($match); } else { global $db, $registry; // diff --git a/src/View/Top.php b/src/View/Top.php index 3c2ed6c..eb67c02 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -102,7 +102,7 @@ class Top extends Composite { $init = array(); foreach($s->_section as $key => $item) { - /*.View_View.*/$ss = $item; + /*.View.*/$ss = $item; if ($ss->codeGenerator !== null) { // функцию которая вычисляет а не результат $part = call_user_func($ss->codeGenerator, $this, $key, $value); From 40fad0e75b17bffb868ed5acf11b4431b6120524 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 18 Apr 2018 18:20:56 +0300 Subject: [PATCH 11/42] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BC=D0=B5=D1=85=D0=B0=D0=BD=D0=B8=D0=B7=D0=BC=20?= =?UTF-8?q?=D1=80=D0=B0=D1=81=D1=88=D0=B8=D1=80=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=81=D1=81=D1=8B=D0=BB=D0=BE=D0=BA.=20=D0=98=D0=B7=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=82=20?= =?UTF-8?q?=D0=B3=D0=BB=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 19 +++++++++++++----- src/Controller/Component.php | 36 ++++++++++++++--------------------- src/Controller/Front.php | 2 +- src/Database.php | 4 ++-- src/Filter/ActionLogger.php | 11 +++++++++-- src/Filter/Login.php | 2 +- src/HttpRequest.php | 8 ++++---- src/Tales.php | 18 ++++++------------ src/Url.php | 18 +++++++++++++++--- src/View/Page.php | 13 ++++--------- src/WrongRequestException.php | 7 +++++++ 11 files changed, 77 insertions(+), 61 deletions(-) create mode 100644 src/WrongRequestException.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index ca3a547..2078409 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -5,12 +5,12 @@ use ctiso\Shortcut, Exception, ctiso\Path, ctiso\Url, - ctiso\View\View, ctiso\Model\Factory, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, ctiso\View\Composite, + ctiso\Filter\ActionAccess, ctiso\View\View, ctiso\Controller\State; @@ -43,7 +43,7 @@ class Action private $factory = null; // Ссылка на обьект создания модели private $helpers = array(); // Помошники для действий - public $param = array(); // Параметры для ссылки + public $part = null; // Параметры для ссылки public /*.Settings.*/$settings; // Ссылка на настройки public $user; // Обьект пользователя @@ -55,6 +55,7 @@ class Action public $childViews = array(); function __construct() { + $this->part = new Url(); } public function setUp() { @@ -198,6 +199,10 @@ class Action return ""; } + public function addUrlPart($key, $value) { + $this->part->addQueryParam($key, $value); + } + /** * Генерация ссылки c учетом прав пользователя на ссылки * @param string $name Действие @@ -208,16 +213,20 @@ class Action public function nUrl($name, array $param = array()) { /*.ActionAccess.*/$access = $this->access; + $url = new Url(); if ($access == null || $access->checkAction($name)) { $param = array_merge(array( 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), "action" => $name + ), $param); - return new Url($param); + $url->setParent($this->part); + $url->setQuery($param); } - return new Url(); + + return $url; } /** @@ -318,7 +327,7 @@ class Action */ public function render() { - if ($this->view instanceof View_View) { + if ($this->view instanceof View) { $this->view->assignValues($this->ctrlValues); /*.Composite.*/$node = null; diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 1e94b27..c87cf59 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -8,6 +8,7 @@ use ctiso\HttpRequest, ctiso\File, ctiso\Form\Form, ctiso\Form\OptionFactory, + ctiso\View\Composite, ctiso\Database, ctiso\Database\PDOStatement, ctiso\Collection, @@ -38,7 +39,7 @@ class FakeTemplate { } function execute() { - return $this->_data; + return json_encode($this->_data); } } @@ -64,6 +65,7 @@ class Component public $module; public $item_module; + public $site; function before() { } @@ -95,7 +97,6 @@ class Component return new FakeTemplate($name); } - // /*.Settings.*/$registry = $this->registry; $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); @@ -195,7 +196,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/$view) + public function setParameters(/*.Composite.*/ $view) { $form = new Form(); $options = new OptionFactory($this->db, $this->registry); @@ -208,7 +209,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, Database $db, /*.Settings.*/ $registry) + static function loadComponent($expression, /*.Site.*/ $site) { $expression = htmlspecialchars_decode($expression); @@ -232,22 +233,16 @@ class Component if (file_exists($path)) { require_once ($path); - $component = new $className(); - $component->db = $db; - $component->registry = $registry; $component->viewPath = array(BASE_PATH . '/components/' . $name . '/'); $component->webPath = array(SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = SITE_WWW_PATH . '/components/'; } else { $path = Path::join (COMPONENTS, $name, $name . '.php'); require_once ($path); $component = new $className(); - $component->db = $db; - $component->registry = $registry; $component->viewPath = array(COMPONENTS . '/' . $name . '/', BASE_PATH . '/components/' . $name . '/'); if (defined('COMPONENTS_WEB')) { @@ -255,6 +250,12 @@ class Component $component->COMPONENTS_WEB = COMPONENTS_WEB; } } + + $db = $site->db; + + $component->db = $db; + $component->registry = $site->registry; + $component->site = $site; $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); $stmt->setString(1, $expression); @@ -282,18 +283,13 @@ class Component $params = new Collection(); $params->import($arguments); + $component->parameter = $params; $component->template = $params->get('template', false); $editor = $component->getEditUrl(); if ($editor) { - if (class_exists("Controller_Site")) { //Если мы в CMS2 - $instance = Site::getInstance(); - $instance->componentsConfig[] = $editor; - } else { - global $componentsConfig; - $componentsConfig[] = $editor; - } + $site->componentsConfig[] = $editor; } return $component; @@ -338,12 +334,8 @@ class Component return '?' . http_build_query($arr); } - /** - * @deprecated В CMS2 перенесено в контроллер сайта! - */ - function addRequireJsPath($name, $path, $shim = null) { - Site::addRequireJsPath($name, $path, $shim); + $this->site->addRequireJsPath($name, $path, $shim); } function actionIndex(/*.ComponentRequest.*/ $request) { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 9e55c82..5f243af 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -51,7 +51,7 @@ class Front extends Action return $module->access->execute($request); } - $system = $this->settings['system']; + /*.Settings.*/$system = $this->settings['system']; $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); diff --git a/src/Database.php b/src/Database.php index bd013e0..9ac4c6d 100644 --- a/src/Database.php +++ b/src/Database.php @@ -181,8 +181,8 @@ class Database extends PDO return $result['nextval']; } - function prepare($query) { - /*.PDOStatement.*/$result = $this->prepare($query); + function prepare($query, $options = NULL) { + /*.PDOStatement.*/$result = parent::prepare($query); return $result; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index d7da199..93c11e7 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -3,6 +3,7 @@ namespace ctiso\Filter; use ctiso\HttpRequest; +/* Переделать формат Логов на список json */ class ActionLogger { public $before = array(); @@ -14,13 +15,19 @@ class ActionLogger function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; - $this->file = fopen($logPath, "a"); + $file = fopen($logPath, "a"); + if (is_resource($file)) { + $this->file = $file; + } else { + throw new \Exception('Ошибка открытия файла ' . $logPath); + } } function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . $this->user->name . "\n"); + $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->name]; + fwrite($this->file, json_encode($message) . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 851e966..74f2259 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -162,7 +162,7 @@ class Login extends Filter /* --------------------- * Проверка на попадание реквеста в белый список */ - public function requestIsWhite(Collection $request, $whiteRequestList){ + public function requestIsWhite(HttpRequest $request, $whiteRequestList){ $module = $request->get('module'); $action = $request->get('action'); foreach ($whiteRequestList as $whiteRequest) { diff --git a/src/HttpRequest.php b/src/HttpRequest.php index f88fb0c..5e1b519 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -9,10 +9,6 @@ use Exception, ctiso\Collection, ctiso\Session; -class WrongRequestException extends Exception -{ -} - // HTTPRequest = ArrayAccess class HttpRequest extends Collection implements ArrayAccess { @@ -132,4 +128,8 @@ class HttpRequest extends Collection implements ArrayAccess public function offsetGet($key) { } + + static function getProtocol() { + return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; + } } diff --git a/src/Tales.php b/src/Tales.php index 58a341d..c0e09d4 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -14,11 +14,11 @@ use PHPTAL_Php_TalesInternal, class Tales_DateTime implements PHPTAL_Tales { static public function date($expression, $nothrow = false) { - return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")"; + return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; } static public function time($expression, $nothrow = false) { - return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path ($expression).")"; + return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; } } @@ -32,8 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static $db; - static $registry; + static $site; static function phptal_date ($e) { return date("d.m.Y", $e); @@ -50,11 +49,7 @@ class Tales { $begin = floatval(microtime(true)); /*.Component.*/$component = null; - if (class_exists("ctiso\\Controller\\Site")) { //Если мы в CMS2 - $component = Site::loadComponent($expression); - } else { - $component = Component::loadComponent($expression, self::$db, self::$registry); - } + $component = self::$site->loadComponent($expression); $req = new HttpRequest(); $result = $component->execute($req); @@ -63,9 +58,8 @@ class Tales { } - static function register($db, $registry) { - self::$db = $db; - self::$registry = $registry; + static function register($site) { + self::$site = $site; /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); diff --git a/src/Url.php b/src/Url.php index f52baec..3b879ef 100644 --- a/src/Url.php +++ b/src/Url.php @@ -3,13 +3,25 @@ namespace ctiso; class Url { - public $parts; + public $parts = []; + public $parent; - function __construct($parts = []) { + function __construct() { + } + + function setParent($parent) { + $this->parent = $parent; + } + + function setQuery($parts) { $this->parts = $parts; } + function addQueryParam($key, $value) { + $this->parts[$key] = $value; + } + function toString() { - return '?' . http_build_query($this->parts); + return '?' . http_build_query(array_merge($this->parts, $this->parent->parts)); } } \ No newline at end of file diff --git a/src/View/Page.php b/src/View/Page.php index 10e40ec..4ccb457 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -10,9 +10,11 @@ class Page extends View { private $counter; public $text; + public $site; - function __construct($data) + function __construct($data, $site) { + $this->site = $site; // Вставка компонентов на странице $pattern = '/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u'; $matches = array(); @@ -53,15 +55,8 @@ class Page extends View function replaceContent($match, $offset) { - //$result = phptal_component($match, $offset); /*.Component.*/$component = null; - - if (class_exists("App\\Controller\\Site")) { //Если мы в CMS2 - $component = Site::loadComponent($match); - } else { - global $db, $registry; // - $component = Component::loadComponent($match, $db, $registry); - } + $component = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/WrongRequestException.php b/src/WrongRequestException.php new file mode 100644 index 0000000..6ebddfc --- /dev/null +++ b/src/WrongRequestException.php @@ -0,0 +1,7 @@ + Date: Fri, 20 Apr 2018 18:03:39 +0300 Subject: [PATCH 12/42] =?UTF-8?q?=D0=94=D1=80=D1=83=D0=B3=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=82=D0=B5=D1=80=D0=BF=D1=80=D0=B5=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D1=80=D0=B5=D0=B5=D1=81=D1=82=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 25 ++++++++------- src/Controller/Component.php | 60 +++++++++++++++++------------------ src/Controller/Front.php | 14 ++++---- src/Controller/Installer.php | 9 +++--- src/Controller/Service.php | 5 +-- src/Controller/State.php | 3 +- src/Excel/Document.php | 2 +- src/Excel/Table.php | 4 ++- src/Filter/ActionAccess.php | 7 ++-- src/Filter/Authorization.php | 23 ++++++++------ src/Filter/Login.php | 5 +-- src/Form/OptionFactory.php | 2 +- src/Path.php | 2 +- src/Registry.php | 40 +++++++++++++++++++++++ src/Settings.php | 28 ++++++++++------ src/Tales.php | 2 +- src/Url.php | 2 +- src/Validator/Rule/Count.php | 2 +- src/View/Page.php | 7 ++-- src/View/Top.php | 4 +-- src/WrongRequestException.php | 2 +- 21 files changed, 156 insertions(+), 92 deletions(-) create mode 100644 src/Registry.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 2078409..be0dfb8 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -9,6 +9,8 @@ use ctiso\Shortcut, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, + ctiso\Registry, + ctiso\Role\User, ctiso\View\Composite, ctiso\Filter\ActionAccess, ctiso\View\View, @@ -45,8 +47,8 @@ class Action private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки - public /*.Settings.*/$settings; // Ссылка на настройки - public $user; // Обьект пользователя + public /*.Registry.*/$config; // Ссылка на настройки + public /*.User.*/$user; // Обьект пользователя // Для Widgets public $view = null; @@ -62,7 +64,7 @@ class Action } public function loadConfig($name) { - $basePath = $this->settings['base']; + $basePath = $this->config->get('site', 'path'); $filename = Path::join($basePath, 'modules', $name); $settings = []; @@ -81,7 +83,7 @@ class Action public function installPath($name) { - $basePath = $this->settings['base']; + $basePath = $this->config->get('site', 'path'); return Path::join($basePath, "modules", $name); } @@ -94,7 +96,7 @@ class Action } function findIcon($icon, $size) { - $webPath = $this->settings['web']; + $webPath = $this->config->get('site', 'web'); return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } @@ -108,8 +110,8 @@ class Action { $file = $name . self::TEMPLATE_EXTENSION; - $basePath = $this->settings['base']; - $webPath = $this->settings['web']; + $basePath = $this->config->get('site', 'path'); + $webPath = $this->config->get('site', 'web'); $list = array( Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), @@ -151,7 +153,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->settings['registry']); + $this->factory = new Factory($this->db, $this->config); } return $this->factory->getModel($name); } @@ -327,7 +329,8 @@ class Action */ public function render() { - if ($this->view instanceof View) { + $view = $this->view; + if ($view instanceof View) { $this->view->assignValues($this->ctrlValues); /*.Composite.*/$node = null; @@ -369,8 +372,8 @@ class Action $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } - function redirect($action) { - header('location: ' . $action->toString()); + function redirect(/*.string.*/$action) { + header('location: ' . $action); exit(); } } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index c87cf59..7210d32 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -12,20 +12,11 @@ use ctiso\HttpRequest, ctiso\Database, ctiso\Database\PDOStatement, ctiso\Collection, - ctiso\Settings, + ctiso\Registry, App\Controller\Site, PHPTAL, PHPTAL_PreFilter_Normalize; -function replaceContent($match) { - $result = Tales\Component::phptal_component(htmlspecialchars_decode($match[3])); - return $result; -} - -function applyComponents($text) { - return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'replaceContent', $text); -} - class FakeTemplate { public $_data = []; public $_name = ''; @@ -56,11 +47,13 @@ class Component public $component_id; public $component_title; + public $COMPONENTS_WEB; - public /*.Settings.*/$registry; + public /*.Registry.*/$config; public /*.Database.*/$db; public /*.Collection.*/$parameter; + public $output = 'html'; public $module; @@ -70,7 +63,12 @@ class Component function before() { } - function get($request, $key, $default) { + static function replaceContent($match) { + return \ctiso\Tales::phptal_component(htmlspecialchars_decode($match[3])); + } + + static function applyComponents($text) { + return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'ctiso\\Controller\\Component::replaceContent', $text); } function execute(HttpRequest $request, $has_id = true) { @@ -97,8 +95,9 @@ class Component return new FakeTemplate($name); } - /*.Settings.*/$registry = $this->registry; - $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); + /*.Registry.*/$config = $this->config; + $default = $config->get('site', 'template'); + $template = ($this->template) ? $this->template : $default; $selected = null; foreach ($this->viewPath as $index => $viewPath) { @@ -121,13 +120,14 @@ class Component $tpl->stripComments(true); $tpl->addPreFilter(new PHPTAL_PreFilter_Normalize()); - $tpl->set('common', Path::join(WWW_PATH, '../', 'common')); - $tpl->set('script', Path::join(WWW_PATH, 'js')); - $tpl->set('media', Path::join(TEMPLATE_WEB, $template)); - if ($registry) { - $tpl->set('site_template', SITE_WWW_PATH . '/templates' . $registry->readKey(array('system', 'template'))); + $tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); + $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); + $tpl->set('media', Path::join($this->config->get('system', 'templates_web'), $template)); + + if ($default) { + $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); } - $tpl->set('base', SITE_WWW_PATH); + $tpl->set('base', $this->config->get('site', 'web')); $tpl->set('component_base', $this->webPath[$selected]); $tpl->set('component', Path::join($this->webPath[$selected], 'templates', $template)); @@ -199,7 +199,7 @@ class Component public function setParameters(/*.Composite.*/ $view) { $form = new Form(); - $options = new OptionFactory($this->db, $this->registry); + $options = new OptionFactory($this->db, $this->config); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); @@ -226,7 +226,7 @@ class Component } $name = $path; - $path = Path::join (BASE_PATH, 'components', $name, $name . '.php'); + $path = Path::join ($this->config->get('site', 'path'), 'components', $name, $name . '.php'); $className = 'Component_' . $name; /*.Component.*/$component = null; @@ -235,26 +235,26 @@ class Component require_once ($path); $component = new $className(); - $component->viewPath = array(BASE_PATH . '/components/' . $name . '/'); - $component->webPath = array(SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = SITE_WWW_PATH . '/components/'; + $component->viewPath = array($this->config->get('site', 'path') . '/components/' . $name . '/'); + $component->webPath = array($this->config->get('site', 'web') . '/components/' . $name); + $component->COMPONENTS_WEB = $this->config->get('site', 'web') . '/components/'; } else { - $path = Path::join (COMPONENTS, $name, $name . '.php'); + $path = Path::join ($this->config->get('system', 'components'), $name, $name . '.php'); require_once ($path); $component = new $className(); - $component->viewPath = array(COMPONENTS . '/' . $name . '/', BASE_PATH . '/components/' . $name . '/'); + $component->viewPath = array($this->config->get('system', 'components') . '/' . $name . '/', $this->config->get('site', 'path') . '/components/' . $name . '/'); if (defined('COMPONENTS_WEB')) { - $component->webPath = array(COMPONENTS_WEB . '/' . $name, SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = COMPONENTS_WEB; + $component->webPath = array($this->config->get('system', 'components_web') . '/' . $name, $this->config->get('site', 'web') . '/components/' . $name); + $component->COMPONENTS_WEB = $this->config->get('system', 'components_web'); } } $db = $site->db; $component->db = $db; - $component->registry = $site->registry; + $component->config = $site->config; $component->site = $site; $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 5f243af..bc4096c 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -26,9 +26,9 @@ class Front extends Action /** * @param Settings $settings */ - public function __construct($db, $settings, $user, $default) { + public function __construct($db, $config, $user, $default) { parent::__construct(); - $this->settings = $settings; + $this->config = $config; $this->db = $db; $this->user = $user; $this->default = $default; @@ -50,11 +50,11 @@ class Front extends Action $module = $this->modules[$name]; return $module->access->execute($request); } + $config = $this->config; - /*.Settings.*/$system = $this->settings['system']; + $moulesPath = Path::join($config->get('system', 'path'), 'modules'); + $logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log')); - $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); - $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); $moduleFile = Path::join($moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); @@ -66,14 +66,14 @@ class Front extends Action $module->modulePath = $modPath; $module->name = $name; // - $module->settings = $this->settings; + $module->config = $this->config; $module->db = $this->db; $module->user = $this->user; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом - $module->access = new ActionAccess($logger); + $module->access = new ActionAccess($logger, $this->user); $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); $module->setUp(); diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index a5a55fa..e544921 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -35,7 +35,7 @@ class Installer // Проверка версии обновления function isChanged($name) // Информация о модулях { - $item = $this->_registry->readKey(array($name)); + $item = $this->_registry->get('system', $name); if ($item) { $setup = $this->getSetupFile($name); if (file_exists($setup) && (filemtime($setup) > $item['time'])) { @@ -81,7 +81,7 @@ class Installer $settings = new Settings($setup); $settings->read(); - $item = $registry->readKey(array($name)); + $item = $registry->get('system', $name); $version_new = $settings->get('version'); if ($item) { @@ -101,8 +101,9 @@ class Installer // Обновление версии меню $registry->removeKey($name); - $registry->writeKey(array($name), $settings->get('settings')); - $registry->writeKey(array($name), + + $registry->set($name, $settings->get('settings')); + $registry->set($name, array('version' => $version_new, 'time' => filemtime($setup))); } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 26c81cc..fbcbb69 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -5,13 +5,14 @@ */ namespace ctiso\Controller; use ctiso\Path, + ctiso\Registry, ctiso\Database\PDOStatement; class Service { public $viewPath = []; public $webPath = []; - public $registry; // Registry->getInstance + public /*.Registry.*/$config; public $template; public $templatePath; public $COMPONENTS_WEB; @@ -33,7 +34,7 @@ class Service */ private function getModelPath($name) { - return Path::join (CMS_PATH, "model", $name . ".php"); + return Path::join ($this->config->get('system', 'path'), "model", $name . ".php"); } /** diff --git a/src/Controller/State.php b/src/Controller/State.php index 481faaf..225de1a 100644 --- a/src/Controller/State.php +++ b/src/Controller/State.php @@ -1,7 +1,8 @@ createStyles($doc); foreach ($this->table as $table) { - if ($table instanceof Excel_Table) { + if ($table instanceof Table) { $table->createTable($doc); } else { $table_data = call_user_func($table); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 1861a36..5a1786f 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -4,7 +4,9 @@ * Клетка таблицы */ namespace ctiso\Excel; -use XMLWriter; +use XMLWriter, + ctiso\Excel\DateTime as Excel_DateTime, + ctiso\Excel\Number as Excel_Number; class TableCell { diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index da01325..c27b1b2 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -5,15 +5,18 @@ */ namespace ctiso\Filter; use ctiso\Filter\UserAccess, - ctiso\HttpRequest; + ctiso\HttpRequest, + ctiso\Role\User; class ActionAccess { public $access = array(); public $processor; + public /*.User.*/$user; - function __construct(/*.Filter.*/$processor) { + function __construct(/*.Filter.*/$processor, $user) { $this->processor = $processor; + $this->user = $user; } /** diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 56ebc4d..0538eb2 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -5,38 +5,41 @@ namespace ctiso\Filter; class Authorization { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + public $group; - static function isLogged($group = 'access') { + function __construct($group) { + $this->group = $group; + } + + function isLogged() { // echo session_status(); if (session_status() == PHP_SESSION_NONE) { session_start(); } $hash = self::getBrowserSign(); // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию - if (isset($_SESSION[$group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { + if (isset($_SESSION[$this->group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { // UserAccess::getUserById($_SESSION ['access']); // Поиск по идентификатору return true; } else { - return false; + return false; } } return false; } - static function enter($id, $group = 'access') - { + function enter($id) { // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // session_register("access"); // session_register("time"); -// $_SESSION ["group"] = $result->getInt('access'); - $_SESSION [$group] = $id; // id_user + $_SESSION [$this->group] = $id; $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); - $_SESSION ["time"] = time(); + $_SESSION ["time"] = time(); } - private static function getBrowserSign() + static function getBrowserSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; // $signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); @@ -48,7 +51,7 @@ class Authorization { return md5($rawSign); } - static function logout() { + function logout() { session_destroy(); } } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 74f2259..7d976bd 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -13,6 +13,7 @@ use ctiso\Filter\Filter, ctiso\HttpRequest, ctiso\Settings, ctiso\Database, + ctiso\Role\User, ctiso\Collection; class Login extends Filter @@ -22,7 +23,7 @@ class Login extends Filter public $mode = 'ajax'; public $user; - public $role; + public /*.User.*/$role; public $whitelist; function __construct($processor, $role, $whitelist = []) { @@ -140,7 +141,7 @@ class Login extends Filter // Параметры при неправильной авторизации // Действия по умолчанию !! Возможно переход на форму регистрации if ($request->get('mode') == 'ajax') { - if (!$this->requestIsWhite($request, $this->whiteRequestList)) { + if (!$this->requestIsWhite($request, $this->whitelist)) { return json_encode(array('result' => 'fail', 'message' =>"NOT_AUTHORIZED")); } } else { diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 42ae288..d0fd9e8 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -38,7 +38,7 @@ class OptionFactory { try { $query_result = $this->db->executeQuery("SELECT * FROM $table"); $field->options = $this->optionsDB($key, $value, $query_result); - } catch(Exception $ex) { + } catch(\Exception $ex) { $field->options = []; } } elseif (isset($input['options.pair'])) { diff --git a/src/Path.php b/src/Path.php index 803952e..5234e73 100644 --- a/src/Path.php +++ b/src/Path.php @@ -372,7 +372,7 @@ class Path */ public function getContent($allow = null, $ignore = array()) { - $ignore = array_merge(array(".", ".."), $ignore); + $ignore = array_merge(array(".", ".."), $ignore); return self::fileList($this->__toString(), $allow, $ignore); } diff --git a/src/Registry.php b/src/Registry.php new file mode 100644 index 0000000..552c086 --- /dev/null +++ b/src/Registry.php @@ -0,0 +1,40 @@ +namespace[$namespace] = [ + 'path' => $filePath, + 'data' => $data + ]; + } + + function importArray($namespace, $data = []) { + if (isset($this->namespace[$namespace])) { + $data = array_merge($this->namespace[$namespace]['data'], $data); + } + $this->namespace[$namespace] = [ + 'path' => null, + 'data' => $data + ]; + } + + public function get($ns, $key) { + return $this->namespace[$ns]['data'][$key]; + } + + public function has($ns, $key) { + return isset($this->namespace[$ns]['data'][$key]); + } + + function set($ns, $key, $value) { + $this->namespace[$ns]['data'][$key] = $value; + } +} diff --git a/src/Settings.php b/src/Settings.php index 4a677a8..5ea6a52 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -10,12 +10,12 @@ * Имя необходимо чтобы потом легко было удалить ненужные ветки дерева */ namespace ctiso; -use ctiso\Collection, - ctiso\File, +use ctiso\File, Exception; -class Settings extends Collection +class Settings { + public $data; protected $file; protected $format = 'php'; @@ -45,7 +45,8 @@ class Settings extends Collection if (!is_array($settings)) { throw new Exception($this->file); } - return $this->import($settings); + + $this->data = $settings; } /** @@ -175,11 +176,20 @@ class Settings extends Collection file_put_contents (($file) ? $file : $this->file, $result); } - /** - * Список модулей - */ - public function getModules() + public function set($key, $value) { + $this->data[$key] = $value; + } + + public function get($key, $default = null) { - return array_keys($this->data); + return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; + } + + function export() { + return $this->data; + } + + function import($data) { + $this->data = $data; } } diff --git a/src/Tales.php b/src/Tales.php index c0e09d4..55bffc6 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static $site; + static /*.Site.*/$site; static function phptal_date ($e) { return date("d.m.Y", $e); diff --git a/src/Url.php b/src/Url.php index 3b879ef..a7b16fd 100644 --- a/src/Url.php +++ b/src/Url.php @@ -4,7 +4,7 @@ namespace ctiso; class Url { public $parts = []; - public $parent; + public /*.Url.*/$parent; function __construct() { } diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 71d60a9..ff030a4 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -30,7 +30,7 @@ class Count extends AbstractRule $count = count(array_filter(array_map('trim', explode(";", $container->get($this->field))), array($this, 'not_empty'))); - return $count >= $this->size && $count <= $this->max; + return $count >= $this->size && $count <= ((int)$this->max); } } diff --git a/src/View/Page.php b/src/View/Page.php index 4ccb457..d224fc2 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - App\Controller\Site, + App\Controller\Site, /* Нужно импортровать интерфейс */ ctiso\Controller\Component, ctiso\HttpRequest; @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public $site; + public /*.Site.*/$site; function __construct($data, $site) { @@ -55,8 +55,7 @@ class Page extends View function replaceContent($match, $offset) { - /*.Component.*/$component = null; - $component = $this->site->loadComponent($match); + /*.Component.*/$component = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/View/Top.php b/src/View/Top.php index eb67c02..47d1a2c 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -29,7 +29,7 @@ class Top extends Composite { private function groupFiles(array $list, $debugMode = true) { $debug = ($debugMode) ? 'debug=1' : ''; - $path = parse_url(WWW_PATH, PHP_URL_PATH); + $path = parse_url($this->config->get('system', 'web'), PHP_URL_PATH); $groups = array(); $use = array(); @@ -120,7 +120,7 @@ class Top extends Composite { $this->set('deps', implode(",", array_values($this->require))); $this->set('title', $this->getTitle()); - $this->set('jspath', enableHttps(WWW_PATH)); + $this->set('jspath', enableHttps($this->config->get('system', 'web'))); // return $this->execute(); // execute+phptal ?? } diff --git a/src/WrongRequestException.php b/src/WrongRequestException.php index 6ebddfc..34863be 100644 --- a/src/WrongRequestException.php +++ b/src/WrongRequestException.php @@ -2,6 +2,6 @@ namespace ctiso; -class WrongRequestException extends Exception +class WrongRequestException extends \Exception { } From c2b9254fd0b1bab0c1525cc86c782214b9b243b7 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Mon, 23 Apr 2018 11:18:53 +0300 Subject: [PATCH 13/42] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D1=85=D0=BE=D0=B6?= =?UTF-8?q?=D0=B4=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B0=D0=B2=D1=82=D1=80=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 5 +++-- src/File.php | 2 +- src/Filter/ActionLogger.php | 1 + src/Model/Factory.php | 10 +++++----- src/Settings.php | 2 +- src/Url.php | 2 +- src/View/Composite.php | 4 ++-- src/View/Top.php | 2 +- src/View/View.php | 2 +- 9 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index be0dfb8..34137af 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -110,8 +110,8 @@ class Action { $file = $name . self::TEMPLATE_EXTENSION; - $basePath = $this->config->get('site', 'path'); - $webPath = $this->config->get('site', 'web'); + $basePath = $this->config->get('system', 'path'); + $webPath = $this->config->get('system', 'web'); $list = array( Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), @@ -125,6 +125,7 @@ class Action } /*.Composite.*/$tpl = new $viewClass($template); + $tpl->config = $this->config; $stylePath = Path::join($webPath, "assets", "css"); $iconsPath = Path::join($webPath, 'icons'); diff --git a/src/File.php b/src/File.php index 5de7429..c523cf6 100644 --- a/src/File.php +++ b/src/File.php @@ -5,7 +5,7 @@ use Exception; class File { static function getContents($filename) { - $buffer = file_get_contents($filename); + $buffer = @file_get_contents($filename); if ($buffer !== false) { return $buffer; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 93c11e7..403d3b0 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -15,6 +15,7 @@ class ActionLogger function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; + $file = fopen($logPath, "a"); if (is_resource($file)) { $this->file = $file; diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 2e57587..577b826 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -1,19 +1,19 @@ db = $db; - $this->_registry = $_registry; + $this->config = $config; } /** @@ -27,7 +27,7 @@ class Factory $model = new $modelName(); $model->db = $this->db; $model->factory = $this; - $model->_registry = $this->_registry; + $model->config = $this->config; $model->setUp(); // return $model; diff --git a/src/Settings.php b/src/Settings.php index 5ea6a52..4bd7ee5 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -15,7 +15,7 @@ use ctiso\File, class Settings { - public $data; + public $data = []; protected $file; protected $format = 'php'; diff --git a/src/Url.php b/src/Url.php index a7b16fd..5c824ab 100644 --- a/src/Url.php +++ b/src/Url.php @@ -22,6 +22,6 @@ class Url { } function toString() { - return '?' . http_build_query(array_merge($this->parts, $this->parent->parts)); + return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : [])); } } \ No newline at end of file diff --git a/src/View/Composite.php b/src/View/Composite.php index 8be63fc..ff659ef 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -11,6 +11,7 @@ use ctiso\View\View, class Composite extends View { private $tal; + public $config; function __construct($file) { @@ -18,7 +19,7 @@ class Composite extends View $this->tal = new PHPTAL($file); $this->tal->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); - $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); // PHPTAL_DEFAULT_ENCODING !! + $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); $this->tal->setTemplateRepository(PHPTAL_TEMPLATE_REPOSITORY); $this->tal->setOutputMode(PHPTAL::HTML5); $this->tal->stripComments(true); @@ -39,7 +40,6 @@ class Composite extends View function execute() { parent::execute(); - // postProcess return $this->tal->execute(); } diff --git a/src/View/Top.php b/src/View/Top.php index 47d1a2c..08051f0 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -120,7 +120,7 @@ class Top extends Composite { $this->set('deps', implode(",", array_values($this->require))); $this->set('title', $this->getTitle()); - $this->set('jspath', enableHttps($this->config->get('system', 'web'))); + $this->set('jspath', $this->config->get('system', 'web')); // return $this->execute(); // execute+phptal ?? } diff --git a/src/View/View.php b/src/View/View.php index 5955112..ab8aff9 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -205,4 +205,4 @@ class View } return $result; } -} \ No newline at end of file +} From df00756a412f597e29f29b76203f39eb54809266 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 25 Apr 2018 14:50:45 +0300 Subject: [PATCH 14/42] =?UTF-8?q?=D0=98=D0=BD=D1=82=D0=B5=D1=80=D1=84?= =?UTF-8?q?=D0=B5=D0=B9=D1=81=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20?= =?UTF-8?q?=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=B0=20Site?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 6 +++--- src/Controller/SiteInterface.php | 11 +++++++++++ src/Registry.php | 5 ++++- src/Tales.php | 4 ++-- src/View/Page.php | 4 ++-- 5 files changed, 22 insertions(+), 8 deletions(-) create mode 100644 src/Controller/SiteInterface.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 7210d32..2204da8 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -13,7 +13,7 @@ use ctiso\HttpRequest, ctiso\Database\PDOStatement, ctiso\Collection, ctiso\Registry, - App\Controller\Site, + ctiso\Controller\SiteInterface, PHPTAL, PHPTAL_PreFilter_Normalize; @@ -209,7 +209,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, /*.Site.*/ $site) + static function loadComponent($expression, /*.SiteInterface.*/ $site) { $expression = htmlspecialchars_decode($expression); @@ -251,7 +251,7 @@ class Component } } - $db = $site->db; + $db = $site->getDatabase(); $component->db = $db; $component->config = $site->config; diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php new file mode 100644 index 0000000..205e5ea --- /dev/null +++ b/src/Controller/SiteInterface.php @@ -0,0 +1,11 @@ +namespace[$ns]['data'][$key]; + if (isset($this->namespace[$ns]['data'][$key])) { + return $this->namespace[$ns]['data'][$key]; + } + throw new Exception('Unknown key ' . $ns . '::' . $key); } public function has($ns, $key) { diff --git a/src/Tales.php b/src/Tales.php index 55bffc6..b6fc45a 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -5,7 +5,7 @@ */ namespace ctiso; use PHPTAL_Php_TalesInternal, - App\Controller\Site, + ctiso\Controller\SiteInterface, ctiso\Controller\Component, ctiso\HttpRequest, PHPTAL_Tales, @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static /*.Site.*/$site; + static /*.SiteInterface.*/$site; static function phptal_date ($e) { return date("d.m.Y", $e); diff --git a/src/View/Page.php b/src/View/Page.php index d224fc2..3591abe 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - App\Controller\Site, /* Нужно импортровать интерфейс */ + ctiso\Controller\SiteInterface, ctiso\Controller\Component, ctiso\HttpRequest; @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public /*.Site.*/$site; + public /*.SiteInterface.*/$site; function __construct($data, $site) { From 8065253db0831ce2542fc9ba1e879a93b3e04373 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Thu, 26 Apr 2018 12:31:43 +0300 Subject: [PATCH 15/42] =?UTF-8?q?OptionFactory=20=D0=B2=D1=8B=D0=BD=D0=B5?= =?UTF-8?q?=D1=81=20=D0=B2=20cms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 4 +- src/Form/OptionFactory.php | 78 ------------------------------------ 2 files changed, 1 insertion(+), 81 deletions(-) delete mode 100644 src/Form/OptionFactory.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 7210d32..b520f09 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -7,7 +7,6 @@ use ctiso\HttpRequest, ctiso\Path, ctiso\File, ctiso\Form\Form, - ctiso\Form\OptionFactory, ctiso\View\Composite, ctiso\Database, ctiso\Database\PDOStatement, @@ -196,10 +195,9 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/ $view) + public function setParameters(/*.Composite.*/ $view, $options = null) { $form = new Form(); - $options = new OptionFactory($this->db, $this->config); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php deleted file mode 100644 index d0fd9e8..0000000 --- a/src/Form/OptionFactory.php +++ /dev/null @@ -1,78 +0,0 @@ -db = $db; - $this->registry = $registry; - } - - function create(Select $field, $input) { - if (isset($input['options.resid'])) { - $type = $input['options.resid']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.res'])) { - $type = $input['options.res']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.all_res'])) { - $type = $input['options.all_res']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); - - } else if (isset($input['options.db'])) { - list($table, $keyvalue) = explode(":", $input['options.db']); - list($key, $value) = explode(",", $keyvalue); - try { - $query_result = $this->db->executeQuery("SELECT * FROM $table"); - $field->options = $this->optionsDB($key, $value, $query_result); - } catch(\Exception $ex) { - $field->options = []; - } - } elseif (isset($input['options.pair'])) { - $field->options = $this->optionsPair($input['options.pair']); - } elseif (isset($input['options.model'])) { - $factory = new Factory($this->db, $this->registry); - $model = $factory->getModel($input['options.model']); - $field->options = $model->getAllAsOptions(); - } else { - $field->options = $input['options']; - } - } - - public function optionsDB($key, $val, $res) { - $result = array(); - while($res->next()) { - $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); - } - return $result; - } - - public function optionsArray($key, $val, $res) { - $result = array(); - foreach($res as $item) { - $result[] = array('value' => $item->{$key}, 'name' => $item->{$val}); - } - return $result; - } - - public function optionsPair($list, $selected = false) { - $result = array(); - foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); - } - return $result; - } -} From 40f40a8d6ddeda416bc945022efeb30dae7d5257 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Sat, 28 Apr 2018 14:13:19 +0300 Subject: [PATCH 16/42] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 7 ++----- src/Form/BrowserInput.php | 6 ++++++ src/Form/Form.php | 31 ++++++++++++++----------------- 3 files changed, 22 insertions(+), 22 deletions(-) create mode 100644 src/Form/BrowserInput.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 34137af..a86511b 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -219,11 +219,8 @@ class Action $url = new Url(); if ($access == null || $access->checkAction($name)) { - $param = array_merge(array( - 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), - "action" => $name - - ), $param); + $moduleName = explode("\\", strtolower(get_class($this)), 2); + $param = array_merge(array('module' => $this->modulePrefix . $moduleName[1], "action" => $name), $param); $url->setParent($this->part); $url->setQuery($param); diff --git a/src/Form/BrowserInput.php b/src/Form/BrowserInput.php new file mode 100644 index 0000000..f6e1e69 --- /dev/null +++ b/src/Form/BrowserInput.php @@ -0,0 +1,6 @@ +constructor = array( - 'input' => 'Form_Input', - 'inputreq' => 'Form_Input', // input с проверкой на заполненность + 'input' => 'ctiso\\Form\\Input', + 'inputreq' => 'ctiso\\Form\\Input', // input с проверкой на заполненность - 'date' => 'Form_Date', - 'datereq' => 'Form_Date', + 'date' => 'ctiso\\Form\\Date', + 'datereq' => 'ctiso\\Form\\Date', 'datetime' => 'TDateTime', - 'color' => 'Form_Color', - 'textarea' => 'Form_TextArea', - 'text' => 'Form_TextArea', - 'multiselect' => 'Form_SelectMany', + 'color' => 'ctiso\\Form\\Color', + 'textarea' => 'ctiso\\Form\\TextArea', + 'text' => 'ctiso\\Form\\TextArea', + 'multiselect' => 'ctiso\\Form\\SelectMany', // 'selectmany' => 'TSelectMany', - 'select1' => 'Form_SelectOne', - 'select' => 'Form_SelectOne', + 'select1' => 'ctiso\\Form\\SelectOne', + 'select' => 'ctiso\\Form\\SelectOne', 'questiontype'=> 'TQuestionType', 'secret' => 'TSecret', 'upload' => 'TUpload', 'image' => 'TUpload', 'checkbox' => 'TCheckbox', - 'checkmany' => 'Form_SelectMany', + 'checkmany' => 'ctiso\\Form\\SelectMany', 'hidden' => 'THidden', - 'radio' => 'Form_SelectOne', - 'filebrowser' => 'TComponentBrowserInput', - 'documents' => 'TComponentBrowserInput', + 'radio' => 'ctiso\\Form\\SelectOne', + 'filebrowser' => 'ctiso\\Form\\BrowserInput', + 'documents' => 'ctiso\\Form\\BrowserInput', ); } From 11370eecc90b26913df208510f4d7434b6e4e72f Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 4 May 2018 14:57:52 +0300 Subject: [PATCH 17/42] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D0=BD=D0=B0=D1=8F=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D1=8C=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=B2=D0=BC=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=BE=20=D0=BF=D1=80=D0=B5=D1=84=D0=B8=D0=BA=D1=81?= =?UTF-8?q?=D0=BD=D0=BE=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/Controller/Action.php | 12 ++++++------ src/Controller/Component.php | 24 ++++++++++++------------ src/Controller/Request.php | 2 +- src/Controller/Service.php | 4 ++-- src/Database.php | 12 ++++++------ src/Database/JsonInstall.php | 2 +- src/Database/Manager.php | 14 +++++++------- src/Database/Statement.php | 4 ++-- src/Database/StatementIterator.php | 2 +- src/Excel/Document.php | 2 +- src/Excel/Table.php | 12 ++++++------ src/Filter/ActionAccess.php | 4 ++-- src/Filter/ActionLogger.php | 7 ++++--- src/Filter/Filter.php | 2 +- src/Filter/Login.php | 2 +- src/Form/Field.php | 2 +- src/Functions.php | 8 ++++---- src/HttpRequest.php | 2 +- src/Layout/Manager.php | 4 ++-- src/MailAlt.php | 2 +- src/Path.php | 4 ++-- src/Role/User.php | 6 +++++- src/Role/UserInterface.php | 11 +++++++++++ src/Setup.php | 6 +++--- src/Tales.php | 4 ++-- src/Tools/SQLStatementExtractor.php | 2 +- src/Tools/TemplateImage.php | 2 +- src/Url.php | 2 +- src/Validator/Validator.php | 4 ++-- src/View/Page.php | 4 ++-- src/View/Pages.php | 2 +- src/View/Top.php | 2 +- 33 files changed, 95 insertions(+), 79 deletions(-) create mode 100644 src/Role/UserInterface.php diff --git a/src/Collection.php b/src/Collection.php index 1f977ee..ccc60cf 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -42,7 +42,7 @@ class Collection implements \ArrayAccess * * @return void */ - public function set(/*.string.*/$key, /*.any.*/$value) + public function set($key/*: string*/, $value/*: any*/) { $this->data[$key] = $value; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 34137af..d365a49 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -47,8 +47,8 @@ class Action private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки - public /*.Registry.*/$config; // Ссылка на настройки - public /*.User.*/$user; // Обьект пользователя + public $config/*: Registry*/; // Ссылка на настройки + public $user/*: User*/; // Обьект пользователя // Для Widgets public $view = null; @@ -124,7 +124,7 @@ class Action if(file_exists($template)) { break; } } - /*.Composite.*/$tpl = new $viewClass($template); + $tpl/*: Composite*/ = new $viewClass($template); $tpl->config = $this->config; $stylePath = Path::join($webPath, "assets", "css"); @@ -215,7 +215,7 @@ class Action */ public function nUrl($name, array $param = array()) { - /*.ActionAccess.*/$access = $this->access; + $access/*: ActionAccess*/ = $this->access; $url = new Url(); if ($access == null || $access->checkAction($name)) { @@ -334,7 +334,7 @@ class Action if ($view instanceof View) { $this->view->assignValues($this->ctrlValues); - /*.Composite.*/$node = null; + $node/*: Composite*/ = null; foreach ($this->childNodes as $name => $node) { $node->make($this); $this->view->setView($name, $node->view); @@ -373,7 +373,7 @@ class Action $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } - function redirect(/*.string.*/$action) { + function redirect($action/*: string*/) { header('location: ' . $action); exit(); } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 30d1904..655fbd5 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -49,9 +49,9 @@ class Component public $COMPONENTS_WEB; - public /*.Registry.*/$config; - public /*.Database.*/$db; - public /*.Collection.*/$parameter; + public $config/*: Registry*/; + public $db/*: Database*/; + public $parameter/*: Collection*/; public $output = 'html'; @@ -94,7 +94,7 @@ class Component return new FakeTemplate($name); } - /*.Registry.*/$config = $this->config; + $config/*: Registry*/ = $this->config; $default = $config->get('site', 'template'); $template = ($this->template) ? $this->template : $default; @@ -157,7 +157,7 @@ class Component return $model; } - public function options($key, $val, /*.PDOStatement.*/$res) { + public function options($key, $val, $res/*: PDOStatement*/) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val)); @@ -195,7 +195,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/ $view, $options = null) + public function setParameters($view/*: Composite*/, $options = null) { $form = new Form(); @@ -207,7 +207,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, /*.SiteInterface.*/ $site) + static function loadComponent($expression, $site/*: SiteInterface*/) { $expression = htmlspecialchars_decode($expression); @@ -227,7 +227,7 @@ class Component $path = Path::join ($this->config->get('site', 'path'), 'components', $name, $name . '.php'); $className = 'Component_' . $name; - /*.Component.*/$component = null; + $component/*: Component*/ = null; if (file_exists($path)) { require_once ($path); @@ -297,12 +297,12 @@ class Component return null; } - function raw_query(/*.ComponentRequest.*/ $request) + function raw_query($request/*: ComponentRequest*/) { $arr = $request->r->export('get'); $param = array(); - /*.Collection.*/$parameter = $this->parameter; + $parameter/*: Collection*/ = $this->parameter; foreach($parameter->export() as $key => $value) { $param[$key] = $value; } @@ -320,7 +320,7 @@ class Component } - function query(/*.ComponentRequest.*/ $request, $list) + function query($request/*: ComponentRequest*/, $list) { $arr = $request->r->export('get'); @@ -336,6 +336,6 @@ class Component $this->site->addRequireJsPath($name, $path, $shim); } - function actionIndex(/*.ComponentRequest.*/ $request) { + function actionIndex($request/*: ComponentRequest*/) { } } diff --git a/src/Controller/Request.php b/src/Controller/Request.php index e67ed7d..b9e77e9 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -7,7 +7,7 @@ class Request { public $r; public $id; - function __construct(/*.HttpRequest.*/$request, $id) { + function __construct($request/*: HttpRequest*/, $id) { $this->r = $request; $this->id = $id; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index fbcbb69..4992e50 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -12,7 +12,7 @@ class Service { public $viewPath = []; public $webPath = []; - public /*.Registry.*/$config; + public $config/*: Registry*/; public $template; public $templatePath; public $COMPONENTS_WEB; @@ -51,7 +51,7 @@ class Service return $model; } - public function options($key, $val, /*.PDOStatement.*/$res) { + public function options($key, $val, $res/*: PDOStatement*/) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 9ac4c6d..ebf717c 100644 --- a/src/Database.php +++ b/src/Database.php @@ -44,13 +44,13 @@ class Database extends PDO if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; - /*.Database.*/$connection = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); + $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); } } if ($dsn['phptype'] == 'sqlite') { - /*.Database.*/$connection = new static("{$dsn['phptype']}:{$dsn['database']}"); + $connection/*: Database*/ = new static("{$dsn['phptype']}:{$dsn['database']}"); $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); @@ -62,7 +62,7 @@ class Database extends PDO public function executeQuery($query, $values=null) { - /*.PDOStatement.*/$stmt = $this->prepare($query); + $stmt/*: PDOStatement*/ = $this->prepare($query); $stmt->execute($values); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -80,7 +80,7 @@ class Database extends PDO */ public function fetchAllArray($query, $values = null) { - /*.PDOStatement.*/$sth = $this->prepare($query); + $sth/*: PDOStatement*/ = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetchAll(PDO::FETCH_ASSOC); @@ -91,7 +91,7 @@ class Database extends PDO */ public function fetchOneArray($query, $values = null) { - /*.PDOStatement.*/$sth = $this->prepare($query); + $sth/*: PDOStatement*/ = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetch(PDO::FETCH_ASSOC); @@ -182,7 +182,7 @@ class Database extends PDO } function prepare($query, $options = NULL) { - /*.PDOStatement.*/$result = parent::prepare($query); + $result/*: PDOStatement*/ = parent::prepare($query); return $result; } diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 0395427..6acb9b7 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -43,7 +43,7 @@ class JsonInstall { } //Создать таблицы - function initDataBase(/*.array.*/$initActions, $dbinit_path) { + function initDataBase($initActions/*: array*/, $dbinit_path) { $pg = $this->db_manager->db->isPostgres(); if (!$pg) { $refs = []; diff --git a/src/Database/Manager.php b/src/Database/Manager.php index a0e46a5..354a722 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -8,13 +8,13 @@ use ctiso\Database, class Manager { - public /*.Database.*/$db; + public $db/*: Database*/; function __construct(Database $db) { $this->db = $db; } - public function ExecuteAction(/*.array.*/$action, $db_file = "") { + public function ExecuteAction($action/*: array*/, $db_file = "") { switch($action["type"]) { case "dropTable": $this->DropTableQuery($action["table_name"], true); @@ -100,7 +100,7 @@ class Manager return; } - /*.array.*/$data = $this->DumpTable($table); + $data/*: array*/ = $this->DumpTable($table); $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); $table_info[$new_name] = $table_info[$old_name]; @@ -147,7 +147,7 @@ class Manager $this->db->query($q); } - function getConstraintDef(/*.array.*/$c) { + function getConstraintDef($c/*: array*/) { if ($c['type'] == 'unique') { return "UNIQUE(" . implode(", ", $c['fields']) . ")"; } @@ -175,8 +175,8 @@ class Manager public function DumpTable($table_name) { $pg = $this->db->isPostgres(); - /*.array.*/$result = array(); - /*.array.*/$data = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); if (!$pg) { $table_fields = $this->TableInfo($table_name); @@ -184,7 +184,7 @@ class Manager $type = strtolower($value['type']); if ($type == "boolean") { foreach ($data as &$row) { - /*.array.*/$row = $row; + $row/*: array*/ = $row; if (isset($row[$name])) { $row[$name] = boolval($row[$name]); } diff --git a/src/Database/Statement.php b/src/Database/Statement.php index f47278f..b25b008 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -16,7 +16,7 @@ class Statement protected $conn; protected $query; - function __construct($query, /*.Database.*/ $conn) { + function __construct($query, $conn/*: Database*/) { $this->query = $query; $this->conn = $conn; } @@ -51,7 +51,7 @@ class Statement if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; } - /*.PDOStatement.*/$stmt = $this->conn->prepare($this->query); + $stmt/*: PDOStatement*/ = $this->conn->prepare($this->query); foreach ($this->binds as $bind) { list($n, $value, $type) = $bind; $stmt->bindValue($n, $value, (int) $type); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 6286a6d..aad0c90 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -11,7 +11,7 @@ class StatementIterator implements \Iterator private $fetchmode; private $row_count; - public function __construct(/*.PDOStatement.*/ $rs) { + public function __construct($rs/*: PDOStatement*/) { $this->result = $rs; $this->row_count = $rs->getRecordCount(); } diff --git a/src/Excel/Document.php b/src/Excel/Document.php index eba0654..dff1c3b 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -43,7 +43,7 @@ class Document { if ($type == 'Borders') { $doc->startElement('Borders'); foreach ($s as $border) { - /*.array.*/$border = $border; + $border/*: array*/ = $border; $doc->startElement('Border'); foreach ($border as $key => $value) { $doc->writeAttribute('ss:' . $key, $value); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 5a1786f..7754aa1 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -69,7 +69,7 @@ class Table if(! isset($this->rows[$x])) { $this->rows[$x] = new TableRow(); } - /*.TableRow.*/$row = $this->rows[$x]; + $row/*: TableRow*/ = $this->rows[$x]; $row->setCell($y, $value); } @@ -123,7 +123,7 @@ class Table assert(is_numeric($x) && $x > 0); assert(is_numeric($cell) && $cell > 0); - /*.TableRow.*/$row = $this->rows[$x]; + $row/*: TableRow*/ = $this->rows[$x]; $row->cells[$cell]->merge = $merge; } @@ -158,7 +158,7 @@ class Table */ function getRows() { - /*.array.*/$keys = array_keys($this->rows); + $keys/*: array*/ = array_keys($this->rows); return max($keys); } @@ -169,7 +169,7 @@ class Table */ function getRowCells(TableRow $row) { - /*.array.*/$keys = array_keys($row->cells); + $keys/*: array*/ = array_keys($row->cells); return max($keys); } @@ -207,7 +207,7 @@ class Table /** * Генерация клетки таблицы (Переработать) */ - function createCell (TableCell $ncell, XMLWriter $doc, $j, /*.any.*/$value, $setIndex) { + function createCell (TableCell $ncell, XMLWriter $doc, $j, $value/*: any*/, $setIndex) { $doc->startElement("Cell"); if ($ncell->style) { @@ -267,7 +267,7 @@ class Table $doc->writeAttribute('ss:Height', $this->rows[$i]->height); } - /*.TableRow.*/$nrow = $this->rows[$i]; + $nrow/*: TableRow*/ = $this->rows[$i]; // Флаг индикатор подстановки номера столбца $setIndex = false; for ($j = 1; $j <= $columns; $j++) { diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index c27b1b2..4fabc60 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -12,9 +12,9 @@ class ActionAccess { public $access = array(); public $processor; - public /*.User.*/$user; + public $user/*: User*/; - function __construct(/*.Filter.*/$processor, $user) { + function __construct($processor/*: Filter*/, $user) { $this->processor = $processor; $this->user = $user; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 403d3b0..09f497c 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -1,7 +1,8 @@ processor = $processor; $this->user = $user; @@ -27,7 +28,7 @@ class ActionLogger function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->name]; + $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->getName()]; fwrite($this->file, json_encode($message) . "\n"); } return $this->processor->execute($request); diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 864e898..156d4e0 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -11,7 +11,7 @@ use ctiso\Controller\Action, class Filter { public $processor; - public function __construct(/*.Action.*/$processor) + public function __construct($processor/*: Action*/) { $this->processor = $processor; } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 7d976bd..4362bc7 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -23,7 +23,7 @@ class Login extends Filter public $mode = 'ajax'; public $user; - public /*.User.*/$role; + public $role/*: User*/; public $whitelist; function __construct($processor, $role, $whitelist = []) { diff --git a/src/Form/Field.php b/src/Form/Field.php index 1e1dd47..83a23ea 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -40,7 +40,7 @@ class Field } } - function setValue(/*.any.*/$value) + function setValue($value/*: any*/) { $this->value = $value; } diff --git a/src/Functions.php b/src/Functions.php index fc1d5a8..be161bc 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -226,7 +226,7 @@ class Functions { * * @return mixed */ - static function key_values($key, /*array|ArrayIterator*/ $array) { + static function key_values($key, $array/*: array|ArrayIterator*/) { $result = array(); foreach($array as $item) { @@ -235,7 +235,7 @@ class Functions { return $result; } - static function key_values_object($key, /*array|ArrayIterator*/ $array) { + static function key_values_object($key, $array/*: array|ArrayIterator*/) { $result = array(); foreach($array as $item) { @@ -260,7 +260,7 @@ class Functions { return $result; } - static function _get($key, /*.any.*/$value, /*.array.*/$array) { + static function _get($key, $value/*: any*/, $array/*: array*/) { foreach ($array as $item) { if ($item[$key] == $value) return $item; } @@ -373,7 +373,7 @@ class Functions { * Преобразует ключи элементов для многомерного массива * @return mixed */ - static function hash_key ($key_name,/*. array .*/ $array) { + static function hash_key ($key_name,$array/*: array */) { $result = array(); foreach($array as $value) { diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 5e1b519..05c435e 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -56,7 +56,7 @@ class HttpRequest extends Collection implements ArrayAccess return $this->_session; } - function set($key, /*.any.*/$value) + function set($key, $value/*: any*/) { return parent::get('data')->set($key, $value); } diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 884fb3b..e843219 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -35,7 +35,7 @@ class Manager extends Filter $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } - public function checkGet(/*.HttpRequest.*/$request, $get) + public function checkGet($request/*: HttpRequest*/, $get) { if (is_array($get)) { foreach ($get as $key => $value) { @@ -47,7 +47,7 @@ class Manager extends Filter return true; } - public function checkXHR(/*.HttpRequest.*/$request, $get) + public function checkXHR($request/*: HttpRequest*/, $get) { return $request->isAjax() && $this->checkGet($request, $get); } diff --git a/src/MailAlt.php b/src/MailAlt.php index 138ae94..753dedf 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -51,7 +51,7 @@ class MailAlt /** * Тема письма */ - function subject(/*.string.*/$subject) + function subject($subject/*: string*/) { $this->mailer->Subject = $subject; } diff --git a/src/Path.php b/src/Path.php index 5234e73..1918571 100644 --- a/src/Path.php +++ b/src/Path.php @@ -160,7 +160,7 @@ class Path } // Сравнение двух путей на равентство - public function equal(/*.Path.*/ $path) + public function equal($path/*: Path*/) { $count = count($this->path); if ($count == count($path->path)) { @@ -205,7 +205,7 @@ class Path * * @return boolean */ - public function isParent(/*.Path.*/ $path) + public function isParent($path/*: Path*/) { if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; diff --git a/src/Role/User.php b/src/Role/User.php index f199363..8d3e892 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -5,7 +5,7 @@ use ctiso\Database, ctiso\Database\Statement; // Класс должен быть в библиотеке приложения -class User +class User implements UserInterface { const LIFE_TIME = 1800; // = 30min * 60sec; @@ -26,6 +26,10 @@ class User $this->db = $db; } + public function getName() { + return $this->name; + } + public function getUserByQuery(Statement $stmt) { $result = $stmt->executeQuery(); diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php new file mode 100644 index 0000000..778394d --- /dev/null +++ b/src/Role/UserInterface.php @@ -0,0 +1,11 @@ +stack[count($this->stack) - 1]; + $item/*: \SimpleXMLElement*/ = $this->stack[count($this->stack) - 1]; $root = $item->children(); foreach ($root as $node) { @@ -200,7 +200,7 @@ class Setup /** * Выполнение Списка SQL команд */ - function batchSQLZip(/*.Database.*/ $conn, $file) + function batchSQLZip($conn/*: Database*/, $file) { $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { @@ -208,7 +208,7 @@ class Setup } } - static function batchSQL(/*.Database.*/ $conn, $file) + static function batchSQL($conn/*: Database*/, $file) { $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { diff --git a/src/Tales.php b/src/Tales.php index b6fc45a..90ce298 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static /*.SiteInterface.*/$site; + static $site/*: SiteInterface*/; static function phptal_date ($e) { return date("d.m.Y", $e); @@ -47,7 +47,7 @@ class Tales { */ static function phptal_component ($expression) { $begin = floatval(microtime(true)); - /*.Component.*/$component = null; + $component/*: Component*/ = null; $component = self::$site->loadComponent($expression); $req = new HttpRequest(); diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index dd4df20..d6acd15 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -124,7 +124,7 @@ class SQLStatementExtractor { * @param string $string The string to check in (haystack). * @return boolean True if $string ends with $check, or they are equal, or $check is empty. */ - protected static function endsWith(/*.string.*/$check, $string) { + protected static function endsWith($check/*: string*/, $string) { if ($check === "" || $check === $string) { return true; } else { diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index fad2434..8dbb21e 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -122,7 +122,7 @@ class TemplateImage return ""; } - function imageText($text, /*.\stdClass.*/$value) + function imageText($text, $value/*: \stdClass*/) { assert(is_string($text)); diff --git a/src/Url.php b/src/Url.php index 5c824ab..f4393b0 100644 --- a/src/Url.php +++ b/src/Url.php @@ -4,7 +4,7 @@ namespace ctiso; class Url { public $parts = []; - public /*.Url.*/$parent; + public $parent/*: Url*/; function __construct() { } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index ed36f7f..0529662 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -74,7 +74,7 @@ class Validator } } - public function addRule(/*.any.*/$rule) { + public function addRule($rule/*: any*/) { if (is_array($rule)) { $this->chain = array_merge($this->chain, $rule); } else { @@ -82,7 +82,7 @@ class Validator } } - public function skip(/*.AbstractRule.*/$rule, /*.Collection.*/$container) // -> Rule_Abstract + public function skip($rule/*: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); diff --git a/src/View/Page.php b/src/View/Page.php index 3591abe..ec6b8f8 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public /*.SiteInterface.*/$site; + public $site/*: SiteInterface*/; function __construct($data, $site) { @@ -55,7 +55,7 @@ class Page extends View function replaceContent($match, $offset) { - /*.Component.*/$component = $this->site->loadComponent($match); + $component/*: Component*/ = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/View/Pages.php b/src/View/Pages.php index 8eb0767..1bba197 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -33,7 +33,7 @@ class Pages * @param $onpage int количество элем на странице * @return string */ - static function getLimit(/*.number.*/$page, /*.number.*/$onpage) { + static function getLimit($page/*: number*/, $onpage/*: number*/) { if ($page <= 0) { $page = 1; } return "LIMIT $onpage OFFSET " . ($page - 1) * $onpage; } diff --git a/src/View/Top.php b/src/View/Top.php index 08051f0..b3fd768 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -102,7 +102,7 @@ class Top extends Composite { $init = array(); foreach($s->_section as $key => $item) { - /*.View.*/$ss = $item; + $ss/*: View*/ = $item; if ($ss->codeGenerator !== null) { // функцию которая вычисляет а не результат $part = call_user_func($ss->codeGenerator, $this, $key, $value); From a09fc396d8d56c932a998a07f75ba84d46e30295 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 22 Nov 2022 12:46:15 +0300 Subject: [PATCH 18/42] fix --- src/Collection.php | 1 - src/ComponentRequest.php | 4 ++-- src/Controller/Action.php | 3 +-- src/Controller/Component.php | 10 ++++------ src/Filter/Authorization.php | 8 ++++---- src/Functions.php | 23 ++++++++++++----------- src/Role/User.php | 5 +++++ src/Role/UserInterface.php | 3 ++- src/View/View.php | 5 ----- 9 files changed, 30 insertions(+), 32 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index d2f662d..4eea3d1 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -1,6 +1,5 @@ r->getAction(); } -} \ No newline at end of file +} diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 4db58c5..cbfd202 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -1,8 +1,7 @@ set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); - $tpl->set('media', Path::join($this->config->get('system', 'templates_web'), $template)); + $tpl->set('media', Path::join($this->config->get('system', 'web'), 'templates', $template)); if ($default) { $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); @@ -244,13 +244,13 @@ class Component } $name = $path; - $path = Path::join ($site->config->get('site', 'path'), 'components', $name, $name . '.php'); - $className = 'Component_' . $name; + $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); + $className = 'Components\\'. ucfirst($name). '\\' . $name; $component/*: Component*/ = null; if (file_exists($path)) { - require_once ($path); + // require_once ($path); $component = new $className(); $component->viewPath = array($site->config->get('site', 'path') . '/components/' . $name . '/'); @@ -258,8 +258,6 @@ class Component $component->COMPONENTS_WEB = $site->config->get('site', 'web') . '/components/'; } else { - $path = Path::join ($site->config->get('system', 'components'), $name, $name . '.php'); - require_once ($path); $component = new $className(); $template = $component->getTemplateName($registry); diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 0538eb2..0df3e6f 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -11,14 +11,14 @@ class Authorization { $this->group = $group; } - function isLogged() { + static function isLogged($group = 'access') { // echo session_status(); if (session_status() == PHP_SESSION_NONE) { session_start(); } $hash = self::getBrowserSign(); // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию - if (isset($_SESSION[$this->group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { + if (isset($_SESSION[$group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { // UserAccess::getUserById($_SESSION ['access']); // Поиск по идентификатору return true; @@ -29,12 +29,12 @@ class Authorization { return false; } - function enter($id) { + static function enter($id, $group = 'access') { // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // session_register("access"); // session_register("time"); - $_SESSION [$this->group] = $id; + $_SESSION [$group] = $id; $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); $_SESSION ["time"] = time(); } diff --git a/src/Functions.php b/src/Functions.php index be161bc..ec3032a 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -101,7 +101,7 @@ class Functions { * @param mixed $a * @param mixed $b * - * @return array[int]mixed + * @return mixed */ static function compose($_rest) { $closure = new compose(func_get_args()); @@ -111,7 +111,7 @@ class Functions { /** * Карирование справа * - * @return array[int]mixed + * @return mixed */ static function rcurry($_rest) { $closure = new right(func_get_args ()); @@ -121,7 +121,7 @@ class Functions { /** * Карирование слева * - * @return array[int]mixed + * @return mixed */ static function lcurry($_rest) { $closure = new left(func_get_args ()); @@ -133,7 +133,7 @@ class Functions { * @param mixed $pred Условие по которому разделяется массив * @param array $lst * - * @return array[int]mixed + * @return mixed */ static function partition($pred, $lst) { $left = array (); @@ -329,19 +329,20 @@ class Functions { /** * Поиск элемента в массиве - * @param function $cb сравнение с элементом массива - * @param array $hs массив в котором ищется значение + * @param mixed $cb сравнение с элементом массива + * @param Array $hs массив в котором ищется значение * * @return int|string ключ найденого элемента в массиве */ static function array_usearch($cb, array $hs, $strict = false) { foreach($hs as $key => $value) if (call_user_func_array($cb, array($value, $key, $strict))) return $key; + return null; } /** * Выбирает все сроки из таблицы с уникальными значениями ключа - * @param $name Имя ключа - * @param $table Двухмерный массив + * @param string $name Имя ключа + * @param Array $table Двухмерный массив * @example * key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1))) => array (1, 2) @@ -359,9 +360,9 @@ class Functions { /** * Сортировка двумерного массива по заданному ключу - * @param $array Массив - * @param $key Имя ключа по значению которого будет идти сравнение - * @return Отсортированный массив + * @param Array $array Массив + * @param string $key Имя ключа по значению которого будет идти сравнение + * @return Array Отсортированный массив */ static function sortOn($array, $key, $fn = 'Functions::__cmp') { usort ($array, Functions::rcurry($fn, $key)); diff --git a/src/Role/User.php b/src/Role/User.php index d6b6671..a22cb13 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -30,6 +30,11 @@ class User implements UserInterface return $this->name; } + function isLogged() { + return \ctiso\Filter\Authorization::isLogged(); + } + + public function getUserByQuery(Statement $stmt) { $result = $stmt->executeQuery(); diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php index 778394d..295e4ca 100644 --- a/src/Role/UserInterface.php +++ b/src/Role/UserInterface.php @@ -1,11 +1,12 @@ _values["suggestions"] = $this->suggestions; } - public function jGrowl($message, $args) - { - $this->addScriptRaw('$.jGrowl("' . $message . '", ' . json_encode($args) . ");\n", true); - } - public function setGlobal($name, $args) { $this->addScriptRaw("var " . $name . " = " . json_encode($args) . ";\n", false); From 28429039a44309e0c522a7791f93649a5b606328 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 24 Nov 2022 19:12:00 +0300 Subject: [PATCH 19/42] =?UTF-8?q?ref=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82=D0=B8=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 8 ++-- src/Controller/Component.php | 4 +- src/Database/PDOStatement.php | 5 +- src/Form/OptionFactory.php | 87 ----------------------------------- src/Model/BaseMapper.php | 6 +++ src/Model/Factory.php | 2 +- src/Registry.php | 7 +++ src/UserMessageException.php | 3 +- 8 files changed, 24 insertions(+), 98 deletions(-) delete mode 100644 src/Form/OptionFactory.php create mode 100644 src/Model/BaseMapper.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index cbfd202..99391a6 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -101,9 +101,9 @@ class Action /** * Создает представление - * @param $name String - * @param $viewClass String - * @return View_Composite + * @param string + * @param string $viewClass + * @return Composite */ public function getView($name, $viewClass = 'ctiso\\View\\Composite') { @@ -163,7 +163,7 @@ class Action * Т.к действия являются методами класса то * 1. Можно переопределить действия * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение - * @param $request Обьект запроса + * @param HttpRequest $request запроса */ public function preProcess(HttpRequest $request) { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 630312d..4fb8fba 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -88,7 +88,7 @@ class Component } } - public function getTemplateName($_registry/*: Settings*/) { + public function getTemplateName($_registry/*: \ctiso\Settings*/) { return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) ? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern'); } @@ -147,7 +147,7 @@ class Component } public function getTemplatePath($name) { - $registry/*: Settings*/ = $this->config; + $registry/*: \ctiso\Settings*/ = $this->config; // Брать настройки из куков если есть $template = ($this->template) ? $this->template : $this->getTemplateName($registry); foreach ($this->viewPath as $index => $viewPath) { diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index d837669..af8c19f 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -5,6 +5,7 @@ namespace ctiso\Database; use ctiso\Database\StatementIterator, ctiso\Tools\StringUtil, PDO; +use TheSeer\Tokenizer\Exception; class PDOStatement extends \PDOStatement implements \IteratorAggregate { @@ -12,7 +13,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate public $cache = array(); public $fields; - function getIterator(): Iterator { + function getIterator(): \Iterator { return new StatementIterator($this); } @@ -73,7 +74,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate function getInt($name) { if (!$this->fields) { - throw new Error('no fields'); + throw new \Exception('no fields'); } return (int)$this->fields[$name]; } diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php deleted file mode 100644 index 724b3e6..0000000 --- a/src/Form/OptionFactory.php +++ /dev/null @@ -1,87 +0,0 @@ -db = $db; - $this->registry = $registry; - } - - function create(Form_Select $field, $input) { - if (isset($input['options.resid'])) { - $type = $input['options.resid']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.res'])) { - $type = $input['options.res']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.all_res'])) { - $type = $input['options.all_res']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); - - } else if (isset($input['options.db'])) { - list($table, $keyvalue) = explode(":", $input['options.db']); - list($key, $value) = explode(",", $keyvalue); - try { - $query_result = $this->db->executeQuery("SELECT * FROM $table"); - $field->options = $this->optionsDB($key, $value, $query_result); - } catch(Exception $ex) { - $field->options = []; - } - } elseif (isset($input['options.pair'])) { - $field->options = $this->optionsPair($input['options.pair']); - } elseif (isset($input['options.model'])) { - $factory = new Model_Factory($this->db, $this->registry); - $model = $factory->getModel($input['options.model']); - $field->options = $model->getAllAsOptions(); - } else { - $field->options = $input['options']; - } - if (isset($input['default'])) { - array_unshift($field->options, ['value' => 0, 'name' => $input['default']]); - } - - // Ставим корневой каталог в начало списка (скорее всего он будет в конце массива) - if ($field->options) - { - $root_elem = array_pop($field->options); - if ($root_elem['value'] == '/') - array_unshift($field->options, $root_elem); - else - array_push($field->options, $root_elem); - } - } - - public function optionsDB($key, $val, $res) { - $result = array(); - while($res->next()) { - $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); - } - return $result; - } - - public function optionsArray($key, $val, $res) { - $result = array(); - foreach($res as $item) { - $result[] = array('value' => $item->{$key}, 'name' => $item->{$val}); - } - return $result; - } - - public function optionsPair($list, $selected = false) { - $result = array(); - foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); - } - return $result; - } -} diff --git a/src/Model/BaseMapper.php b/src/Model/BaseMapper.php new file mode 100644 index 0000000..50cad30 --- /dev/null +++ b/src/Model/BaseMapper.php @@ -0,0 +1,6 @@ +namespace[$ns]['data'][$key])) { + return $this->namespace[$ns]['data'][$key]; + } + return null; + } + public function has($ns, $key) { return isset($this->namespace[$ns]['data'][$key]); } diff --git a/src/UserMessageException.php b/src/UserMessageException.php index 1049dc9..226eb75 100644 --- a/src/UserMessageException.php +++ b/src/UserMessageException.php @@ -4,9 +4,8 @@ * @see Controller_Front */ namespace ctiso; -use Exception; -class UserMessageException extends Exception { +class UserMessageException extends \Exception { public $userMessage; public function __construct($message) { parent::__construct($message); From 526262c80ba65fbf42eb3645d8d820457b0af033 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 28 Nov 2022 18:44:09 +0300 Subject: [PATCH 20/42] fix Validator --- src/Controller/Action.php | 1 + src/Controller/Component.php | 5 ++-- src/Controller/Front.php | 1 + src/Controller/SiteInterface.php | 1 + src/Registry.php | 16 ------------ src/Settings.php | 21 +++++++++++---- .../Rule/{Match.php => MatchRule.php} | 2 +- src/Validator/Validator.php | 26 +++++++++---------- src/View/View.php | 4 +-- 9 files changed, 38 insertions(+), 39 deletions(-) rename src/Validator/Rule/{Match.php => MatchRule.php} (92%) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 99391a6..998f735 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -26,6 +26,7 @@ class Action // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля + public $front; public $modulePath = null; // Путь к модулю public $moduleTitle = ''; diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 4fb8fba..e4b54da 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -171,8 +171,9 @@ class Component */ public function getModel($name) { - $modelName = "Mapper_" . $name; + $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); + $model->config = $this->config; $model->db = $this->db; return $model; } @@ -260,7 +261,7 @@ class Component } else { $component = new $className(); - $template = $component->getTemplateName($registry); + $template = $component->getTemplateName($site->config); $component->viewPath = array( // Сначало ищем локально diff --git a/src/Controller/Front.php b/src/Controller/Front.php index b8c3bae..2e1cc1d 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -67,6 +67,7 @@ class Front extends Action $module->config = $this->config; $module->db = $this->db; $module->user = $this->user; + $module->front = $this; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index 205e5ea..1125601 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -3,6 +3,7 @@ namespace ctiso\Controller; interface SiteInterface { + function getResource(); function loadComponent($expression); function getDatabase(); function getConfig(); diff --git a/src/Registry.php b/src/Registry.php index c9c9fac..21e08eb 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -48,20 +48,4 @@ class Registry { function set($ns, $key, $value) { $this->namespace[$ns]['data'][$key] = $value; } - - /** - * Список модулей - */ - public function getModules() - { - return array_keys($this->data); - } - - /** - * Проверка наличия модуля - */ - public function hasModule($name) - { - return isset($this->data[$name]); - } } diff --git a/src/Settings.php b/src/Settings.php index c7c96b1..1325830 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -156,11 +156,6 @@ class Settings $name = array_shift($key); unset($data[$name]); } - - public function getOwner() - { - return array_keys($this->data); - } /** * Запись настроек в файл (Может переименовать в store) @@ -195,4 +190,20 @@ class Settings function import($data) { $this->data = $data; } + + /** + * Список модулей/ключей + */ + public function getKeys() + { + return array_keys($this->data); + } + + /** + * Проверка наличия ключа + */ + public function hasKey($name) + { + return isset($this->data[$name]); + } } diff --git a/src/Validator/Rule/Match.php b/src/Validator/Rule/MatchRule.php similarity index 92% rename from src/Validator/Rule/Match.php rename to src/Validator/Rule/MatchRule.php index 7f8b999..d54f448 100644 --- a/src/Validator/Rule/Match.php +++ b/src/Validator/Rule/MatchRule.php @@ -7,7 +7,7 @@ namespace ctiso\Validator\Rule; use ctiso\Validator\Rule\AbstractRule, ctiso\Collection; -class Match extends AbstractRule +class MatchRule extends AbstractRule { public $same; diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 0529662..88fd870 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -28,19 +28,19 @@ class Validator public function addRuleList(array $input) { $type = array( - 'date' => 'Validator_Rule_Date', - 'email' => 'Validator_Rule_Email', - 'emaillist'=> 'Validator_Rule_EmailList', - 'match' => 'Validator_Rule_Match', - 'time' => 'Validator_Rule_Time', - 'alpha' => 'Validator_Rule_Alpha', - 'require' => 'Validator_Rule_Notnull', - 'numeric' => 'Validator_Rule_Numeric', - 'unique' => 'Validator_Rule_Unique', - 'filename' => 'Validator_Rule_FileName', - 'count' => 'Validator_Rule_Count', - 'isfile' => 'Validator_Rule_IsFile', - 'code' => 'Validator_Rule_Code' + 'date' => 'ctiso\\Validator\\Rule\\Date', + 'email' => 'ctiso\\Validator\\Rule\\Email', + 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', + 'match' => 'ctiso\\Validator\\Rule\\MatchRule', + 'time' => 'ctiso\\Validator\\Rule\\Time', + 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', + 'require' => 'ctiso\\Validator\\Rule\\Notnull', + 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', + 'unique' => 'ctiso\\Validator\\Rule\\Unique', + 'filename' => 'ctiso\\Validator\\Rule\\FileName', + 'count' => 'ctiso\\Validator\\Rule\\Count', + 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', + 'code' => 'ctiso\\Validator\\Rule\\Code' ); // Разбор правила проверки diff --git a/src/View/View.php b/src/View/View.php index 54000d8..088cd43 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -31,9 +31,9 @@ class View * Связывет переменную с вложенным шаблоном * * @param string $section переменная шаблона - * @param CompositeView $view вложенный шаблон + * @param View|string $view вложенный шаблон */ - public function setView($section, /*View_View|string*/ $view) + public function setView($section, $view/*: View|string*/) { $this->_section [$section] = $view; if (is_object($view)) { From aaba3d758542fe967b511e55f428f219bb8a6b0b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 29 Nov 2022 16:15:58 +0300 Subject: [PATCH 21/42] fix type --- src/Controller/Action.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 998f735..e40e3f1 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -211,7 +211,7 @@ class Action * @param string $name Действие * @param array $param Дополнительные параметры * 'mode' означает что элемент до отправки обрабатывается javascript - * @return array|null + * @return Url|null */ public function nUrl($name, array $param = array()) { From 7fd7c4fd123b0b2bc9e0f91e3dc8e195b3ce1fec Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 8 Dec 2022 18:40:00 +0300 Subject: [PATCH 22/42] =?UTF-8?q?fix=20=D0=9A=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=BB=D0=B5=D0=B9=20?= =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D1=8B=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B2=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Form/CheckBox.php | 14 ++++++++++ src/Form/DateTime.php | 7 +++++ src/Form/Form.php | 59 ++++++++------------------------------- src/Form/Hidden.php | 8 ++++++ src/Form/QuestionType.php | 16 +++++++++++ src/Form/Secret.php | 10 +++++++ src/Form/Upload.php | 7 +++++ 8 files changed, 74 insertions(+), 49 deletions(-) create mode 100644 src/Form/CheckBox.php create mode 100644 src/Form/DateTime.php create mode 100644 src/Form/Hidden.php create mode 100644 src/Form/QuestionType.php create mode 100644 src/Form/Secret.php create mode 100644 src/Form/Upload.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index e40e3f1..485bd3c 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -234,7 +234,7 @@ class Action * Ajax определяется автоматически mode = ajax используется для смены layout * @param $name * @param array $param - * @return array|null + * @return Url|null * * @example ?action=$name&mode=ajax * {$param[i].key = $param[i].value} diff --git a/src/Form/CheckBox.php b/src/Form/CheckBox.php new file mode 100644 index 0000000..ea5f880 --- /dev/null +++ b/src/Form/CheckBox.php @@ -0,0 +1,14 @@ +value = $value; + $this->checked = $value; + } +} diff --git a/src/Form/DateTime.php b/src/Form/DateTime.php new file mode 100644 index 0000000..4f995fb --- /dev/null +++ b/src/Form/DateTime.php @@ -0,0 +1,7 @@ +value = $value; - $this->checked = $value; - } -} - -class TQuestionType extends Select -{ - function setValue($value) - { - // Установить selected у options - $this->value = $value; - foreach ($this->options as &$option) { - $option['selected'] = ($option['value'] == $value); - } - } -} - -class TDateTime extends Input { -} - -/** - * Поле для ввода пароля - */ -class TSecret extends Field { -} - -class TUpload extends Field { -} - -class THidden extends Input { - public $hidden = true; -} - /** * Форма для ввода */ @@ -75,29 +37,30 @@ class Form extends View { { $this->constructor = array( 'input' => 'ctiso\\Form\\Input', - 'inputreq' => 'ctiso\\Form\\Input', // input с проверкой на заполненность + // input с проверкой на заполненность + 'inputreq' => 'ctiso\\Form\\Input', 'date' => 'ctiso\\Form\\Date', 'datereq' => 'ctiso\\Form\\Date', - 'datetime' => 'TDateTime', + 'datetime' => 'ctiso\\Form\\DateTime', 'color' => 'ctiso\\Form\\Color', 'textarea' => 'ctiso\\Form\\TextArea', 'text' => 'ctiso\\Form\\TextArea', 'multiselect' => 'ctiso\\Form\\SelectMany', -// 'selectmany' => 'TSelectMany', 'select1' => 'ctiso\\Form\\SelectOne', 'select' => 'ctiso\\Form\\SelectOne', - 'questiontype'=> 'TQuestionType', - 'secret' => 'TSecret', - 'upload' => 'TUpload', - 'image' => 'TUpload', - 'checkbox' => 'TCheckbox', + + 'questiontype'=> 'ctiso\\Form\\QuestionType', + 'secret' => 'ctiso\\Form\\Secret', + 'upload' => 'ctiso\\Form\\Upload', + 'image' => 'ctiso\\Form\\Upload', + 'checkbox' => 'ctiso\\Form\\CheckBox', 'checkmany' => 'ctiso\\Form\\SelectMany', - 'hidden' => 'THidden', + 'hidden' => 'ctiso\\Form\\Hidden', 'radio' => 'ctiso\\Form\\SelectOne', 'filebrowser' => 'ctiso\\Form\\BrowserInput', - 'documents' => 'ctiso\\Form\\BrowserInput', + 'documents' => 'ctiso\\Form\\BrowserInput', 'chooser' => 'ctiso\\Form\\Input', 'select_chooser' => 'ctiso\\Form\\SelectOne' ); diff --git a/src/Form/Hidden.php b/src/Form/Hidden.php new file mode 100644 index 0000000..535e21b --- /dev/null +++ b/src/Form/Hidden.php @@ -0,0 +1,8 @@ +value = $value; + foreach ($this->options as &$option) { + $option['selected'] = ($option['value'] == $value); + } + } +} diff --git a/src/Form/Secret.php b/src/Form/Secret.php new file mode 100644 index 0000000..ce0175a --- /dev/null +++ b/src/Form/Secret.php @@ -0,0 +1,10 @@ + Date: Fri, 9 Dec 2022 16:09:40 +0300 Subject: [PATCH 23/42] =?UTF-8?q?fix=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=BE=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 9 ++++++--- src/Layout/Manager.php | 6 ++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 485bd3c..241b3df 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -30,7 +30,6 @@ class Action public $modulePath = null; // Путь к модулю public $moduleTitle = ''; - public $modulePrefix = ''; public $viewPathPrefix = null; // Путь к шаблонам контроллера @@ -219,8 +218,12 @@ class Action $url = new Url(); if ($access == null || $access->checkAction($name)) { - $moduleName = explode("\\", strtolower(get_class($this)), 2); - $param = array_merge(array('module' => $this->modulePrefix . $moduleName[1], "action" => $name), $param); + $moduleName = explode("\\", strtolower(get_class($this))); + array_shift($moduleName); + if ($moduleName[0] == $moduleName[1]) { + array_shift($moduleName); + } + $param = array_merge(array('module' => implode("\\", $moduleName), "action" => $name), $param); $url->setParent($this->part); $url->setQuery($param); diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index e843219..d687113 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -67,17 +67,15 @@ class Manager extends Filter */ public function execute(HttpRequest $request) { -// print_r($request->get('mode')); foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { $layout = $condition[1]; $view = $layout->execute($request); if (is_object($view)) { - echo $view->render(); + return $view->render(); } else { - echo $view; + return $view; } - return null; } } } From 73112f5bf0b648380365bfa103a1b71ce958ad10 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 9 Dec 2022 17:39:23 +0300 Subject: [PATCH 24/42] =?UTF-8?q?fix=20=D0=9F=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B0=D1=87=D0=B0=20=D0=BE=D0=B1=D1=8C=D0=B5=D0=BA=D1=82=D0=B0?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B2=20=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Database.php | 2 +- src/Model/Factory.php | 7 +++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 241b3df..4309caf 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -153,7 +153,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->config); + $this->factory = new Factory($this->db, $this->config, $this->user); } return $this->factory->getModel($name); } diff --git a/src/Database.php b/src/Database.php index 3cb15b6..b2ac6ca 100644 --- a/src/Database.php +++ b/src/Database.php @@ -30,7 +30,7 @@ class Database/**/ extends PDO $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); } - function prepare($sql, $args = []) { + function prepare($sql, $args = []) { $result/*: PDOStatement*/ = parent::prepare($sql, $args); return $result; } diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 031ce43..39d30ca 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -2,17 +2,19 @@ namespace ctiso\Model; use ctiso\Registry, - ctiso\Database; + ctiso\Database, + ctiso\Role\User; class Factory { public $db; public $config; - public function __construct (Database $db, Registry $config = null) + public function __construct (Database $db, Registry $config = null, User $user) { $this->db = $db; $this->config = $config; + $this->user = $user; } /** @@ -27,6 +29,7 @@ class Factory $model->db = $this->db; $model->factory = $this; $model->config = $this->config; + $model->user = $this->user; $model->setUp(); // return $model; From ab13ebd2897164326313e4e440fefb327fa0d3d4 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 15 Dec 2022 15:50:40 +0300 Subject: [PATCH 25/42] =?UTF-8?q?fix=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=83=D1=82=D0=B8?= =?UTF-8?q?=20=D0=BA=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Front.php | 25 ++++++++++++++----------- src/Form/Form.php | 2 +- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 2e1cc1d..d5e6d12 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -44,23 +44,31 @@ class Front extends Action * @param Request $request Имя модуля * @return string */ - public function loadModule($name, Collection $request, $controller = null) + public function loadModule($name, Collection $request) { if ($this->isLoaded($name)) { $module = $this->modules[$name]; return $module->access->execute($request); } + + $parts = explode('\\', $name); + $config = $this->config; $moulesPath = Path::join($config->get('system', 'path'), 'modules'); $logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log')); - $ucname = ucfirst($name); - $moduleClass = "Modules\\$ucname\\$ucname"; + $first = $parts[0]; + $second = (count($parts) >= 2) ? $parts[1] : $parts[0]; + + $ucname = ucfirst($first); + $ucpart = ucfirst($second); + + $moduleClass = "Modules\\$ucname\\$ucpart"; $module = new $moduleClass(); if ($module) { // Инициализация модуля - $modPath = Path::join($moulesPath, $name); + $modPath = Path::join($moulesPath, $first); $module->modulePath = $modPath; $module->name = $name; // @@ -87,14 +95,9 @@ class Front extends Action public function execute(HttpRequest $request) { - $name = explode("\\", $request->get('module', $this->default)); - if (count($name) >= 2) { - $controller = $name[1]; - } else { - $controller = null; - } + $name = $request->get('module', $this->default); try { - return $this->loadModule($name[0], $request, $controller); + return $this->loadModule($name, $request); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); if ($mode == 'ajax' || $mode == 'json') { diff --git a/src/Form/Form.php b/src/Form/Form.php index f14360c..d5e7582 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -167,7 +167,7 @@ class Form extends View { { foreach ($schema as $key => $conv) { list($value, $type) = $conv; - $this->field [$key]->setValue(call_user_func(array('Primitive', 'from_' . $type), $data->$value)); + $this->field [$key]->setValue(call_user_func(array('ctiso\\Primitive', 'from_' . $type), $data->$value)); } } From 36b7d93a981e009e634c65db18bf7fa862c38073 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 15 Dec 2022 18:16:58 +0300 Subject: [PATCH 26/42] =?UTF-8?q?fix=20=D0=9F=D1=80=D0=B8=20=D1=83=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B5=20=D0=BC=D0=BE=D0=B4?= =?UTF-8?q?=D1=83=D0=BB=D1=8F=20=D0=BD=D0=B5=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D0=BE=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D0=BB=D0=B8=D1=81=D1=8C=20=D0=BD=D0=B0=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B9=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Controller/Installer.php | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 4309caf..ee955f5 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -82,7 +82,7 @@ class Action public function installPath($name) { - $basePath = $this->config->get('site', 'path'); + $basePath = $this->config->get('system', 'path'); return Path::join($basePath, "modules", $name); } diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index e544921..2adff19 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -94,20 +94,20 @@ class Installer $sql = $settings->get('sql'); if (is_array($sql)) { $res = $this->installSQL($sql, $version_new, $version_old, $name); - if($res){ + if ($res) { $result[]=$res; } } - - // Обновление версии меню - $registry->removeKey($name); - - $registry->set($name, $settings->get('settings')); - $registry->set($name, - array('version' => $version_new, - 'time' => filemtime($setup))); } + // Обновление версии меню + $registry->removeKey($name); + $registry->set($name, [ + 'version' => $version_new, + 'time' => filemtime($setup) + ]); + $registry->writeKey([$name], $settings->get('settings')); + $registry->write(); } return $result; From d9b6faafc6c833e5b85e4ea9d20a395423b3f2bf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Dec 2022 12:38:01 +0300 Subject: [PATCH 27/42] =?UTF-8?q?fix=20=D0=94=D0=BE=D0=BF.=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=B8=D0=BC=D0=B5=D0=BD=D0=B8=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE=D1=85=D0=BE?= =?UTF-8?q?=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 7 ++++--- src/Database.php | 4 ++-- src/Settings.php | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index ee955f5..2066995 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -14,7 +14,6 @@ use Exception, ctiso\Filter\ActionAccess, ctiso\View\View, ctiso\Controller\State; - /** * Контроллер страниц */ @@ -219,9 +218,11 @@ class Action if ($access == null || $access->checkAction($name)) { $moduleName = explode("\\", strtolower(get_class($this))); - array_shift($moduleName); - if ($moduleName[0] == $moduleName[1]) { + if (count($moduleName) > 2) { array_shift($moduleName); + if ($moduleName[0] == $moduleName[1]) { + array_shift($moduleName); + } } $param = array_merge(array('module' => implode("\\", $moduleName), "action" => $name), $param); diff --git a/src/Database.php b/src/Database.php index b2ac6ca..ad989d7 100644 --- a/src/Database.php +++ b/src/Database.php @@ -48,8 +48,8 @@ class Database/**/ extends PDO static function getConnection(array $dsn) { - if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { - $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; + if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { + $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); diff --git a/src/Settings.php b/src/Settings.php index 1325830..d443681 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -46,7 +46,7 @@ class Settings } if (!is_array($settings)) { - throw new Exception($this->file); + throw new Exception('no data in ' . $this->file); } $this->data = $settings; From c912ceebb9d16ef9cfb45e640cf7967974a52396 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Dec 2022 19:17:09 +0300 Subject: [PATCH 28/42] =?UTF-8?q?fix=20=D0=97=D0=B0=D0=BF=D1=8F=D1=82?= =?UTF-8?q?=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Form/Form.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Form/Form.php b/src/Form/Form.php index 8be991b..343f254 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -62,7 +62,7 @@ class Form extends View { 'filebrowser' => 'ctiso\\Form\\BrowserInput', 'documents' => 'ctiso\\Form\\BrowserInput', 'chooser' => 'ctiso\\Form\\Input', - 'select_chooser' => 'ctiso\\Form\\SelectOne' + 'select_chooser' => 'ctiso\\Form\\SelectOne', 'html_text' => 'ctiso\\Form\\HtmlText' ); From e4527ad94e73680ec18f7ead2b84a91e7366a574 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 26 Jan 2023 19:42:10 +0300 Subject: [PATCH 29/42] fix Component class name --- src/Controller/Component.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index e4b54da..badc2f0 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -246,7 +246,7 @@ class Component $name = $path; $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = 'Components\\'. ucfirst($name). '\\' . $name; + $className = 'Components\\'. ucfirst($name). '\\' . ucfirst($name); $component/*: Component*/ = null; From b3f6cfcbd7fe74b05b45de09106b9147a162d20e Mon Sep 17 00:00:00 2001 From: System Administrator Date: Mon, 30 Jan 2023 18:28:45 +0300 Subject: [PATCH 30/42] fix tabletree --- src/{process.php => Process.php} | 0 src/{tabletree.php => TableTree.php} | 26 ++++++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) rename src/{process.php => Process.php} (100%) rename src/{tabletree.php => TableTree.php} (50%) diff --git a/src/process.php b/src/Process.php similarity index 100% rename from src/process.php rename to src/Process.php diff --git a/src/tabletree.php b/src/TableTree.php similarity index 50% rename from src/tabletree.php rename to src/TableTree.php index 0d9203a..70b3cb6 100644 --- a/src/tabletree.php +++ b/src/TableTree.php @@ -19,17 +19,19 @@ namespace ctiso; use ctiso\Functions; -function tableTreeWalk($level, $table, $fn) { - if (empty ($level)) return $table; - $name = array_shift ($level); - - $keys = Functions::key_unique_values($name, $table); - $data = array (); - foreach ($keys as $index) { - list($rows, $table) = Functions::partition (Functions::lcurry(['Functions', '__index'], $index, $name), $table); -// $rows = array_filter ($table, lcurry('__index', intval($index), $name)); - //$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);')); - $data[$index] = call_user_func ($fn, $name, $index, $rows, tableTreeWalk ($level, $rows, $fn)); +class TableTree { + static function walk($level, $table, $fn) { + if (empty ($level)) return $table; + $name = array_shift ($level); + + $keys = Functions::key_unique_values($name, $table); + $data = array (); + foreach ($keys as $index) { + list($rows, $table) = Functions::partition (Functions::lcurry(['\ctiso\Functions', '__index'], $index, $name), $table); + // $rows = array_filter ($table, lcurry('__index', intval($index), $name)); + //$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);')); + $data[$index] = call_user_func ($fn, $name, $index, $rows, self::walk ($level, $rows, $fn)); + } + return $data; } - return $data; } From 0c3fba0d7e3d131f02efe61bc8c7e7bb226eb15f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 31 Jan 2023 10:49:00 +0300 Subject: [PATCH 31/42] =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 8 +++++--- src/Model/Factory.php | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index badc2f0..f0c6647 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -208,9 +208,11 @@ class Component $filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json'); if (file_exists($filename)) { $settings = json_decode(File::getContents($filename), true); - return $settings; + if ($settings) { + return $settings; + } } - return array(); + return array('parameter' => []); } /** @@ -246,7 +248,7 @@ class Component $name = $path; $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = 'Components\\'. ucfirst($name). '\\' . ucfirst($name); + $className = implode("\\", ['Components', ucfirst($name), ucfirst($name)]); $component/*: Component*/ = null; diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 39d30ca..dd99fd7 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -10,7 +10,7 @@ class Factory public $db; public $config; - public function __construct (Database $db, Registry $config = null, User $user) + public function __construct (Database $db, Registry $config = null, User $user = null) { $this->db = $db; $this->config = $config; From fff5b7b5c41890ce568b16d79af0f346cd517b21 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Feb 2023 12:55:02 +0300 Subject: [PATCH 32/42] =?UTF-8?q?fix=20=D0=A0=D0=B0=D1=81=D1=87=D0=B5?= =?UTF-8?q?=D1=82=20=D0=BF=D1=83=D1=82=D0=B5=D0=B9=20=D0=B4=D0=BE=20=D1=88?= =?UTF-8?q?=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=BE=D0=B2=20=D0=B8=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 37 ++++++++++++++++++------------------ src/Functions.php | 2 +- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index f0c6647..02bdd9f 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -128,10 +128,10 @@ class Component $tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); - $tpl->set('media', Path::join($this->config->get('system', 'web'), 'templates', $template)); + $tpl->set('media', Path::join($this->config->get('system', 'templates.web'), $template)); if ($default) { - $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); + $tpl->set('site_template', $this->config->get('site', 'templates.web') . $default); } $tpl->set('base', $this->config->get('site', 'web')); @@ -246,9 +246,11 @@ class Component parse_str($query, $arguments); } $name = $path; + $config = $site->config; - $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = implode("\\", ['Components', ucfirst($name), ucfirst($name)]); + $filename = ucfirst($name); + $path = Path::join ($config->get('site', 'components'), $name, $filename . '.php'); + $className = implode("\\", ['Components', ucfirst($name), $filename]); $component/*: Component*/ = null; @@ -256,35 +258,34 @@ class Component // require_once ($path); $component = new $className(); - $component->viewPath = array($site->config->get('site', 'path') . '/components/' . $name . '/'); - $component->webPath = array($site->config->get('site', 'web') . '/components/' . $name); - $component->COMPONENTS_WEB = $site->config->get('site', 'web') . '/components/'; + $component->viewPath = array($config->get('site', 'components') . '/' . $name . '/'); + $component->webPath = array($config->get('site', 'components.web') . '/' . $name); + $component->COMPONENTS_WEB = $config->get('site', 'web') . '/components/'; } else { $component = new $className(); - $template = $component->getTemplateName($site->config); $component->viewPath = array( // Сначало ищем локально - $site->config->get('site', 'path') . '/templates/' . $template . '/_components/' . $name . '/', - $site->config->get('site', 'path') . '/components/' . $name . '/', + $config->get('site', 'templates') . '/'. $template . '/_components/' . $name . '/', + $config->get('site', 'components') . '/' . $name . '/', // Потом в общем хранилище - CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/', - $site->config->get('system', 'components') . '/' . $name . '/', + $config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/', + $config->get('system', 'components') . '/' . $name . '/', ); if (defined('COMPONENTS_WEB')) { $component->webPath = array( // Сначало локально - $site->config->get('site', 'web') . '/templates/' . $template . '/_components/' . $name, - $site->config->get('site', 'web') . '/components/' . $name, + $config->get('site', 'templates.web') . '/' . $template . '/_components/' . $name, + $config->get('site', 'components.web') . '/' . $name, // Потом в общем хранилище - TEMPLATE_WEB . '/' . $template . '/_components/' . $name, - COMPONENTS_WEB . '/' . $name, + $config->get('system', 'templates.web') . '/' . $template . '/_components/' . $name, + $config->get('system', 'components.web') . '/' . $name, ); - $component->COMPONENTS_WEB = COMPONENTS_WEB; + $component->COMPONENTS_WEB = $config->get('system', 'components.web'); } else { - $component->webPath = array('', $site->config->get('site', 'web') . '/components/' . $name, ''); + $component->webPath = array('', $config->get('site', 'components.web') . '/' . $name, ''); } } diff --git a/src/Functions.php b/src/Functions.php index ec3032a..1c64ed1 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -364,7 +364,7 @@ class Functions { * @param string $key Имя ключа по значению которого будет идти сравнение * @return Array Отсортированный массив */ - static function sortOn($array, $key, $fn = 'Functions::__cmp') { + static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { usort ($array, Functions::rcurry($fn, $key)); //usort ($array, create_function ('$x,$y', 'return __cmp ($x, $y, "'.$key.'");')); return $array; From 8321ec244f6a93937590de8626f2cb529962128c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 16 Feb 2023 16:18:29 +0300 Subject: [PATCH 33/42] =?UTF-8?q?fix=20=D0=9D=D0=B5=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D1=8B=D0=B2=D0=B0=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9?= =?UTF-8?q?=D0=BB=20=D0=B5=D1=81=D0=BB=D0=B8=20=D0=BE=D0=BD=20=D0=BD=D0=B5?= =?UTF-8?q?=D0=B1=D1=8B=D0=BB=20=D0=BF=D1=80=D0=BE=D1=87=D1=82=D0=B5=D0=BD?= =?UTF-8?q?,=20=D0=B8=D0=BD=D0=B0=D1=87=D0=B5=20=D0=BC=D0=BE=D0=B6=D0=B5?= =?UTF-8?q?=D0=BC=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Settings.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Settings.php b/src/Settings.php index 69afd15..8345c1c 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -18,6 +18,7 @@ class Settings public $data = []; protected $file; protected $format = 'php'; + protected $is_read = false; public function __construct ($file = null, $format = false) { @@ -35,6 +36,7 @@ class Settings public function read() { if (!file_exists ($this->file)) { + $this->is_read = true; return false; } // Не include_once т.к читать настройки можно несколько раз @@ -49,6 +51,7 @@ class Settings throw new Exception('no data in ' . $this->file); } + $this->is_read = true; $this->data = $settings; return true; } @@ -165,6 +168,10 @@ class Settings */ public function write($file = null) { + if (!$this->is_read) { + throw new Exception('read settings before write'); + } + if ($this->format == 'json') { $result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else { From 949510924a8340341cf4e76edaeee77f443fa4b9 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 27 Feb 2023 16:47:34 +0300 Subject: [PATCH 34/42] =?UTF-8?q?fix=20=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Form/Upload.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 02bdd9f..a7ce660 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -131,7 +131,7 @@ class Component $tpl->set('media', Path::join($this->config->get('system', 'templates.web'), $template)); if ($default) { - $tpl->set('site_template', $this->config->get('site', 'templates.web') . $default); + $tpl->set('site_template', Path::join($this->config->get('site', 'templates.web'), $default)); } $tpl->set('base', $this->config->get('site', 'web')); diff --git a/src/Form/Upload.php b/src/Form/Upload.php index 3da54f8..7cd38b8 100644 --- a/src/Form/Upload.php +++ b/src/Form/Upload.php @@ -3,5 +3,5 @@ namespace ctiso\Form; use ctiso\Form\Field; -class TUpload extends Field { +class Upload extends Field { } From ca2bcc428f6b1d6486e1b2dec8ebe0222326d78c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Mar 2023 12:05:27 +0300 Subject: [PATCH 35/42] =?UTF-8?q?fix=20=D0=9E=D0=BF=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Tales.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Tales.php b/src/Tales.php index eb598c6..5937db2 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -52,7 +52,7 @@ class Tales { } static function phptal_asset($s) { - self::$sit->addStyleSheet($s); + self::$site->addStyleSheet($s); return ""; } From 7c0a5ab310cdb849d97a160f1f6849f5f90cb67a Mon Sep 17 00:00:00 2001 From: System Administrator Date: Thu, 16 Mar 2023 16:27:52 +0300 Subject: [PATCH 36/42] =?UTF-8?q?fix=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ComponentRequest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php index 15db81b..6bc7dbc 100644 --- a/src/ComponentRequest.php +++ b/src/ComponentRequest.php @@ -19,7 +19,8 @@ class ComponentRequest { if ($key == 'active_page') { return $this->r->get($key); } - if ($arr = $this->r->get($key)) { + $arr = $this->r->get($key); + if (!is_null($arr)) { if (is_array($arr)) { return Arr::get($arr, $this->component_id, $default); } else { From 93c0a67241c0e4646e58c76fe7d6ad6e9664d2a8 Mon Sep 17 00:00:00 2001 From: anatoly Date: Fri, 31 Mar 2023 18:09:34 +0300 Subject: [PATCH 37/42] creating views --- src/Database/Manager.php | 409 ++++++++++++++++++++------------------- 1 file changed, 209 insertions(+), 200 deletions(-) diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 354a722..c54bd73 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,227 +1,236 @@ -db = $db; - } + function __construct(Database $db) { + $this->db = $db; + } - public function ExecuteAction($action/*: array*/, $db_file = "") { - switch($action["type"]) { - case "dropTable": - $this->DropTableQuery($action["table_name"], true); - break; - case "createTable": - $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; - $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); - break; - case "addColumn": - $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); - break; - case "insert": - $this->db->insertQuery($action["table_name"], $action["values"]); - break; - case "alterReference": - $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); - break; - case "renameColumn": - $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); - break; - case "executeFile": - if ($this->db->isPostgres() && isset($action["pgsql"])) { - $file = $action["pgsql"]; - } else { - $file = $action["source"]; - } + public function ExecuteAction($action/*: array*/, $db_file = "") { + switch($action["type"]) { + case "dropTable": + $this->DropTableQuery($action["table_name"], true); + break; + case "createTable": + $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; + $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); + break; + case "addColumn": + $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); + break; + case "insert": + $this->db->insertQuery($action["table_name"], $action["values"]); + break; + case "alterReference": + $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); + break; + case "renameColumn": + $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); + break; + case "createView": + $this->recreateView($action["view"], $action["select"]); + break; + case "executeFile": + if ($this->db->isPostgres() && isset($action["pgsql"])) { + $file = $action["pgsql"]; + } else { + $file = $action["source"]; + } - $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); - foreach($stmtList as $stmt) { - $this->db->executeQuery($stmt); - } + $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); + foreach($stmtList as $stmt) { + $this->db->executeQuery($stmt); + } - break; - default: - throw new Exception("unknown action ". $action["type"] . PHP_EOL); - } - } + break; + default: + throw new Exception("unknown action ". $action["type"] . PHP_EOL); + } + } - public function DropTableQuery($table, $cascade=false) { - $statement = "DROP TABLE IF EXISTS ".$table; - if ($this->db->isPostgres()&&$cascade) { - $statement = $statement." CASCADE"; - } - $this->db->query($statement); - } + //Дропает и создаёт SQL VIEW + public function recreateView($viewName, $selectStatement) { + $this->db->query("DROP VIEW ".$viewName); + $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); + } - public function AlterReference($table,$column,$refTable,$refColumn) { - $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); - } + public function DropTableQuery($table, $cascade=false) { + $statement = "DROP TABLE IF EXISTS ".$table; + if ($this->db->isPostgres()&&$cascade) { + $statement = $statement." CASCADE"; + } + $this->db->query($statement); + } - //Извлечение информации о полях таблицы - public function TableInfo($table) { - $pg = $this->db->isPostgres(); - if ($pg) { - throw new Exception("Not implemented for postgres"); - } else { - $results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");"); - if (empty($results)) { - return null; - } - $fields = []; - foreach ($results as $result) { - $fields[$result["name"]] = [ - "type"=> $result["type"], - "not_null"=> boolval($result["notnull"]), - "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null - ]; - } - return $fields; - } - } + public function AlterReference($table,$column,$refTable,$refColumn) { + $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); + } - public function RenameColumn($table, $old_name, $new_name) { - $pg = $this->db->isPostgres(); - if ($pg) { - $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); - } else { - $tmp_table = "tmp_" . $table; - $this->DropTableQuery($tmp_table); - $table_info = $this->TableInfo($table); + //Извлечение информации о полях таблицы + public function TableInfo($table) { + $pg = $this->db->isPostgres(); + if ($pg) { + throw new Exception("Not implemented for postgres"); + } else { + $results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");"); + if (empty($results)) { + return null; + } + $fields = []; + foreach ($results as $result) { + $fields[$result["name"]] = [ + "type"=> $result["type"], + "not_null"=> boolval($result["notnull"]), + "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null + ]; + } + return $fields; + } + } - if (isset($table_info[$new_name])) { - return; - } + public function RenameColumn($table, $old_name, $new_name) { + $pg = $this->db->isPostgres(); + if ($pg) { + $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); + } else { + $tmp_table = "tmp_" . $table; + $this->DropTableQuery($tmp_table); + $table_info = $this->TableInfo($table); - $data/*: array*/ = $this->DumpTable($table); + if (isset($table_info[$new_name])) { + return; + } - $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); - $table_info[$new_name] = $table_info[$old_name]; - unset($table_info[$old_name]); - $this->CreateTableQuery($table,$table_info,null); + $data/*: array*/ = $this->DumpTable($table); - foreach ($data as $row) { - $values = $row['values']; - $values[$new_name] = $values[$old_name]; - unset($values[$old_name]); - $this->db->insertQuery($table, $values); - } - $this->DropTableQuery($tmp_table); - } - } + $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); + $table_info[$new_name] = $table_info[$old_name]; + unset($table_info[$old_name]); + $this->CreateTableQuery($table,$table_info,null); - //Обновление ключа serial после ручной вставки - public function UpdateSerial($table,$column) { - $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); - } + foreach ($data as $row) { + $values = $row['values']; + $values[$new_name] = $values[$old_name]; + unset($values[$old_name]); + $this->db->insertQuery($table, $values); + } + $this->DropTableQuery($tmp_table); + } + } - public function Column_Definition($name,$data,$pg){ - $constraint = isset($data['constraint'])?" ".$data['constraint']:""; - $references = ""; - if (isset($data['references'])) { - $references = " REFERENCES ".$data['references']; - } - if (isset($data["not_null"]) && $data["not_null"]) - $constraint .=" NOT NULL"; - $type = $data['type']; - if (!$pg) { - if (strtolower($type)=="serial") - $type = "integer"; - //if (strtolower($type)=="boolean") - // $type = "integer"; - } - return $name." ".$type.$references.$constraint; - } + //Обновление ключа serial после ручной вставки + public function UpdateSerial($table,$column) { + $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); + } - public function AddColumn($table_name,$column_name,$field){ - $pg = $this->db->isPostgres(); - $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->Column_Definition($column_name, $field, $pg); - $this->db->query($q); - } + public function Column_Definition($name,$data,$pg){ + $constraint = isset($data['constraint'])?" ".$data['constraint']:""; + $references = ""; + if (isset($data['references'])) { + $references = " REFERENCES ".$data['references']; + } + if (isset($data["not_null"]) && $data["not_null"]) + $constraint .=" NOT NULL"; + $type = $data['type']; + if (!$pg) { + if (strtolower($type)=="serial") + $type = "integer"; + //if (strtolower($type)=="boolean") + // $type = "integer"; + } + return $name." ".$type.$references.$constraint; + } - function getConstraintDef($c/*: array*/) { - if ($c['type'] == 'unique') { - return "UNIQUE(" . implode(", ", $c['fields']) . ")"; - } - return ""; + public function AddColumn($table_name,$column_name,$field){ + $pg = $this->db->isPostgres(); + $q = "ALTER TABLE ".$table_name." ADD COLUMN ". + $this->Column_Definition($column_name, $field, $pg); + $this->db->query($q); + } + + function getConstraintDef($c/*: array*/) { + if ($c['type'] == 'unique') { + return "UNIQUE(" . implode(", ", $c['fields']) . ")"; + } + return ""; + } + + //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + public function CreateTableQuery($table, $fields, $constraints) { + $pg = $this->db->isPostgres(); + if ($constraints) { + if (is_array($constraints)) { + $constraints = $this->getConstraintDef($constraints); + } + $constraints = ", " . $constraints; } - //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) - public function CreateTableQuery($table, $fields, $constraints) { - $pg = $this->db->isPostgres(); - if ($constraints) { - if (is_array($constraints)) { - $constraints = $this->getConstraintDef($constraints); + $statement = "CREATE TABLE $table (" . implode(",", + array_map(function($name,$data) use ($pg) { + return $this->Column_Definition($name,$data,$pg); + }, array_keys($fields), array_values($fields)) + ) . " " . $constraints . ")"; + $this->db->query($statement); + } + + public function DumpTable($table_name) { + $pg = $this->db->isPostgres(); + + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + + if (!$pg) { + $table_fields = $this->TableInfo($table_name); + foreach ($table_fields as $name => $value) { + $type = strtolower($value['type']); + if ($type == "boolean") { + foreach ($data as &$row) { + $row/*: array*/ = $row; + if (isset($row[$name])) { + $row[$name] = boolval($row[$name]); } - $constraints = ", " . $constraints; + } } + } + } + foreach ($data as $r) { + $result[] = array( + "type" => "insert", + "table_name" => $table_name, + "values" => $r + ); + } + return $result; + } - $statement = "CREATE TABLE $table (" . implode(",", - array_map(function($name,$data) use ($pg) { - return $this->Column_Definition($name,$data,$pg); - }, array_keys($fields), array_values($fields)) - ) . " " . $constraints . ")"; - $this->db->query($statement); - } + public function GetAllTableNames() { + $result = []; + if ($this->db->isPostgres()) { + $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; + } else { + $query = "SELECT * FROM sqlite_master WHERE type='table'"; + } + $tables = $this->db->fetchAllArray($query); + foreach ($tables as $table) { + $result[] = $table['name']; + } + return $result; + } - public function DumpTable($table_name) { - $pg = $this->db->isPostgres(); - - $result/*: array*/ = array(); - $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); - - if (!$pg) { - $table_fields = $this->TableInfo($table_name); - foreach ($table_fields as $name => $value) { - $type = strtolower($value['type']); - if ($type == "boolean") { - foreach ($data as &$row) { - $row/*: array*/ = $row; - if (isset($row[$name])) { - $row[$name] = boolval($row[$name]); - } - } - } - } - } - foreach ($data as $r) { - $result[] = array( - "type" => "insert", - "table_name" => $table_name, - "values" => $r - ); - } - return $result; - } - - public function GetAllTableNames() { - $result = []; - if ($this->db->isPostgres()) { - $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; - } else { - $query = "SELECT * FROM sqlite_master WHERE type='table'"; - } - $tables = $this->db->fetchAllArray($query); - foreach ($tables as $table) { - $result[] = $table['name']; - } - return $result; - } - - public function DumpInserts() { - $table_names = $this->GetAllTableNames(); - $result = array(); - foreach ($table_names as $table_name) { - $result = array_merge($result, $this->DumpTable($table_name)); - } - return $result; - } -} \ No newline at end of file + public function DumpInserts() { + $table_names = $this->GetAllTableNames(); + $result = array(); + foreach ($table_names as $table_name) { + $result = array_merge($result, $this->DumpTable($table_name)); + } + return $result; + } +} From 29a18f5410e3fcb6a4495726a440c4699b1ea92e Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 13 Apr 2023 11:34:19 +0300 Subject: [PATCH 38/42] =?UTF-8?q?fix=20=D0=9F=D0=B0=D1=80=D0=B0=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D1=80=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=BE=D0=B2=20=D0=B8?= =?UTF-8?q?=D0=B7=20get?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Form/Form.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a7ce660..4e6f459 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -320,7 +320,7 @@ class Component } $params = new Collection(); - $params->import($arguments); + $params->import(array_merge($_GET, $arguments)); $component->parameter = $params; $component->template = $params->get('template', false); diff --git a/src/Form/Form.php b/src/Form/Form.php index 343f254..3bdd32e 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -96,7 +96,7 @@ class Form extends View { $el->hint = $init['hint']; } - $this->field [$init['name']] = $el; + $this->field[$init['name']] = $el; return $el; } From 2edd65d145d77846401ad05597a60c697d223d0c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 13 Apr 2023 11:38:49 +0300 Subject: [PATCH 39/42] fix format --- src/Controller/Action.php | 44 +-- src/Database/JsonInstall.php | 240 +++++++-------- src/Database/Manager.php | 455 +++++++++++++++-------------- src/Database/PDOStatement.php | 32 +- src/Database/StatementIterator.php | 24 +- 5 files changed, 407 insertions(+), 388 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 2066995..b73b685 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -23,7 +23,7 @@ class Action const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const ACTION_PREFIX = "action"; // Префикс для функций действий - // Параметры устанавливаются при создании контроллера + // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля public $front; @@ -37,12 +37,12 @@ class Action */ public $db; - // Фильтры + // Фильтры public $access = null; // Обьект хранит параметры доступа public $logger = null; // Обьект для ведения лога - private $factory = null; // Ссылка на обьект создания модели - private $helpers = array(); // Помошники для действий + private $factory = null; // Ссылка на обьект создания модели + private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки public $config/*: Registry*/; // Ссылка на настройки @@ -100,7 +100,7 @@ class Action /** * Создает представление - * @param string + * @param string * @param string $viewClass * @return Composite */ @@ -130,7 +130,7 @@ class Action $scriptPath = Path::join($webPath, 'assets'); $tpl->set('icons', $iconsPath); // Путь к файлам текущей темы - $tpl->set('assets', $stylePath); + $tpl->set('assets', $stylePath); $tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('template', $path); // Путь к файлам текущего шаблона @@ -162,7 +162,7 @@ class Action * Т.к действия являются методами класса то * 1. Можно переопределить действия * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение - * @param HttpRequest $request запроса + * @param HttpRequest $request запроса */ public function preProcess(HttpRequest $request) { @@ -172,12 +172,12 @@ class Action } $view = $this->forward($action, $request); if ($view instanceof View) { - $view->active_module = get_class($this); - $view->module_action = $action; - } - return $view; + $view->active_module = get_class($this); + $view->module_action = $action; + } + return $view; } - + public function execute(HttpRequest $request) { $result = $this->preProcess($request); @@ -298,14 +298,14 @@ class Action /** * Установка заголовка для отображения - */ + */ public function setTitle($title) { $this->view->setTitle($title); } /** - * Добавление widget к отображению + * Добавление widget к отображению */ public function addChild($section, $node) { @@ -318,9 +318,9 @@ class Action } /** - * Добавление дочернего отображения к текущему отображению + * Добавление дочернего отображения к текущему отображению */ - public function addView($section, $node) + public function addView($section, $node) { $this->childViews[$section] = $node; } @@ -329,11 +329,11 @@ class Action * Генерация содержания * Путаница c execute и render */ - public function render() + public function render() { $view = $this->view; - if ($view instanceof View) { - $this->view->assignValues($this->ctrlValues); + if ($view instanceof View) { + $this->view->assignValues($this->ctrlValues); $node/*: Composite*/ = null; foreach ($this->childNodes as $name => $node) { @@ -344,17 +344,17 @@ class Action foreach ($this->childViews as $name => $node) { $this->view->setView($name, $node); } - } + } return $this->view; } function getPageId(HttpRequest $request) { - $pageId = time(); + $pageId = time(); $request->session()->set('page', $pageId); return $pageId; } - function checkPageId(HttpRequest $request, $page) + function checkPageId(HttpRequest $request, $page) { if ($request->get('__forced__')) { return true; diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 6acb9b7..9fc0c2f 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -8,139 +8,139 @@ class JsonInstall { public $db_manager; public $serialColumns; - public function __construct(Manager $db_manager) { - $this->db_manager = $db_manager; - } + public function __construct(Manager $db_manager) { + $this->db_manager = $db_manager; + } - function install($dbinit_path, $dbfill_path = null) { - $dbinit_file = file_get_contents($dbinit_path); - if (is_string($dbinit_file)) { - $initActions = json_decode($dbinit_file, true); - if (!$initActions) { - echo "Invalid ".$dbinit_path; - return 0; - } - } else { - echo "No ".$dbinit_path; - return 0; - } + function install($dbinit_path, $dbfill_path = null) { + $dbinit_file = file_get_contents($dbinit_path); + if (is_string($dbinit_file)) { + $initActions = json_decode($dbinit_file, true); + if (!$initActions) { + echo "Invalid ".$dbinit_path; + return 0; + } + } else { + echo "No ".$dbinit_path; + return 0; + } - $this->initDataBase($initActions, $dbinit_path); - if ($dbfill_path) { - $this->fillDataBase($dbfill_path); - } - $this->makeConstraints($initActions); - } + $this->initDataBase($initActions, $dbinit_path); + if ($dbfill_path) { + $this->fillDataBase($dbfill_path); + } + $this->makeConstraints($initActions); + } - function missingTables($tables) { - $actual_tables = $this->db_manager->GetAllTableNames(); - $missingTables = []; - foreach ($tables as $table) { - if (!in_array($table, $actual_tables)) - $missingTables[] = $table; - } - return $missingTables; - } + function missingTables($tables) { + $actual_tables = $this->db_manager->GetAllTableNames(); + $missingTables = []; + foreach ($tables as $table) { + if (!in_array($table, $actual_tables)) + $missingTables[] = $table; + } + return $missingTables; + } - //Создать таблицы - function initDataBase($initActions/*: array*/, $dbinit_path) { - $pg = $this->db_manager->db->isPostgres(); - if (!$pg) { - $refs = []; - //В sqlite нет alter reference. Референсы надо создавать при создании таблицы. - foreach ($initActions as $action) { - if ($action["type"] == "alterReference") { - if (!isset($refs[$action["table"]])) - $refs[$action["table"]] = []; - $refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы - } - } - } + //Создать таблицы + function initDataBase($initActions/*: array*/, $dbinit_path) { + $pg = $this->db_manager->db->isPostgres(); + if (!$pg) { + $refs = []; + //В sqlite нет alter reference. Референсы надо создавать при создании таблицы. + foreach ($initActions as $action) { + if ($action["type"] == "alterReference") { + if (!isset($refs[$action["table"]])) + $refs[$action["table"]] = []; + $refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы + } + } + } - foreach ($initActions as $action) { - if (!$pg) { - if ($action["type"] == "createTable") { - $table_name = $action["table_name"]; - if (isset($refs[$table_name])) { - foreach ($refs[$table_name] as $value) { - $action['fields'][$value['column']]['references'] = - $value['refTable']."(".$value['refColumn'].")"; - } - } + foreach ($initActions as $action) { + if (!$pg) { + if ($action["type"] == "createTable") { + $table_name = $action["table_name"]; + if (isset($refs[$table_name])) { + foreach ($refs[$table_name] as $value) { + $action['fields'][$value['column']]['references'] = + $value['refTable']."(".$value['refColumn'].")"; + } + } - } - } - if ($action["type"] != "alterReference") { - $this->db_manager->ExecuteAction($action, $dbinit_path); - } - } + } + } + if ($action["type"] != "alterReference") { + $this->db_manager->ExecuteAction($action, $dbinit_path); + } + } - //Запомнить все колонки serial - $this->serialColumns = []; - if ($pg) { - foreach ($initActions as $action) { - if ($action["type"] == "createTable") { - foreach ($action["fields"] as $name => $field) { - if ($field["type"]=="serial") { - $this->serialColumns[] = [ + //Запомнить все колонки serial + $this->serialColumns = []; + if ($pg) { + foreach ($initActions as $action) { + if ($action["type"] == "createTable") { + foreach ($action["fields"] as $name => $field) { + if ($field["type"]=="serial") { + $this->serialColumns[] = [ "table"=>$action["table_name"], - "column"=>$name + "column"=>$name ]; - } - } - } - } - } - } + } + } + } + } + } + } - //Заполнить данными - function fillDataBase($dbfill_file_path) { - $dbfill_file = file_get_contents($dbfill_file_path); - if (is_string($dbfill_file)) { - $actions = json_decode($dbfill_file,true); - if ($actions) { - - //Проверка что упоминаемые в списке действий таблицы уже есть в базе - $affected_tables = []; - foreach ($actions as $action) { - if ($action["table_name"]) { - $affected_tables[$action["table_name"]] = 1; + //Заполнить данными + function fillDataBase($dbfill_file_path) { + $dbfill_file = file_get_contents($dbfill_file_path); + if (is_string($dbfill_file)) { + $actions = json_decode($dbfill_file,true); + if ($actions) { + + //Проверка что упоминаемые в списке действий таблицы уже есть в базе + $affected_tables = []; + foreach ($actions as $action) { + if ($action["table_name"]) { + $affected_tables[$action["table_name"]] = 1; } } - $missing = $this->missingTables(array_keys($affected_tables)); - if (!empty($missing)) { - echo "dbfill error. Missing tables: ".implode(" ", $missing); - return; - } - - //Выполнение действий - foreach ($actions as $action) { - $this->db_manager->ExecuteAction($action, $dbfill_file_path); - } - } else { - echo "Invalid dbfill.json"; - } - } else { - echo "No dbfill.json"; - } - } - - //Обновить ключи serial и создать ограничения - function makeConstraints($initActions) { - $pg = $this->db_manager->db->isPostgres(); - if ($pg) { - foreach ($this->serialColumns as $serialColumn) { - $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]); - } - - - foreach ($initActions as $action) { - if ($action["type"] == "alterReference") { - $this->db_manager->ExecuteAction($action); + $missing = $this->missingTables(array_keys($affected_tables)); + if (!empty($missing)) { + echo "dbfill error. Missing tables: ".implode(" ", $missing); + return; } - } - } - } + + //Выполнение действий + foreach ($actions as $action) { + $this->db_manager->ExecuteAction($action, $dbfill_file_path); + } + } else { + echo "Invalid dbfill.json"; + } + } else { + echo "No dbfill.json"; + } + } + + //Обновить ключи serial и создать ограничения + function makeConstraints($initActions) { + $pg = $this->db_manager->db->isPostgres(); + if ($pg) { + foreach ($this->serialColumns as $serialColumn) { + $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]); + } + + + foreach ($initActions as $action) { + if ($action["type"] == "alterReference") { + $this->db_manager->ExecuteAction($action); + } + } + } + } } \ No newline at end of file diff --git a/src/Database/Manager.php b/src/Database/Manager.php index c54bd73..669b570 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,236 +1,255 @@ db = $db; - } - - public function ExecuteAction($action/*: array*/, $db_file = "") { - switch($action["type"]) { - case "dropTable": - $this->DropTableQuery($action["table_name"], true); - break; - case "createTable": - $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; - $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); - break; - case "addColumn": - $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); - break; - case "insert": - $this->db->insertQuery($action["table_name"], $action["values"]); - break; - case "alterReference": - $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); - break; - case "renameColumn": - $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); - break; - case "createView": - $this->recreateView($action["view"], $action["select"]); - break; - case "executeFile": - if ($this->db->isPostgres() && isset($action["pgsql"])) { - $file = $action["pgsql"]; - } else { - $file = $action["source"]; - } - - $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); - foreach($stmtList as $stmt) { - $this->db->executeQuery($stmt); - } - - break; - default: - throw new Exception("unknown action ". $action["type"] . PHP_EOL); - } - } - - //Дропает и создаёт SQL VIEW - public function recreateView($viewName, $selectStatement) { - $this->db->query("DROP VIEW ".$viewName); - $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); - } - - public function DropTableQuery($table, $cascade=false) { - $statement = "DROP TABLE IF EXISTS ".$table; - if ($this->db->isPostgres()&&$cascade) { - $statement = $statement." CASCADE"; - } - $this->db->query($statement); - } - - public function AlterReference($table,$column,$refTable,$refColumn) { - $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); - } - - //Извлечение информации о полях таблицы - public function TableInfo($table) { - $pg = $this->db->isPostgres(); - if ($pg) { - throw new Exception("Not implemented for postgres"); - } else { - $results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");"); - if (empty($results)) { - return null; - } - $fields = []; - foreach ($results as $result) { - $fields[$result["name"]] = [ - "type"=> $result["type"], - "not_null"=> boolval($result["notnull"]), - "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null - ]; - } - return $fields; - } - } - - public function RenameColumn($table, $old_name, $new_name) { - $pg = $this->db->isPostgres(); - if ($pg) { - $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); - } else { - $tmp_table = "tmp_" . $table; - $this->DropTableQuery($tmp_table); - $table_info = $this->TableInfo($table); - - if (isset($table_info[$new_name])) { - return; - } - - $data/*: array*/ = $this->DumpTable($table); - - $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); - $table_info[$new_name] = $table_info[$old_name]; - unset($table_info[$old_name]); - $this->CreateTableQuery($table,$table_info,null); - - foreach ($data as $row) { - $values = $row['values']; - $values[$new_name] = $values[$old_name]; - unset($values[$old_name]); - $this->db->insertQuery($table, $values); - } - $this->DropTableQuery($tmp_table); - } - } - - //Обновление ключа serial после ручной вставки - public function UpdateSerial($table,$column) { - $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); - } - - public function Column_Definition($name,$data,$pg){ - $constraint = isset($data['constraint'])?" ".$data['constraint']:""; - $references = ""; - if (isset($data['references'])) { - $references = " REFERENCES ".$data['references']; - } - if (isset($data["not_null"]) && $data["not_null"]) - $constraint .=" NOT NULL"; - $type = $data['type']; - if (!$pg) { - if (strtolower($type)=="serial") - $type = "integer"; - //if (strtolower($type)=="boolean") - // $type = "integer"; - } - return $name." ".$type.$references.$constraint; - } - - public function AddColumn($table_name,$column_name,$field){ - $pg = $this->db->isPostgres(); - $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->Column_Definition($column_name, $field, $pg); - $this->db->query($q); - } - - function getConstraintDef($c/*: array*/) { - if ($c['type'] == 'unique') { - return "UNIQUE(" . implode(", ", $c['fields']) . ")"; - } - return ""; - } - - //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) - public function CreateTableQuery($table, $fields, $constraints) { - $pg = $this->db->isPostgres(); - if ($constraints) { - if (is_array($constraints)) { - $constraints = $this->getConstraintDef($constraints); - } - $constraints = ", " . $constraints; + public function __construct(Database $db) + { + $this->db = $db; } - $statement = "CREATE TABLE $table (" . implode(",", - array_map(function($name,$data) use ($pg) { - return $this->Column_Definition($name,$data,$pg); - }, array_keys($fields), array_values($fields)) - ) . " " . $constraints . ")"; - $this->db->query($statement); - } + public function ExecuteAction($action/*: array*/, $db_file = "") + { + switch($action["type"]) { + case "dropTable": + $this->DropTableQuery($action["table_name"], true); + break; + case "createTable": + $constraints = isset($action["constraints"]) ? $action["constraints"] : null; + $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); + break; + case "addColumn": + $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); + break; + case "insert": + $this->db->insertQuery($action["table_name"], $action["values"]); + break; + case "alterReference": + $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); + break; + case "renameColumn": + $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); + break; + case "createView": + $this->recreateView($action["view"], $action["select"]); + break; + case "executeFile": + if ($this->db->isPostgres() && isset($action["pgsql"])) { + $file = $action["pgsql"]; + } else { + $file = $action["source"]; + } - public function DumpTable($table_name) { - $pg = $this->db->isPostgres(); + $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); + foreach ($stmtList as $stmt) { + $this->db->executeQuery($stmt); + } - $result/*: array*/ = array(); - $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); - - if (!$pg) { - $table_fields = $this->TableInfo($table_name); - foreach ($table_fields as $name => $value) { - $type = strtolower($value['type']); - if ($type == "boolean") { - foreach ($data as &$row) { - $row/*: array*/ = $row; - if (isset($row[$name])) { - $row[$name] = boolval($row[$name]); - } - } + break; + default: + throw new Exception("unknown action ". $action["type"] . PHP_EOL); } - } } - foreach ($data as $r) { - $result[] = array( - "type" => "insert", - "table_name" => $table_name, - "values" => $r - ); - } - return $result; - } - public function GetAllTableNames() { - $result = []; - if ($this->db->isPostgres()) { - $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; - } else { - $query = "SELECT * FROM sqlite_master WHERE type='table'"; + //Дропает и создаёт SQL VIEW + public function recreateView($viewName, $selectStatement) + { + $this->db->query("DROP VIEW ".$viewName); + $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); } - $tables = $this->db->fetchAllArray($query); - foreach ($tables as $table) { - $result[] = $table['name']; - } - return $result; - } - public function DumpInserts() { - $table_names = $this->GetAllTableNames(); - $result = array(); - foreach ($table_names as $table_name) { - $result = array_merge($result, $this->DumpTable($table_name)); + public function DropTableQuery($table, $cascade=false) + { + $statement = "DROP TABLE IF EXISTS ".$table; + if ($this->db->isPostgres()&&$cascade) { + $statement = $statement." CASCADE"; + } + $this->db->query($statement); + } + + public function AlterReference($table, $column, $refTable, $refColumn) + { + $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); + } + + //Извлечение информации о полях таблицы + public function TableInfo($table) + { + $pg = $this->db->isPostgres(); + if ($pg) { + throw new Exception("Not implemented for postgres"); + } else { + $results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");"); + if (empty($results)) { + return null; + } + $fields = []; + foreach ($results as $result) { + $fields[$result["name"]] = [ + "type"=> $result["type"], + "not_null"=> boolval($result["notnull"]), + "constraint"=> ((bool) $result["pk"]) ? "PRIMARY KEY" : null + ]; + } + return $fields; + } + } + + public function RenameColumn($table, $old_name, $new_name) + { + $pg = $this->db->isPostgres(); + if ($pg) { + $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); + } else { + $tmp_table = "tmp_" . $table; + $this->DropTableQuery($tmp_table); + $table_info = $this->TableInfo($table); + + if (isset($table_info[$new_name])) { + return; + } + + $data/*: array*/ = $this->DumpTable($table); + + $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); + $table_info[$new_name] = $table_info[$old_name]; + unset($table_info[$old_name]); + $this->CreateTableQuery($table, $table_info, null); + + foreach ($data as $row) { + $values = $row['values']; + $values[$new_name] = $values[$old_name]; + unset($values[$old_name]); + $this->db->insertQuery($table, $values); + } + $this->DropTableQuery($tmp_table); + } + } + + //Обновление ключа serial после ручной вставки + public function UpdateSerial($table, $column) + { + $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); + } + + public function Column_Definition($name, $data, $pg) + { + $constraint = isset($data['constraint']) ? " ".$data['constraint'] : ""; + $references = ""; + if (isset($data['references'])) { + $references = " REFERENCES ".$data['references']; + } + if (isset($data["not_null"]) && $data["not_null"]) { + $constraint .=" NOT NULL"; + } + $type = $data['type']; + if (!$pg) { + if (strtolower($type)=="serial") { + $type = "integer"; + } + //if (strtolower($type)=="boolean") + // $type = "integer"; + } + return $name." ".$type.$references.$constraint; + } + + public function AddColumn($table_name, $column_name, $field) + { + $pg = $this->db->isPostgres(); + $q = "ALTER TABLE ".$table_name." ADD COLUMN ". + $this->Column_Definition($column_name, $field, $pg); + $this->db->query($q); + } + + public function getConstraintDef($c/*: array*/) + { + if ($c['type'] == 'unique') { + return "UNIQUE(" . implode(", ", $c['fields']) . ")"; + } + return ""; + } + + //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + public function CreateTableQuery($table, $fields, $constraints) + { + $pg = $this->db->isPostgres(); + if ($constraints) { + if (is_array($constraints)) { + $constraints = $this->getConstraintDef($constraints); + } + $constraints = ", " . $constraints; + } + + $statement = "CREATE TABLE $table (" . implode( + ",", + array_map(function ($name, $data) use ($pg) { + return $this->Column_Definition($name, $data, $pg); + }, array_keys($fields), array_values($fields)) + ) . " " . $constraints . ")"; + $this->db->query($statement); + } + + public function DumpTable($table_name) + { + $pg = $this->db->isPostgres(); + + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + + if (!$pg) { + $table_fields = $this->TableInfo($table_name); + foreach ($table_fields as $name => $value) { + $type = strtolower($value['type']); + if ($type == "boolean") { + foreach ($data as &$row) { + $row/*: array*/ = $row; + if (isset($row[$name])) { + $row[$name] = boolval($row[$name]); + } + } + } + } + } + foreach ($data as $r) { + $result[] = array( + "type" => "insert", + "table_name" => $table_name, + "values" => $r + ); + } + return $result; + } + + public function GetAllTableNames() + { + $result = []; + if ($this->db->isPostgres()) { + $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; + } else { + $query = "SELECT * FROM sqlite_master WHERE type='table'"; + } + $tables = $this->db->fetchAllArray($query); + foreach ($tables as $table) { + $result[] = $table['name']; + } + return $result; + } + + public function DumpInserts() + { + $table_names = $this->GetAllTableNames(); + $result = array(); + foreach ($table_names as $table_name) { + $result = array_merge($result, $this->DumpTable($table_name)); + } + return $result; } - return $result; - } } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index af8c19f..1ae56df 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -10,33 +10,33 @@ use TheSeer\Tokenizer\Exception; class PDOStatement extends \PDOStatement implements \IteratorAggregate { protected $cursorPos = 0; - public $cache = array(); + public $cache = array(); public $fields; function getIterator(): \Iterator { return new StatementIterator($this); } - protected function __construct() { + protected function __construct() { } - function rewind() { + function rewind() { $this->cursorPos = 0; } - public function seek($rownum) { - if ($rownum < 0) { - return false; - } - - // PostgreSQL rows start w/ 0, but this works, because we are - // looking to move the position _before_ the next desired position - $this->cursorPos = $rownum; - return true; - } + public function seek($rownum) { + if ($rownum < 0) { + return false; + } + + // PostgreSQL rows start w/ 0, but this works, because we are + // looking to move the position _before_ the next desired position + $this->cursorPos = $rownum; + return true; + } function valid() { - return true; + return true; } @@ -49,7 +49,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate if ($this->getRecordCount() > $this->cursorPos) { if (!isset($this->cache[$this->cursorPos])) { $this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC); - } + } $this->fields = $this->cache[$this->cursorPos]; $this->cursorPos++; @@ -102,7 +102,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate function getRecordCount() { return count($this->cache); } - + function execute($args = null) { $result = parent::execute($args); return $result; diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index aad0c90..eebd752 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -10,40 +10,40 @@ class StatementIterator implements \Iterator private $pos = 0; private $fetchmode; private $row_count; - + public function __construct($rs/*: PDOStatement*/) { $this->result = $rs; - $this->row_count = $rs->getRecordCount(); + $this->row_count = $rs->getRecordCount(); } - - function rewind() { + + function rewind() { $this->pos = 0; } - + function valid() { - return ($this->pos < $this->row_count); + return ($this->pos < $this->row_count); } - + function key() { return $this->pos; } - + function current() { if (!isset($this->result->cache[$this->pos])) { $this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC); - } + } return $this->result->cache[$this->pos]; } - + function next() { $this->pos++; } function seek($index) { - $this->pos = $index; + $this->pos = $index; } function count() { - return $this->row_count; + return $this->row_count; } } From 9d730c2961eb71621c740de1954b2c3408488421 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Jun 2023 11:34:51 +0300 Subject: [PATCH 40/42] =?UTF-8?q?fix:=20=D0=A1=D0=BB=D0=B5=D1=88=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index e17205b..a6591bd 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -202,7 +202,7 @@ class Login extends Filter $module = $request->get('module'); $action = $request->get('action'); - $moduleDir = explode('_',$module)[0]; + $moduleDir = explode('\\',$module)[0]; $file = Path::join($this->config->get('system', 'path'), 'modules', $moduleDir, 'filters', 'white.json'); if (file_exists($file)) { $whiteList = json_decode(file_get_contents($file), true); From 2b021ffb61fb15ba374714573abda7071fdf4ca2 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Jun 2023 17:58:23 +0300 Subject: [PATCH 41/42] =?UTF-8?q?feat:=20=D0=92=D0=BE=D0=B7=D0=BC=D0=BE?= =?UTF-8?q?=D0=B6=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D1=8F=D1=82=D1=8C=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D0=B0=20=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Validator/Validator.php | 49 ++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 88fd870..c8303ad 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -3,7 +3,7 @@ /// /** - * Проверка коллекции + * Проверка коллекции */ namespace ctiso\Validator; use Exception, @@ -14,35 +14,38 @@ class Validator { protected $chain = array(); // Массив правил protected $errorMsg = array(); // Массив ошибок + protected $type = array( + 'date' => 'ctiso\\Validator\\Rule\\Date', + 'email' => 'ctiso\\Validator\\Rule\\Email', + 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', + 'match' => 'ctiso\\Validator\\Rule\\MatchRule', + 'time' => 'ctiso\\Validator\\Rule\\Time', + 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', + 'require' => 'ctiso\\Validator\\Rule\\Notnull', + 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', + 'unique' => 'ctiso\\Validator\\Rule\\Unique', + 'filename' => 'ctiso\\Validator\\Rule\\FileName', + 'count' => 'ctiso\\Validator\\Rule\\Count', + 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', + 'code' => 'ctiso\\Validator\\Rule\\Code' + ); function __construct($rules = array()) { $this->addRuleList($rules); } + function addRuleType($name, $className) { + $this->type[$name] = $className; + } + /** * Добавление списка правил в специальном формате * array(array('name' => fieldname, 'validate' => ruletext), ...) - * fieldname - Имя переменой для проверки + * fieldname - Имя переменой для проверки * ruletext - Описание правила см. формат правила ниже */ public function addRuleList(array $input) { - $type = array( - 'date' => 'ctiso\\Validator\\Rule\\Date', - 'email' => 'ctiso\\Validator\\Rule\\Email', - 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', - 'match' => 'ctiso\\Validator\\Rule\\MatchRule', - 'time' => 'ctiso\\Validator\\Rule\\Time', - 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', - 'require' => 'ctiso\\Validator\\Rule\\Notnull', - 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', - 'unique' => 'ctiso\\Validator\\Rule\\Unique', - 'filename' => 'ctiso\\Validator\\Rule\\FileName', - 'count' => 'ctiso\\Validator\\Rule\\Count', - 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', - 'code' => 'ctiso\\Validator\\Rule\\Code' - ); - // Разбор правила проверки // Формат правила 'rule1|rule2,param1=value1|rule3,param1=value1,param2=value2' foreach ($input as $value) { @@ -55,8 +58,8 @@ class Validator $rule_param = explode(",", $rule); $name = array_shift($rule_param); - if (isset($type[$name])) { - $constructor = $type[$name]; + if (isset($this->type[$name])) { + $constructor = $this->type[$name]; $ruleObj = new $constructor($value['name'], false); // Нужны шаблонные сообщения для правил if (isset($value['context'])) { $ruleObj->setContext($value['context']); @@ -81,7 +84,7 @@ class Validator $this->chain[] = $rule; } } - + public function skip($rule/*: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract { if ($rule->skipEmpty()) { @@ -90,10 +93,10 @@ class Validator $value = trim($data); return $value == ''; } - } + } return false; } - + public function validate(Collection $container, $rule = null, $status = null) { $fields = array(); From bfaaf77b3e55257f27e7837b47a052db8fb119cf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 3 Jul 2023 16:11:57 +0300 Subject: [PATCH 42/42] =?UTF-8?q?fix:=20=D0=9F=D1=83=D1=82=D1=8C=20=D0=BA?= =?UTF-8?q?=20action=20=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Front.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Controller/Front.php b/src/Controller/Front.php index d5e6d12..ed9148a 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -78,10 +78,11 @@ class Front extends Action $module->front = $this; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); - $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); + $filename = Path::join($modPath, 'filters', 'logger.json'); + $logger->before = $this->loadSettings($filename); // Управление доступом $module->access = new ActionAccess($logger, $this->user); - $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); + $module->access->access = $this->loadSettings(Path::join($modPath, 'filters', 'access.json')); $module->setUp();