Обьединение с namespace

This commit is contained in:
CORP\phedor 2018-03-28 11:15:16 +03:00
commit 8b38b2a3cc
90 changed files with 601 additions and 222 deletions

View file

@ -8,8 +8,8 @@
} }
], ],
"autoload": { "autoload": {
"psr-0": { "psr-4": {
"": "src/" "ctiso\\": "src/"
} }
} }
} }

View file

@ -1,5 +1,8 @@
<?php <?php
namespace ctiso;
/** /**
* Интерфейс к массиву и обьекту как к коллекции * Интерфейс к массиву и обьекту как к коллекции
*/ */

View file

@ -1,5 +1,8 @@
<?php <?php
namespace ctiso;
class Arr { class Arr {
static function get($data, $key, $default = null) { static function get($data, $key, $default = null) {
return isset($data[$key]) ? $data[$key] : $default; return isset($data[$key]) ? $data[$key] : $default;

View file

@ -1,9 +1,12 @@
<?php <?php
namespace ctiso;
/** /**
* Коллекция * Коллекция
* *
*/ */
class Collection implements ArrayAccess class Collection implements \ArrayAccess
{ {
/** /**
* Holds collective request data * Holds collective request data
@ -58,17 +61,17 @@ class Collection implements ArrayAccess
public function getInt($key, $default = 0) public function getInt($key, $default = 0)
{ {
return intval($this->get($key, $default)); return (int)$this->get($key, $default);
} }
public function getString($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) public function getNat($key, $default = 1)
{ {
$result = intval($this->get($key, $default)); $result = (int)$this->get($key, $default);
return (($result > 0) ? $result : $default); return (($result > 0) ? $result : $default);
} }

View file

@ -1,6 +1,9 @@
<?php <?php
class Connection_HttpRequest namespace ctiso\Connection;
use ctiso\File;
class HttpRequest
{ {
const POST = "POST"; const POST = "POST";
const GET = "GET"; const GET = "GET";

View file

@ -3,7 +3,9 @@
/** /**
* Обрабатывает HTTP ответ * Обрабатывает HTTP ответ
*/ */
class Connection_HttpResponse namespace ctiso\Connection;
class HttpResponse
{ {
private $offset; private $offset;
private $param = array (); private $param = array ();
@ -36,12 +38,12 @@ class Connection_HttpResponse
if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') {
//$this->data = substr($this->response, $this->offset); //$this->data = substr($this->response, $this->offset);
$line = hexdec($this->getLine()); $index = hexdec($this->getLine());
$chunk = array(); $chunk = array();
while ($line > 0) { while ($index > 0) {
$chunk [] = substr($this->response, $this->offset, $line); $chunk [] = substr($this->response, $this->offset, $index);
$this->offset += $line; $this->offset += $index;
$line = hexdec($this->getLine()); $index = hexdec($this->getLine());
} }
$this->data = implode("", $chunk); $this->data = implode("", $chunk);

View file

@ -1,5 +1,16 @@
<?php <?php
namespace ctiso\Controller;
use ctiso\Shortcut,
Exception,
ctiso\Path,
ctiso\View\View,
ctiso\Model\Factory,
ctiso\HttpRequest,
ctiso\Functions,
ctiso\Settings,
ctiso\Controller\State;
function forceUrl($name) function forceUrl($name)
{ {
if (is_callable($name)) { if (is_callable($name)) {
@ -11,7 +22,7 @@ function forceUrl($name)
/** /**
* Контроллер страниц * Контроллер страниц
*/ */
class Controller_Action class Action
{ {
const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов
@ -78,7 +89,7 @@ class Controller_Action
return Path::join(CMS_PATH, "modules", $name); return Path::join(CMS_PATH, "modules", $name);
} }
public function addSuggest(View_View $view, $name) public function addSuggest(View $view, $name)
{ {
$suggest = array(); $suggest = array();
$file = Path::join($this->viewPath, 'help', $name . '.suggest'); $file = Path::join($this->viewPath, 'help', $name . '.suggest');
@ -141,7 +152,7 @@ class Controller_Action
public function getModel($name) public function getModel($name)
{ {
if (!$this->factory) { 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); return $this->factory->getModel($name);
} }
@ -364,7 +375,7 @@ class Controller_Action
function _getActionPath() function _getActionPath()
{ {
return new Controller_State('index'); return new State('index');
} }
// Тоже убрать в метод Controller_Model // Тоже убрать в метод Controller_Model

View file

@ -1,7 +1,20 @@
<?php <?php
namespace ctiso\Controller;
use ctiso\HttpRequest,
ctiso\Arr,
ctiso\Path,
PHPTAL,
PHPTAL_PreFilter_Normalize,
ctiso\File,
ctiso\Form\Form,
ctiso\Form\OptionFactory,
ctiso\Database,
ctiso\Collection,
ctiso\Controller\Site;
function replaceContent($match) { function replaceContent($match) {
$result = phptal_component(htmlspecialchars_decode($match[3])); $result = Tales\Component::phptal_component(htmlspecialchars_decode($match[3]));
return $result; return $result;
} }
@ -38,10 +51,27 @@ 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;
}
}
/** /**
* Класс компонента * Класс компонента
*/ */
class Controller_Component class Component
{ {
public $viewPath = array(); public $viewPath = array();
public $webPath = array(); public $webPath = array();
@ -56,6 +86,7 @@ class Controller_Component
public /*.Settings.*/$registry; public /*.Settings.*/$registry;
public /*.Database.*/$db; public /*.Database.*/$db;
public /*.Collection.*/$parameter; public /*.Collection.*/$parameter;
public $output = 'html';
public $module; public $module;
public $item_module; public $item_module;
@ -86,6 +117,10 @@ class Controller_Component
public function getView($name) public function getView($name)
{ {
if ($this->output == 'json') {
return new FakeTemplate($name);
}
// //
/*.Settings.*/$registry = $this->registry; /*.Settings.*/$registry = $this->registry;
$template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template'));
@ -164,8 +199,18 @@ class Controller_Component
return $result; 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() { function getInfo() {
$filename = Path::join($this->viewPath[0], 'install.json'); $filename = $this->findFile($this->viewPath, 'install.json');
if (file_exists($filename)) { if (file_exists($filename)) {
$settings = json_decode(File::getContents($filename), true); $settings = json_decode(File::getContents($filename), true);
return $settings; return $settings;
@ -178,8 +223,8 @@ class Controller_Component
*/ */
public function setParameters(/*.View_Composite.*/$view) public function setParameters(/*.View_Composite.*/$view)
{ {
$form = new Form_Form(); $form = new Form();
$options = new Form_OptionFactory($this->db, $this->registry); $options = new OptionFactory($this->db, $this->registry);
$settings = $this->getInfo(); $settings = $this->getInfo();
$form->addFieldList($settings['parameter'], $options); $form->addFieldList($settings['parameter'], $options);
@ -262,14 +307,14 @@ class Controller_Component
} }
$params = new Collection(); $params = new Collection();
$params->import(array_merge($_GET, $arguments)); $params->import($arguments);
$component->parameter = $params; $component->parameter = $params;
$component->template = $params->get('template', false); $component->template = $params->get('template', false);
$editor = $component->getEditUrl(); $editor = $component->getEditUrl();
if ($editor) { if ($editor) {
if(class_exists("Controller_Site")){ //Если мы в CMS2 if(class_exists("Controller_Site")) { //Если мы в CMS2
$instance = Controller_Site::getInstance(); $instance = Site::getInstance();
$instance->componentsConfig[] = $editor; $instance->componentsConfig[] = $editor;
} else { } else {
global $componentsConfig; global $componentsConfig;
@ -324,10 +369,9 @@ class Controller_Component
*/ */
function addRequireJsPath($name, $path, $shim = null) { function addRequireJsPath($name, $path, $shim = null) {
Controller_Site::addRequireJsPath($name, $path, $shim); Site::addRequireJsPath($name, $path, $shim);
} }
function actionIndex(/*.ComponentRequest.*/ $request) { function actionIndex(/*.ComponentRequest.*/ $request) {
} }
} }

View file

@ -4,7 +4,18 @@
* Первичный контроллер контроллер страниц * Первичный контроллер контроллер страниц
* @package system.controller * @package system.controller
*/ */
class Controller_Front extends Controller_Action namespace ctiso\Controller;
use ctiso\Controller\Action,
ctiso\Settings,
ctiso\Database,
ctiso\Collection,
ctiso\Filter\ActionAccess,
ctiso\Filter\ActionLogger,
ctiso\Path;
ctiso\UserMessageException,
ctiso\HttpRequest;
class Front extends Action
{ {
/** @var Shortcut */ /** @var Shortcut */
@ -18,16 +29,14 @@ class Controller_Front extends Controller_Action
* @param Settings $_registry * @param Settings $_registry
* @param Shortcut $_shortcut * @param Shortcut $_shortcut
*/ */
public function __construct($db, $settings, $default) // $db, $installer, $shortcut public function __construct($db, $settings, $default) {
{
parent::__construct(); parent::__construct();
$this->settings = $settings; $this->settings = $settings;
$this->db = $db; $this->db = $db;
$this->default = $default; $this->default = $default;
} }
public function isLoaded($name) public function isLoaded($name) {
{
return isset($this->modules[$name]); return isset($this->modules[$name]);
} }
@ -37,7 +46,7 @@ class Controller_Front extends Controller_Action
* @param request $request Имя модуля * @param request $request Имя модуля
* @return string * @return string
*/ */
public function loadModule($name, Collection $request, $controller = false) public function loadModule($name, Collection $request, $controller = null)
{ {
if ($this->isLoaded($name)) { if ($this->isLoaded($name)) {
$module = $this->modules[$name]; $module = $this->modules[$name];
@ -47,7 +56,9 @@ class Controller_Front extends Controller_Action
$basePath = $this->settings['system']->readKey(['path', 'modules']); $basePath = $this->settings['system']->readKey(['path', 'modules']);
$moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name); $moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name);
$module = $this->loadClass($moduleFile, null, 'Module_'); $ucname = ucfirst($name);
$moduleClass = "Module\\$ucname\\$ucname";
$module = new $moduleClass();
if ($module) { if ($module) {
// Инициализация модуля // Инициализация модуля
$modPath = Path::join($basePath, $name); $modPath = Path::join($basePath, $name);
@ -57,10 +68,10 @@ class Controller_Front extends Controller_Action
$module->settings = $this->settings; $module->settings = $this->settings;
$module->db = $this->db; $module->db = $this->db;
// Ведение лога // Ведение лога
$logger = new Filter_ActionLogger($module); $logger = new ActionLogger($module);
$logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php'));
// Управление доступом // Управление доступом
$module->access = new Filter_ActionAccess($logger); $module->access = new ActionAccess($logger);
$module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php'));
$module->setUp(); $module->setUp();
@ -72,13 +83,14 @@ class Controller_Front extends Controller_Action
return null; // throw new FileNotFoundException(); return null; // throw new FileNotFoundException();
} }
public function execute(HTTPRequest $request)
public function execute(HttpRequest $request)
{ {
$name = explode("_", $request->get('module', $this->default)); $name = explode("\\", $request->get('module', $this->default));
if (count($name) >= 2) { if (count($name) >= 2) {
$controller = $name[1]; $controller = $name[1];
} else { } else {
$controller = false; $controller = null;
} }
try { try {
return $this->loadModule($name[0], $request, $controller); return $this->loadModule($name[0], $request, $controller);

View file

@ -1,6 +1,11 @@
<?php <?php
class Controller_Installer namespace ctiso\Controller;
use ctiso\Settings,
ctiso\Path,
ctiso\Database\JsonInstall;
class Installer
{ {
protected $db_manager; protected $db_manager;
protected $installPath; protected $installPath;
@ -44,7 +49,7 @@ class Controller_Installer
function installSQL(array $sql, $version_new, $version_old, $name) function installSQL(array $sql, $version_new, $version_old, $name)
{ {
$result = []; $result = [];
$json_installer = new Database_JsonInstall($this->db_manager); $json_installer = new JsonInstall($this->db_manager);
foreach ($sql as $version => $install) { foreach ($sql as $version => $install) {
if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) { if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) {
$file = Path::join(call_user_func($this->installPath, $name), "sql", $install); $file = Path::join(call_user_func($this->installPath, $name), "sql", $install);
@ -58,7 +63,7 @@ class Controller_Installer
function uninstall($name){ function uninstall($name){
$uninstall = $this->getUninstallFile($name); $uninstall = $this->getUninstallFile($name);
if (file_exists($uninstall)) { if (file_exists($uninstall)) {
$json_installer = new Database_JsonInstall($this->db_manager); $json_installer = new JsonInstall($this->db_manager);
$json_installer->install($uninstall,null); $json_installer->install($uninstall,null);
} }
$this->_registry->removeKey($name); $this->_registry->removeKey($name);
@ -108,7 +113,7 @@ class Controller_Installer
} }
function install($dbinit_path, $dbfill_path = null) { 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); $json_installer->install($dbinit_path, $dbfill_path);
} }
} }

View file

@ -1,13 +1,19 @@
<?php <?php
class Controller_Request { namespace ctiso\Controller;
function __construct($request, $id) {
class Request {
public $r;
public $id;
function __construct(/*.HttpRequest.*/$request, $id) {
$this->r = $request; $this->r = $request;
$this->id = $id; $this->id = $id;
} }
function get($name) { function get($name, $def) {
$v = $this->r->get($name); $v = $this->r->get($name);
$id = $this->id;
if ($id && is_array($v)) { if ($id && is_array($v)) {
return isset($v[$id]) ? $v[$id] : $def; return isset($v[$id]) ? $v[$id] : $def;
} }

View file

@ -3,14 +3,20 @@
/** /**
* Класс сервиса = Упрощенный компонент * Класс сервиса = Упрощенный компонент
*/ */
class Controller_Service namespace ctiso\Controller;
use ctiso\Path;
class Service
{ {
public $viewPath = array(); public $viewPath = [];
public $webPath = [];
public $registry; // Registry->getInstance public $registry; // Registry->getInstance
public $template; public $template;
public $templatePath; public $templatePath;
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
public $db;
public function getTemplatePath($name) public function getTemplatePath($name)
{ {
return Path::join($this->viewPath[0], 'templates', 'modern', $name); return Path::join($this->viewPath[0], 'templates', 'modern', $name);
@ -43,7 +49,7 @@ class Controller_Service
return $model; return $model;
} }
public function options($key, $val, $res) { public function options($key, $val, /*.Database_PDOStatement.*/$res) {
$result = array(); $result = array();
while($res->next()) { while($res->next()) {
$result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val));

View file

@ -1,6 +1,9 @@
<?php <?php
class Controller_State namespace ctiso\Controller;
use ctiso\Controller\Action;
class State
{ {
public $action = ''; public $action = '';
public $states = array(); public $states = array();
@ -13,7 +16,7 @@ class Controller_State
static function make($action) static function make($action)
{ {
return new Controller_State($action); return new State($action);
} }
public function addTitle($name, $url = array()) public function addTitle($name, $url = array())
@ -22,7 +25,7 @@ class Controller_State
return $this; return $this;
} }
public function addState(Controller_State $state) public function addState(State $state)
{ {
$this->states [$state->getAction()] = $state; $this->states [$state->getAction()] = $state;
return $this; return $this;
@ -49,7 +52,7 @@ class Controller_State
return false; return false;
} }
function makeTitle(Controller_Action $module) function makeTitle(Action $module)
{ {
foreach ($this->titles as $item) { foreach ($this->titles as $item) {
$module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]); $module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]);

View file

@ -1,6 +1,10 @@
<?php <?php
///<reference path="Database/PDOStatement.php" /> ///<reference path="Database/PDOStatement.php" />
require_once "Database/PDOStatement.php";
namespace ctiso;
use PDO,
ctiso\Database\Statement,
ctiso\Database\IdGenerator;
/** /**
* Класс оболочка для PDO для замены Creole * Класс оболочка для PDO для замены Creole
@ -64,7 +68,7 @@ class Database extends PDO
public function prepareStatement($query) public function prepareStatement($query)
{ {
return new Database_Statement($query, $this); return new Statement($query, $this);
} }
// Для совместимости со старым представлением баз данных CIS // Для совместимости со старым представлением баз данных CIS
@ -161,7 +165,7 @@ class Database extends PDO
} }
function getIdGenerator() { function getIdGenerator() {
return new Database_IdGenerator($this); return new IdGenerator($this);
} }
/** /**

View file

@ -1,6 +1,9 @@
<?php <?php
class Database_IdGenerator { namespace ctiso\Database;
use ctiso\Database;
class IdGenerator {
private $db; private $db;
function __construct(Database $db) { function __construct(Database $db) {
@ -21,6 +24,6 @@ class Database_IdGenerator {
} else { } else {
$result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval");
} }
return intval($result['nextval']); return (int)$result['nextval'];
} }
} }

View file

@ -1,11 +1,14 @@
<?php <?php
//Действия с базой данных согласно json файлу. //Действия с базой данных согласно json файлу.
class Database_JsonInstall { namespace ctiso\Database;
use ctiso\Database\Manager;
class JsonInstall {
public $db_manager; public $db_manager;
public $serialColumns; public $serialColumns;
public function __construct(Database_Manager $db_manager) { public function __construct(Manager $db_manager) {
$this->db_manager = $db_manager; $this->db_manager = $db_manager;
} }

View file

@ -1,6 +1,12 @@
<?php <?php
class Database_Manager namespace ctiso\Database;
use ctiso\Database,
ctiso\Tools\SQLStatementExtractor,
ctiso\Path,
Exception;
class Manager
{ {
public /*.Database.*/$db; public /*.Database.*/$db;
@ -36,7 +42,7 @@ class Database_Manager
$file = $action["source"]; $file = $action["source"];
} }
$stmtList = Tools_SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file));
foreach($stmtList as $stmt) { foreach($stmtList as $stmt) {
$this->db->executeQuery($stmt); $this->db->executeQuery($stmt);
} }

View file

@ -1,13 +1,20 @@
<?php <?php
class Database_PDOStatement extends PDOStatement implements IteratorAggregate
namespace ctiso\Database\PDOStatement;
use ctiso\\PDOStatement,
ctiso\StatementIterator,
PDO;
use ctiso\Database\StatementIterator;
class PDOStatement extends \PDOStatement implements \IteratorAggregate
{ {
protected $cursorPos = 0; protected $cursorPos = 0;
public $cache = array(); public $cache = array();
public $fields; public $fields;
function getIterator() { function getIterator() {
return new Database_StatementIterator($this); return new StatementIterator($this);
} }
protected function __construct() { protected function __construct() {
@ -66,7 +73,7 @@ class Database_PDOStatement extends PDOStatement implements IteratorAggregate
} }
function getInt($name) { function getInt($name) {
return intval($this->fields[$name]); return (int)$this->fields[$name];
} }
function getBlob($name) { function getBlob($name) {

View file

@ -3,7 +3,10 @@
/** /**
* Класс оболочка для PDOStatement для замены Creole * Класс оболочка для PDOStatement для замены Creole
*/ */
class Database_Statement namespace ctiso\Database;
use PDO;
class Statement
{ {
protected $limit = null; protected $limit = null;
protected $offset = null; protected $offset = null;

View file

@ -1,6 +1,9 @@
<?php <?php
class Database_StatementIterator implements Iterator namespace ctiso\Database;
use PDO;
class StatementIterator implements Iterator
{ {
private $result; private $result;

View file

@ -1,12 +1,14 @@
<?php <?php
class Excel_DateTime namespace ctiso\Excel;
class DateTime
{ {
public $value; public $value;
function __construct($value) function __construct($value)
{ {
$this->value = intval($value); $this->value = (int)$value;
} }
function getString() function getString()

View file

@ -3,7 +3,11 @@
/** /**
* Документ * Документ
*/ */
class Excel_Document { namespace ctiso\Excel;
use XMLWriter,
Exception;
class Document {
static $ns = "urn:schemas-microsoft-com:office:spreadsheet"; static $ns = "urn:schemas-microsoft-com:office:spreadsheet";
private $table = array (); private $table = array ();
protected $styles = array(); protected $styles = array();

View file

@ -1,12 +1,14 @@
<?php <?php
class Excel_Number namespace ctiso\Excel;
class Number
{ {
public $value; public $value;
function __construct($value) function __construct($value)
{ {
$this->value = intval($value); $this->value = (int)$value;
} }
function getString() function getString()

View file

@ -3,6 +3,8 @@
/** /**
* Клетка таблицы * Клетка таблицы
*/ */
namespace ctiso\Excel;
class TableCell class TableCell
{ {
public $style = false; public $style = false;
@ -38,7 +40,7 @@ class TableRow
/** /**
* Таблица * Таблица
*/ */
class Excel_Table class Table
{ {
static $index; static $index;
private $name; private $name;
@ -50,7 +52,7 @@ class Excel_Table
function __construct() function __construct()
{ {
$this->name = "Page " . intval(self::$index ++); $this->name = "Page " . ((int)self::$index ++);
} }
/** /**
@ -230,7 +232,7 @@ class Excel_Table
} else { } else {
$doc->writeAttribute('ss:Type', "Number"); $doc->writeAttribute('ss:Type', "Number");
} }
$doc->writeCData($this->encode($value)); $doc->writeCdata($this->encode($value));
} }
$doc->endElement(); $doc->endElement();
$doc->endElement(); $doc->endElement();

View file

@ -1,5 +1,8 @@
<?php <?php
namespace ctiso;
use Exception;
class File { class File {
static function getContents($filename) { static function getContents($filename) {
$buffer = file_get_contents($filename); $buffer = file_get_contents($filename);

View file

@ -3,7 +3,11 @@
/** /**
* Фильтр действий * Фильтр действий
*/ */
class Filter_ActionAccess namespace ctiso\Filter;
use ctiso\Filter\UserAccess,
ctiso\HttpRequest;
class ActionAccess
{ {
public $access = array(); public $access = array();
public $processor; public $processor;
@ -19,7 +23,7 @@ class Filter_ActionAccess
*/ */
function checkAction($action) { function checkAction($action) {
// Импликация !! http://ru.wikipedia.org/wiki/Импликация // Импликация !! http://ru.wikipedia.org/wiki/Импликация
return (!isset($this->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) { function execute(HttpRequest $request) {

View file

@ -1,6 +1,11 @@
<?php <?php
class Filter_ActionLogger namespace ctiso\Filter;
use ctiso\Shortcut,
ctiso\HttpRequest,
ctiso\Filter\UserAccess;
class ActionLogger
{ {
public $before = array(); public $before = array();
public $file; public $file;
@ -15,7 +20,7 @@ class Filter_ActionLogger
function execute(HttpRequest $request) { function execute(HttpRequest $request) {
$action = $request->getAction(); $action = $request->getAction();
if(in_array($action, $this->before)) { 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); return $this->processor->execute($request);
} }

View file

@ -1,6 +1,8 @@
<?php <?php
class Filter_Authorization { namespace ctiso\Filter;
class Authorization {
const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#';
const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign';

View file

@ -3,7 +3,10 @@
/** /**
* Попытка реализовать фильтр для запросов * Попытка реализовать фильтр для запросов
*/ */
class Filter_Filter namespace ctiso\Filter;
use ctiso\HttpRequest;
class Filter
{ {
public $processor; public $processor;
public function __construct(/*.Controller_Action.*/$processor) public function __construct(/*.Controller_Action.*/$processor)

View file

@ -8,11 +8,19 @@
*/ */
// В класс авторизации передавать обьект для управления пользователем // В класс авторизации передавать обьект для управления пользователем
// Вынести в отдельный файл // Вынести в отдельный файл
class Filter_Login extends Filter_Filter namespace ctiso\Filter;
use ctiso\Filter\Filter,
ctiso\HttpRequest,
ctiso\Settings,
ctiso\Database,
ctiso\Collection;
class Login extends Filter
{ {
const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#';
const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign';
public $mode = 'ajax'; public $mode = 'ajax';
public $user;
function __construct($processor, $role, $whitelist = []) { function __construct($processor, $role, $whitelist = []) {
parent::__construct($processor); parent::__construct($processor);
@ -33,6 +41,7 @@ class Filter_Login extends Filter_Filter
$login = $request->get('login'); $login = $request->get('login');
$password = $request->get('password'); $password = $request->get('password');
$result = $this->role->getUserByLogin($login); // Поиск по логину $result = $this->role->getUserByLogin($login); // Поиск по логину
if ($result) { if ($result) {
$userPassword = $this->role->getUserPassword($result); $userPassword = $this->role->getUserPassword($result);

View file

@ -3,6 +3,9 @@
/** /**
* Поле с цветом * Поле с цветом
*/ */
class Form_Color extends Form_Field namespace ctiso\Form;
use ctiso\Form\Field;
class Color extends Field
{ {
} }

View file

@ -2,5 +2,8 @@
/** /**
* Поле с датой * Поле с датой
*/ */
class Form_Date extends Form_Field { namespace ctiso\Form;
use ctiso\Form\Field;
class Date extends Field {
} }

View file

@ -2,7 +2,9 @@
/** /**
* Элемент формы * Элемент формы
*/ */
class Form_Field namespace ctiso\Form;
class Field
{ {
public $hidden = false; public $hidden = false;
public $name; public $name;

View file

@ -4,7 +4,15 @@
* При рендеринге каждому классу соответствует шаблон (см. themes/maxim/templates/macros.html) * При рендеринге каждому классу соответствует шаблон (см. 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; public $checked = false;
function setValue($value) function setValue($value)
@ -14,7 +22,7 @@ class TCheckbox extends Form_Field
} }
} }
class TQuestionType extends Form_Select class TQuestionType extends Select
{ {
function setValue($value) 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; 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 $field = array(); //Поля формы
public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам 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) foreach ($validator->getErrorMsg() as $name => $error)
{ {

View file

@ -3,5 +3,8 @@
/** /**
* Поле ввода Input * Поле ввода Input
*/ */
class Form_Input extends Form_Field { namespace ctiso\Form;
use ctiso\Form\Field;
class Input extends Field {
} }

View file

@ -1,6 +1,11 @@
<?php <?php
class Form_OptionFactory { namespace ctiso\Form;
use ctiso\Form\Select,
ctiso\Model\Resources,
ctiso\Model\Factory;
class OptionFactory {
public $db; public $db;
public $registry; public $registry;
function __construct($db, $registry = null) { function __construct($db, $registry = null) {
@ -8,23 +13,23 @@ class Form_OptionFactory {
$this->registry = $registry; $this->registry = $registry;
} }
function create(Form_Select $field, $input) { function create(Select $field, $input) {
if (isset($input['options.resid'])) { if (isset($input['options.resid'])) {
$type = $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)); $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type));
} else if (isset($input['options.res'])) { } else if (isset($input['options.res'])) {
$type = $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)); $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type));
} else if (isset($input['options.all_res'])) { } else if (isset($input['options.all_res'])) {
$type = $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)); $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type));
} else if (isset($input['options.db'])) { } else if (isset($input['options.db'])) {
@ -39,7 +44,7 @@ class Form_OptionFactory {
} elseif (isset($input['options.pair'])) { } elseif (isset($input['options.pair'])) {
$field->options = $this->optionsPair($input['options.pair']); $field->options = $this->optionsPair($input['options.pair']);
} elseif (isset($input['options.model'])) { } 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']); $model = $factory->getModel($input['options.model']);
$field->options = $model->getAllAsOptions(); $field->options = $model->getAllAsOptions();
} else { } else {

View file

@ -1,6 +1,9 @@
<?php <?php
class Form_Select extends Form_Field namespace ctiso\Form;
use ctiso\Form\Field;
class Select extends Field
{ {
public $options = array(); public $options = array();

View file

@ -1,6 +1,9 @@
<?php <?php
class Form_SelectMany extends Form_Select namespace ctiso\Form;
use ctiso\Form\Select;
class SelectMany extends Select
{ {
function setValue($value) function setValue($value)
{ {

View file

@ -3,7 +3,10 @@
/** /**
* Выбор из одного элемента * Выбор из одного элемента
*/ */
class Form_SelectOne extends Form_Select namespace ctiso\Form;
use ctiso\Form\Select;
class SelectOne extends Select
{ {
function setValue($value) function setValue($value)
{ {

View file

@ -3,7 +3,10 @@
/** /**
* Текстовое поле * Текстовое поле
*/ */
class Form_TextArea extends Form_Field { namespace ctiso\Form;
use ctiso\Form\Field;
class TextArea extends Field {
function setValue($value) function setValue($value)
{ {
$this->value = $value; $this->value = $value;

View file

@ -4,7 +4,9 @@
* http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html * 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(); private $values = array();

View file

@ -8,7 +8,9 @@
/** /**
* Эмуляция каррированой функции * Эмуляция каррированой функции
*/ */
class __right { namespace ctiso;
class right {
protected $params; protected $params;
protected $fn; protected $fn;
@ -24,7 +26,7 @@ class __right {
} }
} }
class __left { class left {
protected $params; protected $params;
protected $fn; protected $fn;
@ -41,7 +43,7 @@ class __left {
} }
define('__', '_ARGUMENT_PLACE_'); define('__', '_ARGUMENT_PLACE_');
class __partial { class partial {
protected $params; protected $params;
protected $fn; protected $fn;
@ -53,7 +55,8 @@ class __partial {
function apply() { function apply() {
$params = func_get_args(); $params = func_get_args();
$result = array(); $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] == __) { if ($this->params[$i] == __) {
$result [] = $params[$j]; $result [] = $params[$j];
$j++; $j++;
@ -68,7 +71,7 @@ class __partial {
/** /**
* Композиция функций * Композиция функций
*/ */
class __compose { class compose {
protected $fns; protected $fns;
function __construct($list) { function __construct($list) {
$this->fns = array_reverse($list); $this->fns = array_reverse($list);
@ -77,7 +80,8 @@ class __compose {
function apply () { function apply () {
$params = func_get_args (); $params = func_get_args ();
$result = call_user_func_array($this->fns[0], $params); $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); $result = call_user_func($this->fns[$i], $result);
} }
return $result; return $result;
@ -86,8 +90,8 @@ class __compose {
class Functions { class Functions {
static function partial() { static function partial($_rest) {
$closure = new __partial(func_get_args()); $closure = new partial(func_get_args());
return array($closure, 'apply'); return array($closure, 'apply');
} }
@ -99,8 +103,8 @@ class Functions {
* *
* @return array[int]mixed * @return array[int]mixed
*/ */
static function compose() { static function compose($_rest) {
$closure = new __compose(func_get_args()); $closure = new compose(func_get_args());
return array($closure, 'apply'); return array($closure, 'apply');
} }
@ -110,7 +114,7 @@ class Functions {
* @return array[int]mixed * @return array[int]mixed
*/ */
static function rcurry($_rest) { static function rcurry($_rest) {
$closure = new __right(func_get_args ()); $closure = new right(func_get_args ());
return array($closure, 'apply'); return array($closure, 'apply');
} }
@ -120,7 +124,7 @@ class Functions {
* @return array[int]mixed * @return array[int]mixed
*/ */
static function lcurry($_rest) { static function lcurry($_rest) {
$closure = new __left(func_get_args ()); $closure = new left(func_get_args ());
return array($closure, 'apply'); return array($closure, 'apply');
} }
@ -306,7 +310,8 @@ class Functions {
assert(is_int($length)); assert(is_int($length));
$result = array(); $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); $result [] = array_slice($array, $i, $length);
} }
return $result; return $result;

View file

@ -3,6 +3,11 @@
/** /**
* Неверный запрос * Неверный запрос
*/ */
namespace ctiso;
use Exception,
ctiso\Collection,
ctiso\Session;
class WrongRequestException extends Exception class WrongRequestException extends Exception
{ {
} }

View file

@ -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) function execute(HttpRequest $request)
{ {

View file

@ -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(); protected $condition = array();
@ -17,7 +22,7 @@ class Layout_Manager extends Filter_Filter
* addConditionGet(array('module' => 'personal'), 'personal') * addConditionGet(array('module' => 'personal'), 'personal')
* addConditionGet(array('module' => 'login'), 'login') * 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); $this->addCondition(Functions::rcurry(array($this, 'checkGet'), $get), $layout);
} }
@ -25,12 +30,12 @@ class Layout_Manager extends Filter_Filter
/** /**
* Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax
*/ */
public function addConditionXHR($get, Filter_Filter $layout) public function addConditionXHR($get, Filter $layout)
{ {
$this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout);
} }
public function checkGet($request, $get) public function checkGet(/*.HttpRequest.*/$request, $get)
{ {
if (is_array($get)) { if (is_array($get)) {
foreach ($get as $key => $value) { foreach ($get as $key => $value) {
@ -42,7 +47,7 @@ class Layout_Manager extends Filter_Filter
return true; return true;
} }
public function checkXHR($request, $get) public function checkXHR(/*.HttpRequest.*/$request, $get)
{ {
return $request->isAjax() && $this->checkGet($request, $get); return $request->isAjax() && $this->checkGet($request, $get);
} }
@ -52,7 +57,7 @@ class Layout_Manager extends Filter_Filter
* @parma $get function(HttpRequest) Функция * @parma $get function(HttpRequest) Функция
* @parma $layout Layout Макет * @parma $layout Layout Макет
*/ */
public function addCondition($get, Filter_Filter $layout) public function addCondition($get, Filter $layout)
{ {
$this->condition [] = array($get, $layout); $this->condition [] = array($get, $layout);
} }

View file

@ -4,6 +4,10 @@
* Класс для работы с почтой * Класс для работы с почтой
* http://en.wikipedia.org/wiki/MIME * http://en.wikipedia.org/wiki/MIME
*/ */
namespace ctiso;
use ctiso\Path,
Exception;
class Mail class Mail
{ {
public $_from; public $_from;

View file

@ -1,5 +1,8 @@
<?php <?php
namespace ctiso;
use PHPMailer;
class MailAlt class MailAlt
{ {
public $mailer; public $mailer;

View file

@ -1,6 +1,9 @@
<?php <?php
class Model_Factory namespace ctiso\Model;
use ctiso\Settings;
class Factory
{ {
static $shortcut = "model"; static $shortcut = "model";
public $db; public $db;

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
class Numbers class Numbers
{ {
static function roman($i) static function roman($i)
@ -15,7 +17,8 @@ class Numbers
static function prefix($prefix, array $array, $key = false) static function prefix($prefix, array $array, $key = false)
{ {
$result = array(); $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]; $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i];
} }
return $result; return $result;

View file

@ -6,6 +6,8 @@
* *
*/ */
namespace ctiso;
class Path class Path
{ {
const SEPARATOR = "/"; const SEPARATOR = "/";
@ -160,8 +162,9 @@ class Path
// Сравнение двух путей на равентство // Сравнение двух путей на равентство
public function equal(/*.Path.*/ $path) public function equal(/*.Path.*/ $path)
{ {
if (count($this->path) == count($path->path)) { $count = count($this->path);
for ($i = 0; $i < count($this->path); $i++) { if ($count == count($path->path)) {
for ($i = 0; $i < $count; $i++) {
if ($this->path[$i] != $path->path[$i]) { if ($this->path[$i] != $path->path[$i]) {
return false; return false;
} }
@ -207,8 +210,9 @@ class Path
if (isset($this->url['host']) && isset($path->url['host']) if (isset($this->url['host']) && isset($path->url['host'])
&& ($this->url['host'] != $path->url['host'])) return false; && ($this->url['host'] != $path->url['host'])) return false;
if (count($path->path) > count($this->path)) { $count = count($this->path);
for ($i = 0; $i < count($this->path); $i++) { if (count($path->path) > $count) {
for ($i = 0; $i < $count; $i++) {
if ($path->path[$i] != $this->path[$i]) { if ($path->path[$i] != $this->path[$i]) {
return false; return false;
} }
@ -252,15 +256,18 @@ class Path
$list_path = $list->getParts(); $list_path = $list->getParts();
$result = array(); $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]) { if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) {
break; break;
} }
} }
for($j = $i; $j < count($list_path); $j++) { $list_count = count($list_path);
for($j = $i; $j < $list_count; $j++) {
array_push($result, '..'); 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]); array_push($result, $self_path[$j]);
} }
return implode("/", $result); return implode("/", $result);

View file

@ -6,6 +6,8 @@
* @package system * @package system
*/ */
namespace ctiso;
class Primitive { class Primitive {
// varchar // varchar
public static function to_varchar($value) public static function to_varchar($value)
@ -48,9 +50,9 @@ class Primitive {
if (!empty($tmp)) { if (!empty($tmp)) {
if (count($tmp) != 3) return $result; if (count($tmp) != 3) return $result;
$year = intval($tmp[2]); $year = (int)$tmp[2];
$month = intval($tmp[1]); $month = (int)$tmp[1];
$day = intval($tmp[0]); $day = (int)$tmp[0];
if ($month != 0 && $day != 0 && $year != 0) { if ($month != 0 && $day != 0 && $year != 0) {
if (checkdate($month, $day, $year)) { if (checkdate($month, $day, $year)) {

View file

@ -1,7 +1,11 @@
<?php <?php
namespace ctiso;
use ctiso\Database,
ctiso\Database\Statement;
// Класс должен быть в библиотеке приложения // Класс должен быть в библиотеке приложения
class Role_User class User
{ {
const LIFE_TIME = 1800; // = 30min * 60sec; const LIFE_TIME = 1800; // = 30min * 60sec;
@ -11,22 +15,20 @@ class Role_User
public $password; public $password;
public $id; public $id;
public $db; public $db;
public $groups;
protected function __construct() protected function __construct($db, $groups) {
{
} }
public function setDB(Database $db) public function setDB(Database $db) {
{
$this->db = $db; $this->db = $db;
} }
public function getUserByQuery(Database_Statement $stmt) public function getUserByQuery(Statement $stmt)
{ {
global $GROUPS;
$result = $stmt->executeQuery(); $result = $stmt->executeQuery();
if ($result->next()) { if ($result->next()) {
$this->access = $GROUPS[$result->getString('access')]; $this->access = $this->groups[$result->getString('access')];
$this->name = $result->getString('login'); $this->name = $result->getString('login');
$this->id = $result->getInt('id_user'); $this->id = $result->getInt('id_user');
$this->password = $result->getString('password'); $this->password = $result->getString('password');

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
class Security { class Security {
static function generatePassword($length = 9, $strength = 0) { static function generatePassword($length = 9, $strength = 0) {
$vowels = 'aeuy'; $vowels = 'aeuy';

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
class Session class Session
{ {
function get($key) function get($key)

View file

@ -9,6 +9,11 @@
* parameters1, parameters1 - Массивы с параметрами модуля * parameters1, parameters1 - Массивы с параметрами модуля
* Имя необходимо чтобы потом легко было удалить ненужные ветки дерева * Имя необходимо чтобы потом легко было удалить ненужные ветки дерева
*/ */
namespace ctiso;
use ctiso\Collection,
ctiso\File,
Exception;
class Settings extends Collection class Settings extends Collection
{ {
protected $file; protected $file;

View file

@ -7,6 +7,10 @@
* $setup->executeActions('install'); * $setup->executeActions('install');
* </code> * </code>
*/ */
namespace ctiso;
use ZipArchive,
ctiso\Tools\SQLStatementExtractor;
class Setup class Setup
{ {
protected $actions = array(); protected $actions = array();
@ -198,7 +202,7 @@ class Setup
*/ */
function batchSQLZip(/*.Database.*/ $conn, $file) function batchSQLZip(/*.Database.*/ $conn, $file)
{ {
$stmtList = Tools_SQLStatementExtractor::extract($this->zip->getFromName($file)); $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file));
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {
$conn->executeQuery ($stmt); $conn->executeQuery ($stmt);
} }
@ -206,7 +210,7 @@ class Setup
static function batchSQL(/*.Database.*/ $conn, $file) static function batchSQL(/*.Database.*/ $conn, $file)
{ {
$stmtList = Tools_SQLStatementExtractor::extractFile($file); $stmtList = SQLStatementExtractor::extractFile($file);
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {
$conn->executeQuery ($stmt); $conn->executeQuery ($stmt);
} }

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
class SortRecord class SortRecord
{ {
public $key; public $key;

View file

@ -3,34 +3,36 @@
/** /**
* Расширения для PHPTAL для отображения времени и даты * Расширения для PHPTAL для отображения времени и даты
*/ */
class DateTime_Tales implements PHPTAL_Tales namespace ctiso;
use PHPTAL_Php_TalesInternal,
ctiso\Controller\Site,
ctiso\Controller\Component,
ctiso\HttpRequest,
PHPTAL_TalesRegistry;
class Tales_DateTime_ implements PHPTAL_Tales
{ {
static public function date($expression, $nothrow = false) static public function date($expression, $nothrow = false) {
{ return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")";
return "Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")";
} }
static public function time($expression, $nothrow = false) static public function time($expression, $nothrow = false) {
{ return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path ($expression).")";
return "Tales::phptal_time(".PHPTAL_Php_TalesInternal::path ($expression).")";
} }
} }
class Tales_Component implements PHPTAL_Tales
/**
* TALES для подключения компонентов
* component:name?param1=value1&param2=value2
*/
class Component_Tales implements PHPTAL_Tales
{ {
static public function component($expression, $nothrow = false) static public function component($expression, $nothrow = false)
{ {
$s = PHPTAL_Php_TalesInternal::string($expression); $s = PHPTAL_Php_TalesInternal::string($expression);
return "Tales::phptal_component(" . $s . ")"; return "ctiso\\Tales::phptal_component(" . $s . ")";
} }
} }
class Tales { class Tales {
static $db;
static $registry;
static function phptal_date ($e) { static function phptal_date ($e) {
return date("d.m.Y", $e); return date("d.m.Y", $e);
@ -47,14 +49,12 @@ class Tales {
$begin = floatval(microtime(true)); $begin = floatval(microtime(true));
/*.Controller_Component.*/$component = null; /*.Controller_Component.*/$component = null;
if (class_exists("Controller_Site")) { //Если мы в CMS2 if (class_exists("ctiso\\Controller\\Site")) { //Если мы в CMS2
$component = Controller_Site::loadComponent($expression); $component = Site::loadComponent($expression);
} else { } else {
global $db, $registry; // Иначе обращаемся к глобальным переменным $component = Component::loadComponent($expression, self::$db, self::$registry);
$component = Controller_Component::loadComponent($expression, $db, $registry);
} }
$req = new HttpRequest(); $req = new HttpRequest();
$result = $component->execute($req); $result = $component->execute($req);
echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->"; echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->";
@ -62,11 +62,14 @@ class Tales {
} }
static function register() { static function register($db, $registry) {
self::$db = $db;
self::$registry = $registry;
/* Регистрация нового префикса для подключения компонента */ /* Регистрация нового префикса для подключения компонента */
$tales = PHPTAL_TalesRegistry::getInstance(); $tales = PHPTAL_TalesRegistry::getInstance();
$tales->registerPrefix('component', array('Component_Tales', 'component')); $tales->registerPrefix('component', array('ctiso\\Component_Tales', 'component'));
$tales->registerPrefix('date', array('DateTime_Tales', 'date')); $tales->registerPrefix('date', array('ctiso\\DateTime_Tales', 'date'));
$tales->registerPrefix('time', array('DateTime_Tales', 'time')); $tales->registerPrefix('time', array('ctiso\\DateTime_Tales', 'time'));
} }
} }

View file

@ -1,6 +1,8 @@
<?php <?php
class Tools_Drawing namespace ctiso\Tools;
class Drawing
{ {
const ALIGN_LEFT = "left"; const ALIGN_LEFT = "left";
const ALIGN_TOP = "top"; const ALIGN_TOP = "top";
@ -40,7 +42,8 @@ class Tools_Drawing
$first_word = true; $first_word = true;
$last_width = 0; $last_width = 0;
for ($i = 0; $i < count($words); $i++) { $count = count($words);
for ($i = 0; $i < $count; $i++) {
$item = $words[$i]; $item = $words[$i];
$dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item);
$line_width = $dimensions[2] - $dimensions[0]; $line_width = $dimensions[2] - $dimensions[0];

View file

@ -1,6 +1,8 @@
<?php <?php
class Tools_Image namespace ctiso\Tools;
class Image
{ {
static function load($uri) static function load($uri)
{ {

View file

@ -26,7 +26,10 @@
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
* @package creole.util.sql * @package creole.util.sql
*/ */
class Tools_SQLStatementExtractor { namespace ctiso\Tools;
use Exception;
class SQLStatementExtractor {
protected static $delimiter = ';'; protected static $delimiter = ';';
@ -111,7 +114,7 @@ class Tools_SQLStatementExtractor {
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
return (strpos($string, $check) === 0) ? true : false; return (strpos($string, $check) === 0);
} }
} }
@ -125,7 +128,7 @@ class Tools_SQLStatementExtractor {
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
return (strpos(strrev($string), strrev($check)) === 0) ? true : false; return (strpos(strrev($string), strrev($check)) === 0);
} }
} }

View file

@ -1,6 +1,8 @@
<?php <?php
class Tools_String { namespace ctiso\Tools;
class String {
// from creole // from creole
static function strToArray($str) { static function strToArray($str) {
@ -15,7 +17,7 @@ class Tools_String {
if ($in_subarr > 0) { // already in sub-array? if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok; $subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component 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--; $in_subarr--;
} }
} elseif ($tok{0} === '{') { // we're inside a new sub-array } elseif ($tok{0} === '{') { // we're inside a new sub-array
@ -25,7 +27,7 @@ class Tools_String {
$subarr[$in_subarr] = array(); $subarr[$in_subarr] = array();
$subarr[$in_subarr][] = $tok; $subarr[$in_subarr][] = $tok;
} else { } else {
$res[] = strToArray($tok); $res[] = self::strToArray($tok);
} }
} else { // not sub-array } else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings) $val = trim($tok, '"'); // remove " (surrounding strings)

View file

@ -3,7 +3,10 @@
/** /**
* Формат для композиции изображений * Формат для композиции изображений
*/ */
class Tools_TemplateImage namespace ctiso\Tools;
use ctiso\Tools\Drawing;
class TemplateImage
{ {
static $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); static $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp');
static $listfonts = array( static $listfonts = array(
@ -33,13 +36,16 @@ class Tools_TemplateImage
protected $data = array(); protected $data = array();
protected $base = "c:\\windows\\fonts\\"; protected $base = "c:\\windows\\fonts\\";
protected $image; protected $image;
protected $prepare = true; protected $_prepare = true;
public $debug = false; public $debug = false;
function __construct ($template = false) public $resource;
public $filename;
function __construct ($template = null)
{ {
// assert(is_string($src)); // assert(is_string($src));
if($template) { if ($template) {
$this->data = $template; $this->data = $template;
} }
} }
@ -116,7 +122,7 @@ class Tools_TemplateImage
return ""; return "";
} }
function imageText($text, $value) function imageText($text, /*.stdClass.*/$value)
{ {
assert(is_string($text)); assert(is_string($text));
@ -126,22 +132,22 @@ class Tools_TemplateImage
$color = intval(substr($value->color, 1), 16); $color = intval(substr($value->color, 1), 16);
if ($value->align[0]) { if ($value->align[0]) {
$align = Tools_Drawing::ALIGN_LEFT; $align = Drawing::ALIGN_LEFT;
} elseif ($value->align[2]) { } elseif ($value->align[2]) {
$align = Tools_Drawing::ALIGN_RIGHT; $align = Drawing::ALIGN_RIGHT;
} else { } else {
$align = Tools_Drawing::ALIGN_CENTER; $align = Drawing::ALIGN_CENTER;
} }
if ($value->valign[0]) { if ($value->valign[0]) {
$valign = Drawing::ALIGN_TOP; $valign = Drawing::ALIGN_TOP;
} elseif ($value->valign[1]) { } elseif ($value->valign[1]) {
$valign = Tools_Drawing::ALIGN_CENTER; $valign = Drawing::ALIGN_CENTER;
} else { } 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, $value->width, $value->height,
$align, $valign); $align, $valign);
} }
@ -159,7 +165,7 @@ class Tools_TemplateImage
{ {
$width = imagesx($this->image); $width = imagesx($this->image);
$height = imagesy($this->image); $height = imagesy($this->image);
if($new_height == false) { if ($new_height == null) {
$new_height = ceil($height * $new_width / $width); $new_height = ceil($height * $new_width / $width);
} }
@ -171,8 +177,8 @@ class Tools_TemplateImage
} }
function prepare() { function prepare() {
if($this->prepare) { if($this->_prepare) {
$this->prepare = false; $this->_prepare = false;
foreach ($this->data as $value) { foreach ($this->data as $value) {
$this->imageText($value->text, $value); // break; $this->imageText($value->text, $value); // break;
} }

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
class UTF8 { class UTF8 {
static function str_split($str, $split_length = 1) { static function str_split($str, $split_length = 1) {
$split_length = (int) $split_length; $split_length = (int) $split_length;

View file

@ -8,6 +8,9 @@
* Исключение с понятным пользователю сообщением, которое имеет смысл ему показать. * Исключение с понятным пользователю сообщением, которое имеет смысл ему показать.
* @see Controller_Front * @see Controller_Front
*/ */
namespace ctiso;
use Exception;
class UserMessageException extends Exception { class UserMessageException extends Exception {
public $userMessage; public $userMessage;
public function __construct($message) { public function __construct($message) {

View file

@ -1,6 +1,9 @@
<?php <?php
abstract class Validator_Rule_Abstract abstract namespace ctiso\Validator\Rule;
use ctiso\Collection;
class Abstract
{ {
public $field; public $field;
protected $errorMsg; protected $errorMsg;

View file

@ -3,7 +3,11 @@
/** /**
* Проверка на число * Проверка на число
*/ */
class Validator_Rule_Alpha extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Alpha extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
class Validator_Rule_Code extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Code extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {
@ -25,7 +29,8 @@ class Validator_Rule_Code extends Validator_Rule_Abstract
$name = $this->field; $name = $this->field;
if (is_array($_POST[$name . '_code_genre'])) { 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( $code = array(
$_POST[$name . '_code_genre'][$n], $_POST[$name . '_code_genre'][$n],
$_POST[$name . '_code_f'][$n], $_POST[$name . '_code_f'][$n],

View file

@ -3,10 +3,14 @@
/** /**
* Проверка формата даты * Проверка формата даты
*/ */
class Validator_Rule_Count extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Count extends Abstract
{ {
public $size = 1; public $size = 1;
public $max = false; public $max = null;
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата даты * Проверка формата даты
*/ */
class Validator_Rule_Date extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Date extends Abstract
{ {
private $split = "\\/"; private $split = "\\/";
@ -15,6 +19,7 @@ class Validator_Rule_Date extends Validator_Rule_Abstract
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null)
{ {
$pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/"; $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/";
$matches = [];
return (preg_match($pattern, $container->get($this->field), $matches) return (preg_match($pattern, $container->get($this->field), $matches)
&& checkdate($matches[2], $matches[1], $matches[3])); && checkdate($matches[2], $matches[1], $matches[3]));
} }

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
class Validator_Rule_Email extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Email extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
class Validator_Rule_EmailList extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class EmailList extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -1,6 +1,11 @@
<?php <?php
class Validator_Rule_FileName extends Validator_Rule_Abstract { namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection,
ctiso\Path;
class FileName extends Abstract {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата времени * Проверка формата времени
*/ */
class Validator_Rule_IsFile extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class IsFile extends Abstract
{ {
private $type = array(); private $type = array();
private $maxsize = 1024; private $maxsize = 1024;

View file

@ -3,7 +3,11 @@
/** /**
* Проверка на равентство двух полей * Проверка на равентство двух полей
*/ */
class Validator_Rule_Match extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Match extends Abstract
{ {
public $same; public $same;

View file

@ -1,6 +1,10 @@
<?php <?php
class Validator_Rule_Notnull extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Notnull extends Abstract
{ {
function skipEmpty() { function skipEmpty() {
return false; return false;

View file

@ -3,7 +3,11 @@
/** /**
* Проверка на число * Проверка на число
*/ */
class Validator_Rule_Numeric extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Numeric extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -3,7 +3,11 @@
/** /**
* Проверка формата времени * Проверка формата времени
*/ */
class Validator_Rule_Time extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Time extends Abstract
{ {
private $split = ":"; private $split = ":";
@ -23,7 +27,7 @@ class Validator_Rule_Time extends Validator_Rule_Abstract
{ {
$tmp = explode($this->split, $container->get($this->field), 2); $tmp = explode($this->split, $container->get($this->field), 2);
if ($tmp) { if ($tmp) {
if (self::checktime ($tmp[0], $tmp[1])) { if (self::checktime ((int)$tmp[0], (int)$tmp[1])) {
return true; return true;
} }
} }

View file

@ -2,7 +2,11 @@
/** /**
*/ */
class Validator_Rule_Unique extends Validator_Rule_Abstract namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\Abstract,
ctiso\Collection;
class Unique extends Abstract
{ {
public function getErrorMsg() public function getErrorMsg()
{ {

View file

@ -5,7 +5,11 @@
/** /**
* Проверка коллекции * Проверка коллекции
*/ */
class Validator_Validator namespace ctiso\Validator;
use Exception,
ctiso\Collection;
class Validator
{ {
protected $chain = array(); // Массив правил protected $chain = array(); // Массив правил
protected $errorMsg = array(); // Массив ошибок protected $errorMsg = array(); // Массив ошибок

View file

@ -4,7 +4,11 @@
*/ */
// View_Base + PHPTAL = View_Template (View_Composite) // View_Base + PHPTAL = View_Template (View_Composite)
class View_Composite extends View_View namespace ctiso\View;
use ctiso\View\View,
PHPTAL;
class Composite extends View
{ {
private $tal; private $tal;

View file

@ -1,6 +1,9 @@
<?php <?php
class View_List extends View_View namespace ctiso\View;
use ctiso\View\View;
class List extends View
{ {
function execute() function execute()
{ {

View file

@ -1,6 +1,12 @@
<?php <?php
class View_Page extends View_View namespace ctiso\View;
use ctiso\View\View,
ctiso\Controller\Site,
ctiso\Controller\Component,
ctiso\HttpRequest;
class Page extends View
{ {
private $counter; private $counter;
public $text; public $text;
@ -52,10 +58,10 @@ class View_Page extends View_View
if(class_exists("Controller_Site")){ //Если мы в CMS2 if(class_exists("Controller_Site")){ //Если мы в CMS2
$component = Controller_Site::loadComponent($match); $component = Site::loadComponent($match);
} else { } else {
global $db, $registry; // global $db, $registry; //
$component = Controller_Component::loadComponent($match, $db, $registry); $component = Component::loadComponent($match, $db, $registry);
} }
$req = new HttpRequest(); $req = new HttpRequest();

View file

@ -3,7 +3,9 @@
* @package system.widgets * @package system.widgets
*/ */
class View_Pages namespace ctiso\View;
class Pages
{ {
static $range = 5; static $range = 5;
static function getPages($page, $onpage, $count, $prefix = '?') static function getPages($page, $onpage, $count, $prefix = '?')

View file

@ -6,7 +6,9 @@
/** /**
* @package system.view * @package system.view
*/ */
class View_Plain namespace ctiso\View;
class Plain
{ {
protected $document; protected $document;
protected $values = array(); protected $values = array();

View file

@ -1,6 +1,9 @@
<?php <?php
class View_Top extends View_Composite { namespace ctiso\View;
use ctiso\View\Composite;
class Top extends Composite {
/** /**
* Общая строка заголовка * Общая строка заголовка
*/ */

View file

@ -1,6 +1,9 @@
<?php <?php
class View_View namespace ctiso\View;
use Exception;
class View
{ {
protected $_section = array(); // Вложенные шаблоны protected $_section = array(); // Вложенные шаблоны
// Блоки // Блоки

View file

@ -3,6 +3,9 @@
/** /**
* Расширение класса ZipArchive с возможность архивирования директории * Расширение класса ZipArchive с возможность архивирования директории
*/ */
namespace ctiso;
use ZipArchive;
class ZipFile extends ZipArchive class ZipFile extends ZipArchive
{ {
private $ignore = array('.', '..'); private $ignore = array('.', '..');

View file

@ -1,5 +1,7 @@
<?php <?php
namespace ctiso;
if (!function_exists('str_getcsv')) { if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 1024; $fiveMBs = 1024;

View file

@ -16,6 +16,9 @@
* @param array $table Таблица * @param array $table Таблица
* @param Function $fn Функция которая применяется к каждой ветке дерева * @param Function $fn Функция которая применяется к каждой ветке дерева
*/ */
namespace ctiso;
use ctiso\Functions;
function tableTreeWalk($level, $table, $fn) { function tableTreeWalk($level, $table, $fn) {
if (empty ($level)) return $table; if (empty ($level)) return $table;
$name = array_shift ($level); $name = array_shift ($level);