Версия полностью совместимая c CMS

This commit is contained in:
origami11 2017-02-17 17:31:17 +03:00
parent 7ce493414e
commit 75bb35d5bf
21 changed files with 1404 additions and 783 deletions

View file

@ -13,7 +13,7 @@ function forceUrl($name)
/**
* Контроллер страниц
*/
*/
class Controller_Action
{
@ -24,9 +24,16 @@ class Controller_Action
public $themePath; // Глобальный путь к текущей теме
// Параметры устанавливаются при создании контроллера
public $name; // Имя модуля
public $viewPath = null; // Путь к шаблонам контроллера
public /*.Database.*/$db; // Соединение с базой данных
public $name = ''; // Имя модуля
public $viewPath = null; // Путь к шаблонам контроллера
public $viewPathPrefix = null; // Путь к шаблонам контроллера
public $moduleTitle = "";
/**
* Соединение с базой данных
*/
public $db;
// Фильтры
public $access = null; // Обьект хранит параметры доступа
@ -42,14 +49,11 @@ class Controller_Action
public $iconPath = '';
public $path;
public function __construct ()
{
//
public function __construct () {
$this->path = new Widgets_PathMenu();
}
public function setUp ()
{
// override this
public function setUp() {
}
public function loadConfig($name) {
@ -69,15 +73,16 @@ class Controller_Action
public function installPath($name)
{
return Path::join(CMS_PATH, "modules", $name, "install");
return Path::join(CMS_PATH, "modules", $name);
}
public function addSuggest($view, $name)
public function addSuggest(View_View $view, $name)
{
$suggest = array();
$file = Path::join($this->viewPath, 'help', $name . '.suggest');
if (file_exists($file) && include($file)) {
$view->addScriptRaw("add_suggest(".json_encode($suggest).");\n");
if (file_exists($file)) {
include($file);
$view->suggestions = $suggest;
}
}
@ -85,39 +90,43 @@ class Controller_Action
{
return Path::join($this->iconPath, $size . 'x' . $size, $icon . '.png');
}
/**
* Создает представление
* @param string $file
* @return template
* @param $name String
* @param $viewClass String
* @return View_Composite
*/
public function getView($name)
public function getView($name, $viewClass = 'View_Composite')
{
$file = $name . self::TEMPLATE_EXTENSION;
// Список возможных директорий для поиска файла шаблона
$theme = $this->_registry->readKey(array('system', 'theme'));
$icon_theme = $this->_registry->readKey(array('system', 'icon_theme'));
$list = array(
Path::join($this->viewPath, TEMPLATES) => Path::join(WWW_PATH, "modules", $this->name, TEMPLATES),
PHPTAL_TEMPLATE_REPOSITORY => "");
$file = $name . self::TEMPLATE_EXTENSION;
$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")
);
// Поиск файла для шаблона
foreach($list as $ospath => $path) {
$template = Path::join($ospath, $file);
$template = Path::join($ospath, $file);
if(file_exists($template)) { break; }
}
$tpl = new View_Composite($template);
$tpl->icons = $this->iconPath; // Путь к файлам текущей темы
$tpl->media = $this->themePath; // Путь к файлам текущей темы
$tpl->script = $this->jsPath; // Путь к файлам скриптов
$tpl->template = $path; // Путь к файлам текущего шаблона
/*.View_Composite.*/$tpl = new $viewClass($template);
$tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы
$tpl->set('media', $this->themePath); // Путь к файлам текущей темы
$tpl->set('assets', Path::join(WWW_PATH, "assets", "css"));
$tpl->set('script', $this->jsPath); // Путь к файлам скриптов
$tpl->set('template', $path); // Путь к файлам текущего шаблона
$tpl->setAlias(array(
'${icons}' => $this->iconPath,
'${media}' => $this->themePath,
'${script}' => $this->jsPath,
'${template}' => $path));
'icons' => $this->iconPath,
'script' => $this->jsPath,
// Для media и template поиск происходит как для файлов шаблонов
'media' => $list,
'template' => $list
));
$tpl->loadImports(Path::skipExtension($template) . ".import");
@ -128,7 +137,7 @@ class Controller_Action
public function getModel($name)
{
if (!$this->factory) {
$this->factory = new ModelFactory($this->db, $this->_registry, $this->_shortcut);
$this->factory = new Model_Factory($this->db, $this->_registry);
}
return $this->factory->getModel($name);
}
@ -143,57 +152,59 @@ class Controller_Action
public function execute1(HttpRequest $request)
{
$action = self::ACTION_PREFIX . ucfirst($request->getAction());
if (method_exists($this, $action)) {
return $this->forward($action, $request);
} else {
return $this->forward("actionIndex", $request);
if (!method_exists($this, $action)) {
$action = "actionIndex";
}
$view = $this->forward($action, $request);
if ($view instanceof View_View) {
$view->active_module = get_class($this);
$view->module_action = $action;
}
return $view;
}
public function execute(HttpRequest $request)
{
$result = $this->execute1($request);
if ($result) {
if (!empty($result)) {
$this->view = $result;
}
return $this->render();
$text = $this->render();
return $text;
}
public function forward($action, HttpRequest $args)
{
// Действия до вызова основного обработчика
/*foreach($this->_aspect as $aspect) {
if (isset($aspect->before[$action])) {
call_user_func ($aspect->before[$action], $action, $args);
}
}*/
return call_user_func(array($this, $action), $args);
public function forward($action, HttpRequest $args) {
$value = call_user_func(array($this, $action), $args);
return $value;
}
/**
* Страница по умолчанию
*/
public function actionIndex(HttpRequest $request)
{
public function actionIndex(HttpRequest $request) {
return "";
}
public function postUrl($name, $param)
{
return "?" . http_build_query(
array_merge(array('module' => strtolower(get_class($this)), "action" => $name),
$this->param, $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 учетом прав пользователя на ссылки
*
* @parma string $name Действие
* @parma string $param Дополнительные параметры
* @param string $name Действие
* @param array $param Дополнительные параметры
* 'mode' означает что элемент до отправки обрабатывается javascript
* @return array|null
*/
public function nUrl($name, array $param = array())
{
if (!$this->access || $this->access->checkAction($name)) {
/*.Filter_ActionAccess.*/$access = $this->access;
if ($access != null || $access->checkAction($name)) {
return lcurry(array($this, 'postUrl'), $name, $param);
}
return null;
@ -217,6 +228,12 @@ class Controller_Action
/**
* Генерация ссылки на действие контроллера
* Ajax определяется автоматически mode = ajax используется для смены layout
* @param $name
* @param array $param
* @return array|null
*
* @example ?action=$name&mode=ajax
* {$param[i].key = $param[i].value}
*/
public function aUrl($name, array $param = array())
{
@ -249,14 +266,14 @@ class Controller_Action
/**
* Загрузка файла класса
*/
public function loadClass($path, $setup = null)
public function loadClass($path, $setup = null, $prefix = '')
{
if (file_exists($path)) {
require_once ($path);
$class = pathinfo($path, PATHINFO_FILENAME);
$class = $prefix . pathinfo($path, PATHINFO_FILENAME);
return new $class($setup);
}
return null;
throw new Exception("NO CLASS $path");
}
public function loadSettings($path)
@ -269,6 +286,7 @@ class Controller_Action
// Для Widgets
public $view = null;
public $childNodes = array();
public $ctrlValues = array();
public $childViews = array();
public function setView($name)
@ -292,6 +310,11 @@ class Controller_Action
$this->childNodes[$section] = $node;
}
public function setValue(/*Widget*/ $name, $value)
{
$this->ctrlValues[$name] = $value;
}
/**
* Добавление дочернего отображения к текущему отображению
*/
@ -306,34 +329,86 @@ class Controller_Action
*/
public function render()
{
foreach ($this->childNodes as $name => $node) {
$node->make($this);
$this->view->setView($name, $node->view);
}
foreach ($this->childViews as $name => $node) {
$this->view->setView($name, $node);
}
if ($this->view instanceof View_View) {
$this->view->assignValues($this->ctrlValues);
foreach ($this->childNodes as $name => $node) {
$node->make($this);
$this->view->setView($name, $node->view);
}
foreach ($this->childViews as $name => $node) {
$this->view->setView($name, $node);
}
}
return $this->view;
}
function getPageId($request)
function getPageId(HttpRequest $request)
{
$pageId = time();
$request->session()->set('page', $pageId);
return $pageId;
}
function checkPageId($request, $page)
function checkPageId(HttpRequest $request, $page)
{
if ($request->get('__forced__')) {
return true;
}
$_page = $request->session()->get('page');
$result = ($_page && $_page == $page);
$request->session()->clean('page');
return $result;
}
function redirect($action) {
header('location: ' . $this->fUrl($action));
exit();
function _getActionPath()
{
return new Controller_State('index');
}
}
// Тоже убрать в метод Controller_Model
function getActionPath(HttpRequest $request, $action = null)
{
$this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction());
}
function addFilePathToPath($filePath, $type)
{
$pathToItem = $this->directoryPath($filePath, $type, 'default');
$this->path->addMenuItems($pathToItem['path']);
}
function directoryPath($path, $type, $action)
{
$path = empty($path) ? '/' : $path;
$base = new Path($path);
$parts = $base->getParts();
$_path = '/' . implode('/', $parts);
$rs = new Model_Resources($this->db);
$section_path = $rs->getSectionByPath($_path, $type);
$pathMenu = new Widgets_PathMenu();
$pathMenu->addTitle('title');
$modules = ['image' => 'images','page' => 'pages','document' => 'documents','media' => 'videos'];
while ($section_path->id_parent) {
$_path = '/' . implode('/', $parts);
$pathMenu->addMenuItem(
forceUrl($this->nUrl('', array('module'=>$modules[$type],'action' => $action, 'mode' => 'ajax', 'path' => $_path))),
$section_path->title
);
$section_path = $rs->getSectionById($section_path->id_parent);
array_pop($parts);
}
$pathMenu->addMenuItem(
forceUrl($this->nUrl('', array('module'=>$modules[$type],'action' => $action, 'mode' => 'ajax', 'path' => '/'))),
$this->moduleTitle
);
return $pathMenu->getItemsReverse();
}
}