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')); -