+{include file="$codemirror_connect"}
\ No newline at end of file
diff --git a/admin/templates/templates/form.tpl b/admin/templates/templates/form.tpl
index 1a1e5a9..80f04c4 100644
--- a/admin/templates/templates/form.tpl
+++ b/admin/templates/templates/form.tpl
@@ -82,7 +82,7 @@
[tag:title]
diff --git a/class/class.core.php b/class/class.core.php
index e0c8e49..3d3c98e 100755
--- a/class/class.core.php
+++ b/class/class.core.php
@@ -1,1604 +1,466 @@
HTTP Error 404: Page not found';
-
- /**
- * Сообщение об ошибке, если для рубрики не найден шаблон
- *
- * @public string
- */
- public $_rubric_template_empty = 'Ошибка Не задан шаблон рубрики.';
-
- /**
- * Сообщение об ошибке, если документ запрещен к показу
- *
- * @public string
- */
- public $_doc_not_published = 'Запрашиваемый документ запрещен к публикации.';
-
- /**
- * Сообщение об ошибке, если модуль не может быть загружен
- *
- * @public string
- */
- public $_module_error = 'Запрашиваемый модуль не может быть загружен.';
-
- /**
- * Сообщение об ошибке, если модуль, указанный в шаблоне, не установлен в системе
- *
- * @public string
- */
- public $_module_not_found = 'Запрашиваемый модуль не найден.';
-
-/**
- * Внутренние методы класса
- */
-
- /**
- * Получение основных настроек сисблока
- *
- * @param string $param параметр настройки, если не указан - все параметры
- * @return mixed
*/
- function _sysBlock($id, $param = '')
+ class AVE_Core
{
- global $AVE_DB;
-
- static $sys_block = null;
-
- if ($sys_block === null)
- {
- $sys_block = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_sysblocks
- WHERE
- " . (is_numeric($id) ? 'id' : 'sysblock_alias') . " = '" . $id . "'
- ")->FetchAssocArray();
- }
-
- if ($param == '')
- return $sys_block;
-
- return isset($sys_block[$param])
- ? $sys_block[$param]
- : null;
- }
-
/**
- * Получение основных настроек сисблока
- *
- * @param string $param параметр настройки, если не указан - все параметры
- * @return mixed
+ * Свойства класса
*/
- function _requestGet($id, $param = '')
- {
- global $AVE_DB;
+ /**
+ * Текущий документ
+ *
+ * @public object
+ */
+ public $curentdoc = null;
- static $request = null;
+ /**
+ * Установленные модули
+ *
+ * @public array
+ */
+ public $install_modules = null;
- if ($request === null)
- {
- $request = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_request
- WHERE
- " . (is_numeric($id) ? 'Id' : 'request_alias') . " = '" . $id . "'
- ")->FetchAssocArray();
- }
+ /**
+ * Сообщение об ошибке, если документ не найден
+ *
+ * @public string
+ */
+ public $_doc_not_found = 'HTTP Error 404: Page not found ';
- if ($param == '')
- return $request;
+ /**
+ * Сообщение об ошибке, если для рубрики не найден шаблон
+ *
+ * @public string
+ */
+ public $_rubric_template_empty = 'Ошибка Не задан шаблон рубрики.';
- return isset($request[$param])
- ? $request[$param]
- : null;
- }
+ /**
+ * Сообщение об ошибке, если документ запрещен к показу
+ *
+ * @public string
+ */
+ public $_doc_not_published = 'Запрашиваемый документ запрещен к публикации.';
+
+ /**
+ * Сообщение об ошибке, если модуль не может быть загружен
+ *
+ * @public string
+ */
+ public $_module_error = 'Запрашиваемый модуль не может быть загружен.';
+
+ /**
+ * Сообщение об ошибке, если модуль, указанный в шаблоне, не установлен в системе
+ *
+ * @public string
+ */
+ public $_module_not_found = 'Запрашиваемый модуль не найден.';
/**
- * Метод, предназначенный для получения шаблонов
- *
- * @param int $rubric_id идентификатор рубрики
- * @param string $template шаблон
- * @param string $fetched шаблон модуля
- * @return string
+ * Внутренние методы класса
*/
- function _coreDocumentTemplateGet($rubric_id = '', $template = '', $fetched = '')
- {
- global $AVE_DB;
- // Если выводится только содержимое модуля или это новое окно (например страница для печати),
- // просто возвращаем содержимое.
- if (defined('ONLYCONTENT') || (isset ($_REQUEST['pop']) && $_REQUEST['pop'] == 1))
+ /**
+ * Получение основных настроек сисблока
+ *
+ * @param string $param параметр настройки, если не указан - все параметры
+ * @return mixed
+ */
+
+ function _sysBlock($id, $param = '')
{
- $out = '[tag:maincontent]';
- }
- else
- {
- // В противном случае, если в качестве аргумента передан шаблон модуля, возвращаем его.
- if (! empty($fetched))
+ global $AVE_DB;
+
+ static $sys_block = null;
+
+ if ($sys_block === null)
{
- $out = $fetched;
+ $sys_block = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_sysblocks
+ WHERE
+ " . (is_numeric($id) ? 'id' : 'sysblock_alias') . " = '" . $id . "'
+ ")->FetchAssocArray();
+ }
+
+ if ($param == '')
+ return $sys_block;
+
+ return isset($sys_block[$param])
+ ? $sys_block[$param]
+ : null;
+ }
+
+
+ /**
+ * Получение основных настроек сисблока
+ *
+ * @param string $param параметр настройки, если не указан - все параметры
+ * @return mixed
+ */
+
+ function _requestGet($id, $param = '')
+ {
+ global $AVE_DB;
+
+ static $request = null;
+
+ if ($request === null)
+ {
+ $request = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ " . (is_numeric($id) ? 'Id' : 'request_alias') . " = '" . $id . "'
+ ")->FetchAssocArray();
+ }
+
+ if ($param == '')
+ return $request;
+
+ return isset($request[$param])
+ ? $request[$param]
+ : null;
+ }
+
+ /**
+ * Метод, предназначенный для получения шаблонов
+ *
+ * @param int $rubric_id идентификатор рубрики
+ * @param string $template шаблон
+ * @param string $fetched шаблон модуля
+ * @return string
+ */
+ function _coreDocumentTemplateGet($rubric_id = '', $template = '', $fetched = '')
+ {
+ global $AVE_DB;
+
+ // Если выводится только содержимое модуля или это новое окно (например страница для печати),
+ // просто возвращаем содержимое.
+ if (defined('ONLYCONTENT') || (isset ($_REQUEST['pop']) && $_REQUEST['pop'] == 1))
+ {
+ $out = '[tag:maincontent]';
}
else
{
- // В противном случае, если в качестве аргумента передан общий шаблон, возвращаем его
- if (! empty($template))
+ // В противном случае, если в качестве аргумента передан шаблон модуля, возвращаем его.
+ if (! empty($fetched))
{
- $out = $template;
+ $out = $fetched;
}
- else // В противном случае, если аргументы не определены, тогда проверяем
+ else
{
- // Если для текущего документа в свойстве класса $this->curentdoc определен шаблон, тогда возвращаем его
- if (! empty ($this->curentdoc->template_text))
+ // В противном случае, если в качестве аргумента передан общий шаблон, возвращаем его
+ if (! empty($template))
{
- $out = stripslashes($this->curentdoc->template_text);
- unset($this->curentdoc->template_text);
+ $out = $template;
}
- else
+ else // В противном случае, если аргументы не определены, тогда проверяем
{
- // В противном случае, если не указан идентификатор рубрики
- if (empty ($rubric_id))
+ // Если для текущего документа в свойстве класса $this->curentdoc определен шаблон, тогда возвращаем его
+ if (! empty ($this->curentdoc->template_text))
{
- // Получаем id документа из запроса
- $_REQUEST['id'] = (isset ($_REQUEST['id']) && is_numeric($_REQUEST['id']))
- ? $_REQUEST['id']
- : 1;
+ $out = stripslashes($this->curentdoc->template_text);
+ unset($this->curentdoc->template_text);
+ }
+ else
+ {
+ // В противном случае, если не указан идентификатор рубрики
+ if (empty ($rubric_id))
+ {
+ // Получаем id документа из запроса
+ $_REQUEST['id'] = (isset ($_REQUEST['id']) && is_numeric($_REQUEST['id']))
+ ? $_REQUEST['id']
+ : 1;
- // Выполняем запрос к БД на получение id рубрики на основании id документа
- $rubric_id = $AVE_DB->Query("
+ // Выполняем запрос к БД на получение id рубрики на основании id документа
+ $rubric_id = $AVE_DB->Query("
+ SELECT
+ rubric_id
+ FROM
+ " . PREFIX . "_documents
+ WHERE
+ Id = '" . $_REQUEST['id'] . "'
+ LIMIT 1
+ ")->GetCell();
+
+ // Если id рубрики не найден, возвращаем пустую строку
+ if (! $rubric_id)
+ return '';
+ }
+
+ // Выполняем запрос к БД на получение основного шаблона, а также шаблона рубрики
+ $tpl = $AVE_DB->Query("
SELECT
- rubric_id
+ template_text
FROM
- " . PREFIX . "_documents
+ " . PREFIX . "_templates AS tpl
+ LEFT JOIN
+ " . PREFIX . "_rubrics AS rub
+ ON tpl.Id = rubric_template_id
WHERE
- Id = '" . $_REQUEST['id'] . "'
+ rub.Id = '" . $rubric_id . "'
LIMIT 1
")->GetCell();
- // Если id рубрики не найден, возвращаем пустую строку
- if (! $rubric_id)
- return '';
+ // Если запрос выполнился с нулевым результатом, возвращаем пустую строку
+ $out = $tpl
+ ? stripslashes($tpl)
+ : '';
}
-
- // Выполняем запрос к БД на получение основного шаблона, а также шаблона рубрики
- $tpl = $AVE_DB->Query("
- SELECT
- template_text
- FROM
- " . PREFIX . "_templates AS tpl
- LEFT JOIN
- " . PREFIX . "_rubrics AS rub
- ON tpl.Id = rubric_template_id
- WHERE
- rub.Id = '" . $rubric_id . "'
- LIMIT 1
- ")->GetCell();
-
- // Если запрос выполнился с нулевым результатом, возвращаем пустую строку
- $out = $tpl
- ? stripslashes($tpl)
- : '';
}
}
}
+
+ // получаем из шаблона системный тег, определяющий название темы дизайна
+ $match = array();
+
+ preg_match('/\[tag:theme:(\w+)]/', $out, $match);
+
+ define('THEME_FOLDER', empty ($match[1])
+ ? DEFAULT_THEME_FOLDER
+ : $match[1]);
+
+ $out = preg_replace('/\[tag:theme:(.*?)]/', '', $out);
+
+ // Если пришел вызов на активацию языковых файлов
+ $out = preg_replace_callback(
+ '/\[tag:language]/',
+ function ()
+ {
+ global $AVE_Template;
+
+ $lang_file = BASE_DIR . '/templates/' . THEME_FOLDER . '/lang/' . $_SESSION['user_language'] . '.txt';
+
+ $AVE_Template->config_load($lang_file);
+ $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
+ },
+ $out
+ );
+
+ return $out;
}
- // получаем из шаблона системный тег, определяющий название темы дизайна
- $match = array();
-
- preg_match('/\[tag:theme:(\w+)]/', $out, $match);
-
- define('THEME_FOLDER', empty ($match[1])
- ? DEFAULT_THEME_FOLDER
- : $match[1]);
-
- $out = preg_replace('/\[tag:theme:(.*?)]/', '', $out);
-
- // Если пришел вызов на активацию языковых файлов
- $out = preg_replace_callback(
- '/\[tag:language]/',
- function ()
- {
- global $AVE_Template;
-
- $lang_file = BASE_DIR . '/templates/' . THEME_FOLDER . '/lang/' . $_SESSION['user_language'] . '.txt';
-
- $AVE_Template->config_load($lang_file);
- $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
- },
- $out
- );
-
- return $out;
- }
-
- /**
- * Метод, предназначенный для получения шаблона модуля
- *
- * @return string
- */
- function _coreModuleTemplateGet()
- {
- global $AVE_DB;
-
- // Если папка, с запрашиваемым модулем не существует, выполняем редирект
- // на главную страницу и отображаем сообщение с ошибкой
- if (! is_dir(BASE_DIR . '/modules/' . $_REQUEST['module']))
+ /**
+ * Метод, предназначенный для получения шаблона модуля
+ *
+ * @return string
+ */
+ function _coreModuleTemplateGet()
{
- echo ' ';
- $out = $this->_module_not_found;
- }
- // В противном случае
- else
- {
- // Выполняем запрос к БД на получение списка общих шаблонов имеющиюся в системе
- // и шаблоне, который установлен для данного модуля
- // Например, в системе есть шаблоны Template_1 и Template_2, а для модуля установлен Template_3
- $out = $AVE_DB->Query("
- SELECT
- tmpl.template_text
- FROM
- " . PREFIX . "_templates AS tmpl
- LEFT JOIN
- " . PREFIX . "_module AS mdl
- ON tmpl.Id = mdl.ModuleTemplate
- WHERE
- ModuleSysName = '" . $_REQUEST['module'] . "'
- ")->GetCell();
+ global $AVE_DB;
- // Если шаблон, установленный для модуля не найден в системе, принудительно устанавливаем для него
- // первый шаблон (id=1)
- if (empty ($out))
+ // Если папка, с запрашиваемым модулем не существует, выполняем редирект
+ // на главную страницу и отображаем сообщение с ошибкой
+ if (! is_dir(BASE_DIR . '/modules/' . $_REQUEST['module']))
{
+ echo ' ';
+ $out = $this->_module_not_found;
+ }
+ // В противном случае
+ else
+ {
+ // Выполняем запрос к БД на получение списка общих шаблонов имеющиюся в системе
+ // и шаблоне, который установлен для данного модуля
+ // Например, в системе есть шаблоны Template_1 и Template_2, а для модуля установлен Template_3
$out = $AVE_DB->Query("
SELECT
- template_text
+ tmpl.template_text
FROM
- " . PREFIX . "_templates
+ " . PREFIX . "_templates AS tmpl
+ LEFT JOIN
+ " . PREFIX . "_module AS mdl
+ ON tmpl.Id = mdl.ModuleTemplate
WHERE
- Id = '1'
- LIMIT 1
+ ModuleSysName = '" . $_REQUEST['module'] . "'
")->GetCell();
- }
- }
- // Возвращаем информацию о полученном шаблоне
- return stripslashes($out);
- }
- /**
- * Метод, предназначенный для получения прав доступа к документам рубрики
- *
- * @param int $rubrik_id идентификатор рубрики
- */
- function _coreRubricPermissionFetch($rubrik_id = '')
- {
- global $AVE_DB;
-
- unset ($_SESSION[$rubrik_id . '_docread']);
-
- // Если для документа уже получены права доступа, тогда
- if (!empty ($this->curentdoc->rubric_permission))
- {
- // Формируем массив с правами доступа
- $rubric_permissions = explode('|', $this->curentdoc->rubric_permission);
-
- // Циклически обрабатываем сформированный массив и создаем в сессии соответсвующие переменные
- foreach ($rubric_permissions as $rubric_permission)
- {
- if (!empty ($rubric_permission))
+ // Если шаблон, установленный для модуля не найден в системе, принудительно устанавливаем для него
+ // первый шаблон (id=1)
+ if (empty ($out))
{
- $_SESSION[$rubrik_id . '_' . $rubric_permission] = 1;
+ $out = $AVE_DB->Query("
+ SELECT
+ template_text
+ FROM
+ " . PREFIX . "_templates
+ WHERE
+ Id = '1'
+ LIMIT 1
+ ")->GetCell();
}
}
- } // В противном случае
- else
+ // Возвращаем информацию о полученном шаблоне
+ return stripslashes($out);
+ }
+
+ /**
+ * Метод, предназначенный для получения прав доступа к документам рубрики
+ *
+ * @param int $rubrik_id идентификатор рубрики
+ */
+ function _coreRubricPermissionFetch($rubrik_id = '')
{
- // Выполняем запрос к БД на получение списка прав для данного документа
- $sql = $AVE_DB->Query("
- SELECT
- rubric_permission
- FROM
- " . PREFIX . "_rubric_permissions
- WHERE
- rubric_id = '" . $rubrik_id . "'
- AND
- user_group_id = '" . UGROUP . "'
- ");
+ global $AVE_DB;
- // Обрабатываем полученные данные и создаем в сессии соответсвующие переменные
- while ($row = $sql->FetchRow())
+ unset ($_SESSION[$rubrik_id . '_docread']);
+
+ // Если для документа уже получены права доступа, тогда
+ if (!empty ($this->curentdoc->rubric_permission))
{
- $row->rubric_permission = explode('|', $row->rubric_permission);
+ // Формируем массив с правами доступа
+ $rubric_permissions = explode('|', $this->curentdoc->rubric_permission);
- foreach ($row->rubric_permission as $rubric_permission)
+ // Циклически обрабатываем сформированный массив и создаем в сессии соответсвующие переменные
+ foreach ($rubric_permissions as $rubric_permission)
{
- if (! empty($rubric_permission))
+ if (!empty ($rubric_permission))
{
$_SESSION[$rubrik_id . '_' . $rubric_permission] = 1;
}
}
- }
- }
- }
-
- /**
- * Метод, предназначенный для обработки события 404 Not Found, т.е. когда страница не найдена.
- *
- * @return unknown
- */
- function _coreErrorPage404()
- {
- global $AVE_DB;
-
- // Выполняем запрос к БД на проверку существования страницы, которая содержит информацию о том, что
- // запрашиваемая страница не найдена
- $available = $AVE_DB->Query("
- SELECT
- COUNT(*)
- FROM
- " . PREFIX . "_documents
- WHERE
- Id = '" . PAGE_NOT_FOUND_ID . "'
- LIMIT 1
- ")->GetCell();
-
- // Если такая страница в БД существует, выполняем переход на страницу с ошибкой
- if ($available)
- {
- header('Location:' . ABS_PATH . 'index.php?id=' . PAGE_NOT_FOUND_ID);
- }
- // Если не существует, тогда просто выводим текст, определенный в свойстве _doc_not_found
- else
- {
- echo $this->_doc_not_found;
- }
-
- exit;
- }
-
- /**
- * Метод, предназначенный для формирования хэша страницы
- *
- * @return string
- */
- function _get_cache_hash()
- {
- $hash = 'g-' . UGROUP;
- $hash .= 'r-' . RUB_ID;
- $hash .= 'u-' . get_redirect_link();
- $hash .= 't-' . $this->curentdoc->rubric_tmpl_id;
-
- return md5($hash);
- }
-
- /**
- * Метод, предназначенный для проверки существования документа в БД
- *
- * @param int $document_id - id документа
- * @param int $user_group - группа пользователя
- * @return boolean
- */
- function _coreCurrentDocumentFetch($document_id = 1, $user_group = 2)
- {
- global $AVE_DB;
-
- // Выполняем составной запрос к БД на получение информации о запрашиваемом документе
- $this->curentdoc = $AVE_DB->Query("
- SELECT
- doc.*,
- rubric_permission,
- rubric_template,
- rubric_header_template,
- rubric_meta_gen,
- template_text,
- other.template
- FROM
- " . PREFIX . "_documents AS doc
- JOIN
- " . PREFIX . "_rubrics AS rub
- ON rub.Id = doc.rubric_id
- JOIN
- " . PREFIX . "_templates AS tpl
- ON tpl.Id = rubric_template_id
- JOIN
- " . PREFIX . "_rubric_permissions AS prm
- ON doc.rubric_id = prm.rubric_id
- LEFT JOIN
- " . PREFIX . "_rubric_templates AS other
- ON doc.rubric_id = other.rubric_id AND doc.rubric_tmpl_id = other.id
- WHERE
- user_group_id = '" . $user_group . "'
- AND
- doc.Id = '" . $document_id . "'
- LIMIT 1
- ")->FetchRow();
-
- if ($this->curentdoc->rubric_tmpl_id != 0)
- {
- $this->curentdoc->rubric_template = (($this->curentdoc->template != '') ? $this->curentdoc->template : $this->curentdoc->rubric_template);
-
- unset($this->curentdoc->template);
- }
-
- // Возвращаем 1, если документ найден, либо 0 в противном случае
- return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $document_id);
- }
-
- /**
- * Метод, предназначенный для получения содержимого страницы с 404 ошибкой
- *
- *
- * @param int $page_not_found_id
- * @param int $user_group
- * @return int/boolean
- */
- function _corePageNotFoundFetch($page_not_found_id = 2, $user_group = 2)
- {
- global $AVE_DB;
-
- // Выполняем запрос к БД на получение полной информации о странице с 404 ошибкой, включая
- // права доступа, шаблон рубрики и основной шаблон сайта
- $this->curentdoc = $AVE_DB->Query("
- SELECT
- doc.*,
- rubric_permission,
- rubric_template,
- rubric_header_template,
- rubric_meta_gen,
- template_text
- FROM
- " . PREFIX . "_documents AS doc
- JOIN
- " . PREFIX . "_rubrics AS rub
- ON rub.Id = doc.rubric_id
- JOIN
- " . PREFIX . "_templates AS tpl
- ON tpl.Id = rubric_template_id
- JOIN
- " . PREFIX . "_rubric_permissions AS prm
- ON doc.rubric_id = prm.rubric_id
- WHERE
- user_group_id = '" . $user_group . "'
- AND
- doc.Id = '" . $page_not_found_id . "'
- LIMIT 1
- ")->FetchRow();
-
- return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $page_not_found_id);
- }
-
- /**
- * Метод, предназначенный для получения МЕТА-тегов для различных модулей.
- *
- * @return boolean
- */
- function _coreModuleMetatagsFetch()
- {
- global $AVE_DB;
-
- // Если в запросе не пришел параметр module, заврешаем работу
- if (! isset($_REQUEST['module']))
- return false;
-
- $this->curentdoc = $AVE_DB->Query("
- SELECT
- 1 AS Id,
- 0 AS document_published,
- document_meta_robots,
- document_meta_keywords,
- document_meta_description,
- document_title
- FROM
- " . PREFIX . "_documents
- WHERE
- Id = 1
- ")->FetchRow();
-
- return (isset($this->curentdoc->Id) && $this->curentdoc->Id == 1);
- }
-
- /**
- * Метод, предназначенный для определения статуса документа (доступен ли он к публикации).
- *
- * @return int/boolean
- */
- function _coreDocumentIsPublished()
- {
- //Контроль даты: Использовать/Не использовать
- if (get_settings('use_doctime') != 0)
- {
- if (!empty ($this->curentdoc) // документ есть
- && $this->curentdoc->Id != PAGE_NOT_FOUND_ID // документ не сообщение ошибки 404
- && $this->curentdoc->document_deleted == 1 // пометка удаления
- )
- {
- // Если пользователь авторизован в Панели управления или имеет полные права на просмотр документа, тогда
- if (isset ($_SESSION['adminpanel']) || isset ($_SESSION['alles']))
- {
- // Отображаем информационное окно с сообщением, определенным в свойстве _doc_not_published
- display_notice($this->_doc_not_published);
- }
- else // В противном случае фиксируем ошибку
- {
- $this->curentdoc = false;
- }
- }
- }
- else
- {
- if (! empty($this->curentdoc) // документ есть
- && $this->curentdoc->Id != PAGE_NOT_FOUND_ID // документ не сообщение ошибки 404
- && $this->curentdoc->document_deleted == 1 // пометка удаления
- )
- {
- // Если пользователь авторизован в Панели управления или имеет полные права на просмотр документа, тогда
- if (isset ($_SESSION['adminpanel']) || isset ($_SESSION['alles']))
- {
- // Отображаем информационное окно с сообщением, определенным в свойстве _doc_not_published
- display_notice($this->_doc_not_published);
- }
- else // В противном случае фиксируем ошибку
- {
- $this->curentdoc = false;
- }
- }
- }
- return (! empty($this->curentdoc));
- }
-
- /**
- * Метод парсинга тега [tag:(css|js):files]
- * для вывода css/js-файлов в шаблоне через combine.php
- *
- * @param array $tag параметры тега
- * @return string что выводить в шаблоне
- */
- function _parse_combine($tag)
- {
- // тип тега (css|js)
- $type = $tag[1];
- // имена файлов
- $files = explode(',',$tag[2]);
-
- // определяем путь. если указан - то считаем от корня, если нет, то в /[tag:mediapath]/css|js/
- if ($tag[3])
- {
- $path = '/' . trim($tag[3],'/') . '/';
- }
- else
- {
- $path = '/templates/' . THEME_FOLDER . '/' . $type . '/';
- }
-
- // уровень вложенности
- $level = substr_count($path,'/') - 1;
-
- // копируем combine.php, если он поменялся или отсутствует
- $dest_stat = stat(BASE_DIR . $path . 'combine.php');
- $source_stat = stat(BASE_DIR . '/lib/combine/combine.php');
-
- if (! file_exists(BASE_DIR . $path . 'combine.php') || $source_stat[9] > $dest_stat[9])
- {
- @copy(BASE_DIR . '/lib/combine/combine.php', BASE_DIR . $path . 'combine.php');
- }
-
- // удаляем из списка отсутствующие файлы
- foreach($files as $key=>$file)
- {
- if (! file_exists(BASE_DIR . $path . $file))
- unset($files[$key]);
- }
-
- if ($files)
- {
- $combine = $path . 'combine.php?level=' . $level . '&' . $type . '=' . implode(',', $files);
- $combine = @str_replace('//','/',$combine);
- }
-
- return $combine;
- }
-
-/**
- * Внешние методы класса
- */
-
- /**
- * Метод, предназначенный для обработки системных тегов модулей. Здесь подключаются только те файлы модулей,
- * системные теги которых обнаружены в шаблоне при парсинге. Также формирует массив всех установленных модулей
- * в системе, предварительно проверяя их доступность.
- *
- * @param string $template текст шаблона с тегами
- * @return string текст шаблона с обработанными тегами модулей
- */
- function coreModuleTagParse($template)
- {
- global $AVE_DB, $AVE_Template;
-
- $pattern = array(); // Массив системных тегов
- $replace = array(); // Массив функций, на которые будут заменены системные теги
-
- // Если уже имеются данные об установленных модулях
- if (null !== $this->install_modules)
- {
- // Циклически обрабатываем каждый модуль
- foreach ($this->install_modules as $row)
- {
- // Если в запросе пришел вызов модуля или у модуля есть функция вызываемая тегом,
- // который присутствует в шаблоне
- if ((isset($_REQUEST['module']) && $_REQUEST['module'] == $row->ModuleSysName) ||
- (1 == $row->ModuleIsFunction && !empty($row->ModuleAveTag) && 1 == preg_match($row->ModuleAveTag, $template)))
- {
- // Проверяем, существует ли для данного модуля функция. Если да,
- // получаем php код функции.
- if (function_exists($row->ModuleStatus))
- {
- $pattern[] = $row->ModuleAveTag;
- $replace[] = $row->ModulePHPTag;
- }
- else // В противном случае
- {
- // Проверяем, существует ли для данного модуля файл module.php в его персональной директории
- $mod_file = BASE_DIR . '/modules/' . $row->ModuleSysName . '/module.php';
-
- if (is_file($mod_file) && include_once($mod_file))
- {
- // Если файл модуля найден, тогда
- if ($row->ModuleAveTag)
- {
- $pattern[] = $row->ModuleAveTag; // Получаем его системный тег
-
- // Проверяем, существует ли для данного модуля функция. Если да,
- // получаем php код функции, в противном случае формируем сообщение с ошибкой
- $replace[] = function_exists($row->ModuleFunction)
- ? $row->ModulePHPTag
- : ($this->_module_error . ' "' . $row->ModuleName . '"');
- }
- }
- // Если файла module.php не существует, формируем сообщение с ошибкой
- elseif ($row->ModuleAveTag)
- { $pattern[] = $row->ModuleAveTag;
- $replace[] = $this->_module_error . ' "' . $row->ModuleName . '"';
- }
- }
- }
- }
-
- // Выполняем замену систеного тега на php код и возвращаем результат
- return preg_replace($pattern, $replace, $template);
- }
- else // В противном случае, если список модулей пустой
- {
- $this->install_modules = array();
-
- // Выполняем запрос к БД на получение информации о всех модулях, которые установлены в системе
- // (именно установлены, а не просто существуют в виде папок)
- $sql = $AVE_DB->Query("
- SELECT *
- FROM
- " . PREFIX. "_module
- WHERE
- ModuleStatus = '1'
- ");
-
- // Циклически обрабатываем полученные данные
- while ($row = $sql->FetchRow())
- {
- // Если в запросе пришел параметр module и для данного названия модуля существует
- // директория или данный модуль имеет функцию и его системный тег указан в каком-либо шаблоне, тогда
- if ((isset($_REQUEST['module']) && $_REQUEST['module'] == $row->ModuleSysName) ||
- (1 == $row->ModuleIsFunction && !empty($row->ModuleAveTag) && 1 == preg_match($row->ModuleAveTag, $template)))
- {
- // Проверяем, существует ли для данного модуля файл module.php в его персональной директории
- $mod_file = BASE_DIR . '/modules/' . $row->ModuleSysName . '/module.php';
-
- if (is_file($mod_file) && include_once($mod_file))
- { // Если файл модуля найден, тогда
- if (! empty($row->ModuleAveTag))
- {
- $pattern[] = $row->ModuleAveTag; // Получаем его системный тег
-
- // Проверяем, существует ли для данного модуля функция. Если да,
- // получаем php код функции, в противном случае формируем сообщение с ошибкой
- $replace[] = function_exists($row->ModuleFunction)
- ? $row->ModulePHPTag
- : ($this->_module_error . ' "' . $row->ModuleName . '"');
- }
- // Сохряняем информацию о модуле
- $this->install_modules[$row->ModuleSysName] = $row;
- }
- elseif ($row->ModuleAveTag) // Если файла module.php не существует, формируем сообщение с ошибкой
- {
- $pattern[] = $row->ModuleAveTag;
- $replace[] = $this->_module_error . ' "' . $row->ModuleName . '"';
- }
- }
- else
- { // Если у модуля нет функции или тег модуля не используется - просто помещаем в массив информацию о модуле
- $this->install_modules[$row->ModuleSysName] = $row;
- }
- }
- // Выполняем замену систеного тега на php код и возвращаем результат
- return preg_replace($pattern, $replace, $template);
- }
- }
-
- /**
- * Метод, предназанченный для сборки всей страницы в единое целое.
- *
- * @param int $id идентификатор документа
- * @param int $rub_id идентификатор рубрики
- */
- function coreSiteFetch($id, $rub_id = '')
- {
- global $AVE_DB;
-
- $main_content = '';
-
- // Если происходит вызов модуля, получаем соответствующие мета-теги и получаем шаблон модуля
- if (isset($_REQUEST['module']) && ! empty($_REQUEST['module']))
- {
- $out = $this->_coreModuleMetatagsFetch();
- $out = $this->_coreDocumentTemplateGet('', '', $this->_coreModuleTemplateGet());
- }
- elseif (isset($_REQUEST['sysblock']) && ! empty($_REQUEST['sysblock']))
- {
- if (! is_numeric($_REQUEST['sysblock']) && preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $_REQUEST['sysblock']) !== 1)
- {
- header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true);
- exit;
- }
-
- // проверяем разрешение на внешнее обращение
- if (! $this->_sysBlock($_REQUEST['sysblock'], 'sysblock_external'))
- {
- header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true);
- exit;
- }
-
- // проверяем разрешение на обращение только по Ajax
- if ($this->_sysBlock($_REQUEST['sysblock'], 'sysblock_ajax'))
- {
- if (isAjax())
- {
- $out = parse_sysblock($_REQUEST['sysblock']);
- }
- else
- {
- $this->_coreErrorPage404();
- }
- }
+ } // В противном случае
else
{
- $out = parse_sysblock($_REQUEST['sysblock']);
- }
- }
- elseif (isset($_REQUEST['request']) && ! empty($_REQUEST['request']))
- {
- if (! is_numeric($_REQUEST['request']) && preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $_REQUEST['request']) !== 1)
- {
- $this->_coreErrorPage404();
- }
+ // Выполняем запрос к БД на получение списка прав для данного документа
+ $sql = $AVE_DB->Query("
+ SELECT
+ rubric_permission
+ FROM
+ " . PREFIX . "_rubric_permissions
+ WHERE
+ rubric_id = '" . $rubrik_id . "'
+ AND
+ user_group_id = '" . UGROUP . "'
+ ");
- // Определяем рубрику
- define('RUB_ID', ! empty ($rub_id)
- ? $rub_id
- : $this->curentdoc->rubric_id);
-
- // проверяем разрешение на внешнее обращение
- if (! $this->_requestGet($_REQUEST['request'], 'request_external'))
- {
- $this->_coreErrorPage404();
- }
-
- // проверяем разрешение на обращение только по Ajax
- if ($this->_requestGet($_REQUEST['request'], 'request_ajax'))
- {
- if (isAjax())
+ // Обрабатываем полученные данные и создаем в сессии соответсвующие переменные
+ while ($row = $sql->FetchRow())
{
- $out = request_parse($_REQUEST['request']);
- }
- else
- {
- $this->_coreErrorPage404();
- }
- }
- else
- {
- $out = request_parse($_REQUEST['request']);
- }
- }
- // В противном случае начинаем вывод документа
- else
- {
- if (! isset($this->curentdoc->Id) && ! $this->_coreCurrentDocumentFetch($id, UGROUP))
- {
- // Определяем документ с 404 ошибкой в случае, если документ не найден
- if ($this->_corePageNotFoundFetch(PAGE_NOT_FOUND_ID, UGROUP))
- {
- $_REQUEST['id'] = $_GET['id'] = $id = PAGE_NOT_FOUND_ID;
- }
- }
+ $row->rubric_permission = explode('|', $row->rubric_permission);
- // проверяем параметры публикации документа
- if (! $this->_coreDocumentIsPublished())
- {
- $this->_coreErrorPage404();
- }
-
- // Определяем права доступа к документам рубрики
- define('RUB_ID', ! empty ($rub_id)
- ? $rub_id
- : $this->curentdoc->rubric_id);
-
- $this->_coreRubricPermissionFetch(RUB_ID);
-
- // получаем шаблон
- $out = $this->_coreDocumentTemplateGet(RUB_ID);
-
- // Выполняем Код рубрики
- ob_start();
- eval('?>' . $this->curentdoc->rubric_start_code . '');
- ob_end_clean();
-
- if (! ((isset ($_SESSION[RUB_ID . '_docread']) && $_SESSION[RUB_ID . '_docread'] == 1)
- || (isset ($_SESSION[RUB_ID . '_alles']) && $_SESSION[RUB_ID . '_alles'] == 1)) )
- { // читать запрещено - извлекаем ругательство и отдаём вместо контента
- $main_content = get_settings('message_forbidden');
- }
- else
- {
- if (isset ($_REQUEST['print']) && $_REQUEST['print'] == 1)
- { // увеличиваем счетчик версий для печати
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_documents
- SET
- document_count_print = document_count_print + 1
- WHERE
- Id = '" . $id . "'
- ");
- }
- else
- {
- if (! isset ($_SESSION['doc_view'][$id]))
- { // увеличиваем счетчик просмотров (1 раз в пределах сессии)
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_documents
- SET
- document_count_view = document_count_view + 1
- WHERE
- Id = '" . $id . "'
- ");
-
- $_SESSION['doc_view'][$id] = time();
- }
-
- $curdate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
-
- if (!isset ($_SESSION['doc_view_dayly['.$curdate.'][' . $id . ']']))
+ foreach ($row->rubric_permission as $rubric_permission)
{
- // и подневный счетчик просмотров тоже увеличиваем
- $curdate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
-
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_view_count
- SET
- count = count + 1
- WHERE
- document_id = '" . $id . "' AND
- day_id = '".$curdate."'
- ");
-
- if (! $AVE_DB->getAffectedRows())
+ if (! empty($rubric_permission))
{
- $AVE_DB->Query("
- INSERT INTO " . PREFIX . "_view_count (
- document_id,
- day_id,
- count
- )
- VALUES (
- '" . $id . "', '".$curdate."', '1'
- )
- ");
- }
-
- $_SESSION['doc_view_dayly['.$curdate.'][' . $id . ']'] = time();
- }
- }
-
- if (CACHE_DOC_TPL && empty ($_POST) && !(isset ($_SESSION['user_adminmode']) && $_SESSION['user_adminmode'] == 1))
- {
- // кэширование разрешено
- // извлекаем скомпилированный шаблон документа из кэша
- // если там пусто, пробуем достать из бд
-
- $cache_id = (int)$this->curentdoc->Id;
- $cache_id = 'compiled/' . (floor($cache_id / 1000)) . '/' . $cache_id;
-
- $cache_file = $this->_get_cache_hash();
-
- $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
- ? trim($cache_id) . '/'
- : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
-
- if (CACHE_DOC_FILE && file_exists($cache_dir . $cache_file))
- {
- $main_content = file_get_contents($cache_dir . $cache_file);
- }
- else
- {
- $main_content = $AVE_DB->Query("
- SELECT
- compiled
- FROM
- " . PREFIX . "_rubric_template_cache
- WHERE
- hash = '" . $cache_file . "'
- LIMIT 1
- ")->GetCell();
- }
-
- unset($cache_dir, $cache_file, $cache_id);
- }
- else
- { // кэширование запрещено
- $main_content = false;
- }
-
- // Собираем контент
- // если в кеше нет контента, то
- if (empty($main_content))
- {
- // кэш пустой или отключен, извлекаем и компилируем шаблон
- if (! empty ($this->curentdoc->rubric_template))
- {
- $rubTmpl = $this->curentdoc->rubric_template;
- }
- else
- {
- // если документу задан другой шаблон из данной рубрики, то берем его
- if ($this->curentdoc->rubric_tmpl_id != 0)
- {
- $rubTmpl = $AVE_DB->Query("
- SELECT
- template
- FROM
- " . PREFIX . "_rubric_templates
- WHERE
- id = '" . $this->curentdoc->rubric_tmpl_id . "'
- AND
- rubric_id = '" . RUB_ID . "'
- LIMIT 1
- ")->GetCell();
- }
- else // иначе берем стандартный шаблон рубрики
- {
- $rubTmpl = $AVE_DB->Query("
- SELECT
- rubric_template
- FROM
- " . PREFIX . "_rubrics
- WHERE
- Id = '" . RUB_ID . "'
- LIMIT 1
- ")->GetCell();
- }
- }
-
- $rubTmpl = trim($rubTmpl);
-
- // Собираем шаблон рубрики
- if (empty($rubTmpl))
- {
- // Если не задан шаблон рубрики, выводим сообщение
- $main_content = $this->_rubric_template_empty;
- }
- else
- {
- // Проверяем теги полей в шаблоне рубрики на условие != ''
- $main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.'?'.'>', $rubTmpl);
- $main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.'?'.'>', $main_content);
- $main_content = str_replace('[tag:if:else]', '', $main_content);
- $main_content = str_replace('[tag:/if]', '', $main_content);
-
- // Парсим теги полей документа в шаблоне рубрики
- $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', 'return_element', $main_content);
- $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]/', 'document_get_field', $main_content);
- $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', 'return_element', $main_content);
- $main_content = preg_replace_callback('/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/', 'watermarks', $main_content);
- $main_content = preg_replace_callback('/\[tag:([r|c|f|t|s]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $main_content);
-
- // Возвращаем поле из БД документа
- $main_content = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- return isset($this->curentdoc->{$match[1]})
- ? $this->curentdoc->{$match[1]}
- : null;
- },
- $main_content
- );
-
- // Если пришел вызов на активацию языковых файлов
- $main_content = preg_replace_callback(
- '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- global $AVE_Template;
-
- return $AVE_Template->get_config_vars($match[1]);
- },
- $main_content
- );
-
- // Удаляем ошибочные теги полей документа в шаблоне рубрики
- $main_content = preg_replace('/\[tag:watermark:\w*\]/', '', $main_content);
- $main_content = preg_replace('/\[tag:fld:\d*\]/', '', $main_content);
- $main_content = preg_replace('/\[tag:doc:\w*\]/', '', $main_content);
- $main_content = preg_replace('/\[tag:langfile:\w*\]/', '', $main_content);
-
- if (CACHE_DOC_TPL && empty ($_POST) && !(isset ($_SESSION['user_adminmode']) && $_SESSION['user_adminmode'] == 1))
- {
- $cache_id = (int)$this->curentdoc->Id;
- $cache_id = 'compiled/' . (floor($cache_id / 1000)) . '/' . $cache_id;
-
- $cache_file = $this->_get_cache_hash();
-
- $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
- ? trim($cache_id) . '/'
- : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
-
- // кэширование разрешено
- // сохраняем скомпилированный шаблон в кэш
- if (CACHE_DOC_FILE)
- {
- if(! is_dir($cache_dir))
- mkdir($cache_dir, 0777, true);
-
- file_put_contents($cache_dir . $cache_file, $main_content);
- }
-
- // кэширование разрешено
- // сохраняем скомпилированный шаблон в кэш
- $AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_template_cache
- SET
- hash = '" . $cache_file . "',
- rub_id = '" . RUB_ID . "',
- rub_tmpl_id = '" . $this->curentdoc->rubric_tmpl_id . "',
- grp_id = '" . UGROUP . "',
- doc_id = '" . $id . "',
- compiled = '" . addslashes($main_content) . "'
- ");
-
- unset($cache_id, $cache_file, $cache_dir);
+ $_SESSION[$rubrik_id . '_' . $rubric_permission] = 1;
}
}
}
-
- // парсим теги в шаблоне рубрики
- $main_content = preg_replace_callback(
- '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
- create_function('$m','return translate_date(date($m[1], '.$this->curentdoc->document_published.'));
- '),
- $main_content
- );
-
- $main_content = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $this->curentdoc->document_published)), $main_content);
- $main_content = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $this->curentdoc->document_published)), $main_content);
- $main_content = str_replace('[tag:humandate]', human_date($this->curentdoc->document_published), $main_content);
- $main_content = str_replace('[tag:docauthorid]', $this->curentdoc->document_author_id, $main_content);
- if (preg_match('[tag:docauthor]', $main_content)){
- $main_content = str_replace('[tag:docauthor]', get_username_by_id($this->curentdoc->document_author_id), $main_content);
- }
}
-
-
-
- $out = str_replace('[tag:maincontent]', $main_content, $out);
-
- unset($this->curentdoc->rubric_template, $this->curentdoc->template);
- }
- // Конец вывода документа
-
- //Работа с условиями
- /*
- $out = preg_replace('/\[tag:if_exp:?(.*)\]/u', '', $out);
- $out = str_replace('[tag:if_exp_else]', '', $out);
- $out = str_replace('[tag:/if_exp]', '', $out);
-
- */
-
- // Тут мы вводим в хеадер иньекцию скриптов.
- if (defined('RUB_ID'))
- {
- $rubheader = $this->curentdoc->rubric_header_template;
- $out = str_replace('[tag:rubheader]', $rubheader.'[tag:rubheader]', $out);
-
- unset($rubheader);
}
- // Парсим поля запроса
- $out = preg_replace_callback(
- '/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/',
- create_function(
- '$m',
- 'return request_get_document_field($m[1], ' . $id . ', $m[2], ' . (defined('RUB_ID') ? RUB_ID : 0) . ');'
- ),
- $out
- );
-
- // Удаляем ошибочные теги полей документа в шаблоне рубрики
- $out = preg_replace('/\[tag:rfld:\d*\]/', '', $out);
-
- // Если в запросе пришел параметр print, т.е. страница для печати,
- // парсим контент, который обрамлен тегами только для печати
- if (isset ($_REQUEST['print']) && $_REQUEST['print'] == 1)
+ /**
+ * Метод, предназначенный для обработки события 404 Not Found, т.е. когда страница не найдена.
+ *
+ * @return unknown
+ */
+ function _coreErrorPage404()
{
- $out = str_replace(array('[tag:if_print]', '[/tag:if_print]'), '', $out);
- $out = preg_replace('/\[tag:if_notprint\](.*?)\[\/tag:if_notprint\]/si', '', $out);
- }
- else
- {
- // В противном случае наоборот, парсим только тот контент, который предназначен НЕ для печати
- $out = preg_replace('/\[tag:if_print\](.*?)\[\/tag:if_print\]/si', '', $out);
- $out = str_replace(array('[tag:if_notprint]', '[/tag:if_notprint]'), '', $out);
- }
+ global $AVE_DB;
- // Парсим теги визуальных блоков
- $out = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $out);
-
- // Парсим теги системных блоков
- $out = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $out);
-
- // Парсим теги модулей
- $out = $this->coreModuleTagParse($out);
-
- // Если в запросе пришел параметр module, т.е. вызов модуля,
- // проверяем установлен и активен ли модуль
- if ( isset($_REQUEST['module'])
- && ! (isset($this->install_modules[$_REQUEST['module']])
- && '1' == $this->install_modules[$_REQUEST['module']]->ModuleStatus) )
- {
- // Выводим сообщение о том что такого модуля нет
- display_notice($this->_module_error);
- }
-
- // Парсим теги системы внутренних запросов
- $out = preg_replace_callback('/\[tag:request:([A-Za-z0-9-_]{1,20}+)\]/', 'request_parse', $out);
-
- // Парсим теги навигации
- $out = preg_replace_callback('/\[tag:navigation:([A-Za-z0-9-_]{1,20}+):?([0-9,]*)\]/', 'parse_navigation', $out);
-
- // Парсим теги скрытого текста
- $out = parse_hide($out);
-
- // Если в запросе пришел параметр sysblock, т.е. вызов сис блока,
- // парсим контент
- if (isset($_REQUEST['sysblock']) && $_REQUEST['sysblock'] != '')
- {
- $search = array(
- '[tag:mediapath]',
- '[tag:path]',
- '[tag:sitename]',
- '[tag:home]',
- '[tag:docid]',
- '[tag:docparent]'
- );
-
- $replace = array(
- ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
- ABS_PATH,
- htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
- get_home_link(),
- (isset ($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
- (isset ($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
- );
- }
- // Если в запросе пришел параметр request, т.е. вызов запроса,
- // парсим контент
- elseif (isset($_REQUEST['request']) && $_REQUEST['request'] != '')
- {
- $search = array(
- '[tag:mediapath]',
- '[tag:path]',
- '[tag:sitename]',
- '[tag:home]',
- '[tag:docid]',
- '[tag:docparent]'
- );
-
- $replace = array(
- ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
- ABS_PATH,
- htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
- get_home_link(),
- (isset ($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
- (isset ($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
- );
- }
- else
- {
- // В противном случае
- // парсим остальные теги основного шаблона
- $search = array(
- '[tag:mediapath]',
- '[tag:path]',
- '[tag:sitename]',
- '[tag:alias]',
- '[tag:domain]',
- '[tag:home]',
- '[tag:robots]',
- '[tag:canonical]',
- '[tag:docid]',
- '[tag:docparent]'
- );
-
- $replace = array(
- ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
- ABS_PATH,
- htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
- (isset($_REQUEST['id'])) ? $this->curentdoc->document_alias : '',
- getSiteUrl(),
- get_home_link(),
- (isset($this->curentdoc->document_meta_robots) ? $this->curentdoc->document_meta_robots : ''),
- canonical(ABS_PATH . $this->curentdoc->document_alias),
- (isset($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
- (isset($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
- );
- }
-
- if (defined('MODULE_CONTENT'))
- {
- // парсинг тегов при выводе из модуля
- $search[] = '[tag:maincontent]';
- $replace[] = MODULE_CONTENT;
- $search[] = '[tag:title]';
- $replace[] = htmlspecialchars(defined('MODULE_TITLE') ? MODULE_TITLE : '', ENT_QUOTES);
- $search[] = '[tag:description]';
- $replace[] = htmlspecialchars(defined('MODULE_DESCRIPTION') ? MODULE_DESCRIPTION : '', ENT_QUOTES);
- $search[] = '[tag:keywords]';
- $replace[] = htmlspecialchars(defined('MODULE_KEYWORDS') ? MODULE_KEYWORDS : '', ENT_QUOTES);
- }
- elseif (isset($_REQUEST['sysblock']))
- {
- // Убираем пустые теги в сис блоке
- $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
- $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
- }
- elseif (isset($_REQUEST['request']))
- {
- // Убираем пустые теги в сис блоке
- $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
- $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
- }
- else
- {
- if ($this->curentdoc->rubric_meta_gen)
- {
- // Генерируем keywords, description на основе
- // данных документа, если позволяет рубрика
- require_once(dirname(__FILE__).'/class.meta.php');
- $meta = new Meta();
- $res = $meta->generateMeta($main_content);
- }
-
- // Убираем пустые теги
- $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
- $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
-
- // Парсим keywords, description, title
- $search[] = '[tag:keywords]';
- $replace[] = stripslashes(htmlspecialchars((! empty ($this->curentdoc->rubric_meta_gen) ? $res['keywords'] : $this->curentdoc->document_meta_keywords), ENT_QUOTES));
- $search[] = '[tag:description]';
- $replace[] = stripslashes(htmlspecialchars((! empty ($this->curentdoc->rubric_meta_gen) ? $res['description'] : $this->curentdoc->document_meta_description), ENT_QUOTES));
- $search[] = '[tag:title]';
- $replace[] = stripslashes(htmlspecialchars_decode(pretty_chars($this->curentdoc->document_title)));
- }
-
- // Возвращаем поле из БД документа
- $out = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- return isset($this->curentdoc->{$match[1]})
- ? $this->curentdoc->{$match[1]}
- : null;
- },
- $out
- );
-
- // Если пришел вызов на активацию языковых файлов
- $out = preg_replace_callback(
- '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- global $AVE_Template;
-
- return $AVE_Template->get_config_vars($match[1]);
- },
- $out
- );
-
- // Убираем пустые теги
- $out = preg_replace('/\[tag:doc:\d*\]/', '', $out);
- $out = preg_replace('/\[tag:langfile:\d*\]/', '', $out);
-
- // Убираем дубликат
- $search[] = '[tag:maincontent]';
- $replace[] = '';
-
- // Парсим линк на версию для печати
- $search[] = '[tag:printlink]';
- $replace[] = get_print_link();
-
- // Парсим тег версии системы
- $search[] = '[tag:version]';
- $replace[] = APP_NAME . ' v' . APP_VERSION ;
-
- // Парсим тег кол-ва просмотра данного документа
- $search[] = '[tag:docviews]';
- $replace[] = isset ($this->curentdoc->document_count_view) ? $this->curentdoc->document_count_view : '';
-
- // Парсим тизер документа
- $out = preg_replace_callback(
- '/\[tag:teaser:(\d+)(|:\[(.*?)\])\]/',
- create_function(
- '$m',
- 'return showteaser($m[1], $m[2]);'
- ),
- $out
- );
-
- // Парсим аватар автора документа
- if (defined('RUB_ID'))
- $out = preg_replace_callback(
- '/\[tag:docauthoravatar:(\d+)\]/',
- create_function(
- '$m',
- 'return getAvatar('.intval($this->curentdoc->document_author_id).', $m[1]);'
- ),
- $out
- );
-
- // Парсим теги языковых условий
- if (defined('RUB_ID'))
- {
- $out = preg_replace('/\[tag:lang:([a-zA-Z0-9-_]+)\]/', 'curentdoc->document_lang=="$1") { ?>', $out);
- }
- else
- {
- $out = preg_replace('/\[tag:lang:([a-zA-Z0-9-_]+)\]/', '', $out);
- }
-
- $out = str_replace('[tag:/lang]', '', $out);
-
- // Парсим хлебные крошки
- if (preg_match('/\[tag:breadcrumb]/u', $out))
- {
- $out = preg_replace_callback('/\[tag:breadcrumb\]/', 'get_breadcrumb', $out);
- }
-
- // Парсим остальные теги основного шаблона
- $out = str_replace($search, $replace, $out);
- unset ($search, $replace); //Убираем данные
-
- // Парсим теги для combine.php
- $out = preg_replace_callback('/\[tag:(css|js):([^ :\/]+):?(\S+)*\]/', array($this, '_parse_combine'), $out);
-
- // ЧПУ
- $out = str_ireplace('"//"','"/"', str_ireplace('///','/', rewrite_link($out)));
-
- unset($main_content);
-
- // Выводим собранный документ
- echo $out;
- }
-
- /**
- * Метод, предназначенный для формирования ЧПУ, а также для поиска документа и разбора
- * дополнительных параметров в URL
- *
- * @param string $get_url Строка символов
- *
- */
- function coreUrlParse($get_url = '')
- {
- global $AVE_DB;
-
- // Если нужны параметры GET, можно отключить
- $get_url = (strpos($get_url, ABS_PATH . '?') === 0
- ? ''
- : $get_url);
-
- if (substr($get_url, 0, strlen(ABS_PATH.'index.php')) != ABS_PATH . 'index.php' && strpos($get_url, '?') !== false)
- $get_url = substr($get_url, 0, strpos($get_url,'?'));
-
- $get_url = rawurldecode($get_url);
- $get_url = mb_substr($get_url, strlen(ABS_PATH));
-
- // Сохранение старого урла для првоерки использования суффикса
- $test_url = $get_url;
-
- if (mb_substr($get_url, - strlen(URL_SUFF)) == URL_SUFF)
- {
- $get_url = mb_substr($get_url, 0, - strlen(URL_SUFF));
- }
-
- // Разбиваем строку параметров на отдельные части
- $get_url = explode('/', $get_url);
-
- if (isset ($get_url['index']))
- {
- unset ($get_url['index']);
- }
-
- if (isset ($get_url['print']))
- {
- $_GET['print'] = $_REQUEST['print'] = 1;
- unset ($get_url['print']);
- }
-
- // Определяем, используется ли у нас разделение документа по страницам
- $pages = preg_grep('/^(a|art)?page-\d+$/i', $get_url);
-
- if (! empty ($pages))
- {
- $get_url = implode('/', array_diff($get_url, $pages));
- $pages = implode('/', $pages);
-
- preg_replace_callback(
- '/(page|apage|artpage)-(\d+)/i',
- create_function(
- '$matches',
- '$_GET[$matches[1]] = $matches[2]; $_REQUEST[$matches[1]] = $matches[2];'
- ),
- $pages
- );
- }
- // В противном случае формируем окончательную ссылку для документа
- else
- {
- $get_url = implode('/', $get_url);
- }
-
- //-- Проверяем есть ли данный URL в таблице алиасов модулей
- $sql = "
- SELECT
- module_name,
- module_action,
- module_link
- FROM
- " . PREFIX . "_modules_aliases
- WHERE
- module_url = '" . str_ireplace("'", "\'", $get_url) . "'
- ";
-
- $query = $AVE_DB->Query($sql)->FetchRow();
-
- if ($query)
- {
- //-- Передаем глобальные перемененные
- $_GET['module'] = $_REQUEST['module'] = $query->module_name;
- $_GET['action'] = $_REQUEST['action'] = $query->module_action;
-
- $get_url = ABS_PATH . $query->module_link;
- }
-
- // проверка на наличие id в запросе
- if(! empty($_REQUEST['id']))
- {
- $get_url = $AVE_DB->Query("
+ // Выполняем запрос к БД на проверку существования страницы, которая содержит информацию о том, что
+ // запрашиваемая страница не найдена
+ $available = $AVE_DB->Query("
SELECT
- document_alias
+ COUNT(*)
FROM
" . PREFIX . "_documents
WHERE
- Id = '" . (int)$_REQUEST['id'] . "'
+ Id = '" . PAGE_NOT_FOUND_ID . "'
+ LIMIT 1
")->GetCell();
+
+ // Если такая страница в БД существует, выполняем переход на страницу с ошибкой
+ if ($available)
+ {
+ header('Location:' . ABS_PATH . 'index.php?id=' . PAGE_NOT_FOUND_ID);
+ }
+ // Если не существует, тогда просто выводим текст, определенный в свойстве _doc_not_found
+ else
+ {
+ echo $this->_doc_not_found;
+ }
+
+ exit;
}
- // Выполняем запрос к БД на получение всей необходимой
- // информации о документе
- // Экранируем поступающий URL
- $get_url = $AVE_DB->EscStr($get_url);
-
- // Забираем нужные данные
- $sql = $AVE_DB->Query("
- SELECT
- doc.*,
- rubric_permission,
- rubric_template,
- rubric_meta_gen,
- rub.rubric_header_template,
- rub.rubric_start_code,
- template_text,
- other.template
- FROM
- " . PREFIX . "_documents AS doc
- JOIN
- " . PREFIX . "_rubrics AS rub
- ON rub.Id = doc.rubric_id
- JOIN
- " . PREFIX . "_templates AS tpl
- ON tpl.Id = rubric_template_id
- JOIN
- " . PREFIX . "_rubric_permissions AS prm
- ON doc.rubric_id = prm.rubric_id
- LEFT JOIN
- " . PREFIX . "_rubric_templates AS other
- ON doc.rubric_id = other.rubric_id AND doc.rubric_tmpl_id = other.id
- WHERE
- user_group_id = '" . UGROUP . "'
- AND
- " . (! empty ($get_url)
- ? "document_alias = '" . str_ireplace("'", "\'", $get_url) . "'"
- : (! empty($_REQUEST['id'])
- ? "doc.Id =" . intval($_REQUEST['id'])
- :"doc.Id = 1")) . "
- LIMIT 1
- ");
-
- if ($this->curentdoc = $sql->FetchRow())
+ /**
+ * Метод, предназначенный для формирования хэша страницы
+ *
+ * @return string
+ */
+ function _get_cache_hash()
{
+ $hash = 'g-' . UGROUP;
+ $hash .= 'r-' . RUB_ID;
+ $hash .= 'u-' . get_redirect_link();
+ $hash .= 't-' . $this->curentdoc->rubric_tmpl_id;
+
+ return md5($hash);
+ }
+
+ /**
+ * Метод, предназначенный для проверки существования документа в БД
+ *
+ * @param int $document_id - id документа
+ * @param int $user_group - группа пользователя
+ * @return boolean
+ */
+ function _coreCurrentDocumentFetch($document_id = 1, $user_group = 2)
+ {
+ global $AVE_DB;
+
+ // Выполняем составной запрос к БД на получение информации о запрашиваемом документе
+ $this->curentdoc = $AVE_DB->Query("
+ SELECT
+ doc.*,
+ rubric_permission,
+ rubric_template,
+ rubric_header_template,
+ rubric_footer_template,
+ rubric_meta_gen,
+ template_text,
+ other.template
+ FROM
+ " . PREFIX . "_documents AS doc
+ JOIN
+ " . PREFIX . "_rubrics AS rub
+ ON rub.Id = doc.rubric_id
+ JOIN
+ " . PREFIX . "_templates AS tpl
+ ON tpl.Id = rubric_template_id
+ JOIN
+ " . PREFIX . "_rubric_permissions AS prm
+ ON doc.rubric_id = prm.rubric_id
+ LEFT JOIN
+ " . PREFIX . "_rubric_templates AS other
+ ON doc.rubric_id = other.rubric_id AND doc.rubric_tmpl_id = other.id
+ WHERE
+ user_group_id = '" . $user_group . "'
+ AND
+ doc.Id = '" . $document_id . "'
+ LIMIT 1
+ ")->FetchRow();
+
if ($this->curentdoc->rubric_tmpl_id != 0)
{
$this->curentdoc->rubric_template = (($this->curentdoc->template != '')
@@ -1608,62 +470,1205 @@ class AVE_Core
unset($this->curentdoc->template);
}
- // Глобальные переменные
- $_GET['id'] = $_REQUEST['id'] = $this->curentdoc->Id;
- $_GET['doc'] = $_REQUEST['doc'] = $this->curentdoc->document_alias;
+ // Возвращаем 1, если документ найден, либо 0 в противном случае
+ return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $document_id);
+ }
- // Назначаем язык пользователю, в завивисомтси от языка документа
- if ($this->curentdoc->Id != PAGE_NOT_FOUND_ID OR $this->curentdoc->document_lang == '--')
- $_SESSION['user_language'] = $this->curentdoc->document_lang;
+ /**
+ * Метод, предназначенный для получения содержимого страницы с 404 ошибкой
+ *
+ *
+ * @param int $page_not_found_id
+ * @param int $user_group
+ * @return int/boolean
+ */
+ function _corePageNotFoundFetch($page_not_found_id = 2, $user_group = 2)
+ {
+ global $AVE_DB;
- // Перенаправление на адреса с суффиксом
- if (
- $test_url !== $get_url . URL_SUFF
- && ! $pages && $test_url
- && ! $_REQUEST['print']
- && ! $_REQUEST['module']
- && ! $_REQUEST['tag']
- && REWRITE_MODE
- )
+ // Выполняем запрос к БД на получение полной информации о странице с 404 ошибкой, включая
+ // права доступа, шаблон рубрики и основной шаблон сайта
+ $this->curentdoc = $AVE_DB->Query("
+ SELECT
+ doc.*,
+ rubric_permission,
+ rubric_template,
+ rubric_header_template,
+ rubric_footer_template,
+ rubric_meta_gen,
+ template_text
+ FROM
+ " . PREFIX . "_documents AS doc
+ JOIN
+ " . PREFIX . "_rubrics AS rub
+ ON rub.Id = doc.rubric_id
+ JOIN
+ " . PREFIX . "_templates AS tpl
+ ON tpl.Id = rubric_template_id
+ JOIN
+ " . PREFIX . "_rubric_permissions AS prm
+ ON doc.rubric_id = prm.rubric_id
+ WHERE
+ user_group_id = '" . $user_group . "'
+ AND
+ doc.Id = '" . $page_not_found_id . "'
+ LIMIT 1
+ ")->FetchRow();
+
+ return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $page_not_found_id);
+ }
+
+ /**
+ * Метод, предназначенный для получения МЕТА-тегов для различных модулей.
+ *
+ * @return boolean
+ */
+ function _coreModuleMetatagsFetch()
+ {
+ global $AVE_DB;
+
+ // Если в запросе не пришел параметр module, заврешаем работу
+ if (! isset($_REQUEST['module']))
+ return false;
+
+ $this->curentdoc = $AVE_DB->Query("
+ SELECT
+ 1 AS Id,
+ 0 AS document_published,
+ document_meta_robots,
+ document_meta_keywords,
+ document_meta_description,
+ document_title
+ FROM
+ " . PREFIX . "_documents
+ WHERE
+ Id = 1
+ ")->FetchRow();
+
+ return (isset($this->curentdoc->Id) && $this->curentdoc->Id == 1);
+ }
+
+ /**
+ * Метод, предназначенный для определения статуса документа (доступен ли он к публикации).
+ *
+ * @return int/boolean
+ */
+ function _coreDocumentIsPublished()
+ {
+ //Контроль даты: Использовать/Не использовать
+ if (get_settings('use_doctime') != 0)
{
- header('HTTP/1.1 301 Moved Permanently');
- if ($this->curentdoc->Id == 1)
+ if (!empty ($this->curentdoc) // документ есть
+ && $this->curentdoc->Id != PAGE_NOT_FOUND_ID // документ не сообщение ошибки 404
+ && $this->curentdoc->document_deleted == 1 // пометка удаления
+ )
{
- header('Location:' . ABS_PATH);
- exit();
+ // Если пользователь авторизован в Панели управления или имеет полные права на просмотр документа, тогда
+ if (isset ($_SESSION['adminpanel']) || isset ($_SESSION['alles']))
+ {
+ // Отображаем информационное окно с сообщением, определенным в свойстве _doc_not_published
+ display_notice($this->_doc_not_published);
+ }
+ else // В противном случае фиксируем ошибку
+ {
+ $this->curentdoc = false;
+ }
+ }
+ }
+ else
+ {
+ if (! empty($this->curentdoc) // документ есть
+ && $this->curentdoc->Id != PAGE_NOT_FOUND_ID // документ не сообщение ошибки 404
+ && $this->curentdoc->document_deleted == 1 // пометка удаления
+ )
+ {
+ // Если пользователь авторизован в Панели управления или имеет полные права на просмотр документа, тогда
+ if (isset ($_SESSION['adminpanel']) || isset ($_SESSION['alles']))
+ {
+ // Отображаем информационное окно с сообщением, определенным в свойстве _doc_not_published
+ display_notice($this->_doc_not_published);
+ }
+ else // В противном случае фиксируем ошибку
+ {
+ $this->curentdoc = false;
+ }
+ }
+ }
+ return (! empty($this->curentdoc));
+ }
+
+ /**
+ * Метод парсинга тега [tag:(css|js):files]
+ * для вывода css/js-файлов в шаблоне через combine.php
+ *
+ * @param array $tag параметры тега
+ * @return string что выводить в шаблоне
+ */
+ function _parse_combine($tag)
+ {
+ // тип тега (css|js)
+ $type = $tag[1];
+ // имена файлов
+ $files = explode(',',$tag[2]);
+
+ // определяем путь. если указан - то считаем от корня, если нет, то в /[tag:mediapath]/css|js/
+ if ($tag[3])
+ {
+ $path = '/' . trim($tag[3],'/') . '/';
+ }
+ else
+ {
+ $path = '/templates/' . THEME_FOLDER . '/' . $type . '/';
+ }
+
+ // уровень вложенности
+ $level = substr_count($path,'/') - 1;
+
+ // копируем combine.php, если он поменялся или отсутствует
+ $dest_stat = stat(BASE_DIR . $path . 'combine.php');
+ $source_stat = stat(BASE_DIR . '/lib/combine/combine.php');
+
+ if (! file_exists(BASE_DIR . $path . 'combine.php') || $source_stat[9] > $dest_stat[9])
+ {
+ @copy(BASE_DIR . '/lib/combine/combine.php', BASE_DIR . $path . 'combine.php');
+ }
+
+ // удаляем из списка отсутствующие файлы
+ foreach($files as $key=>$file)
+ {
+ if (! file_exists(BASE_DIR . $path . $file))
+ unset($files[$key]);
+ }
+
+ if ($files)
+ {
+ $combine = $path . 'combine.php?level=' . $level . '&' . $type . '=' . implode(',', $files);
+ $combine = @str_replace('//','/',$combine);
+ }
+
+ return $combine;
+ }
+
+ /**
+ * Внешние методы класса
+ */
+
+ /**
+ * Метод, предназначенный для обработки системных тегов модулей. Здесь подключаются только те файлы модулей,
+ * системные теги которых обнаружены в шаблоне при парсинге. Также формирует массив всех установленных модулей
+ * в системе, предварительно проверяя их доступность.
+ *
+ * @param string $template текст шаблона с тегами
+ * @return string текст шаблона с обработанными тегами модулей
+ */
+ function coreModuleTagParse($template)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $pattern = array(); // Массив системных тегов
+ $replace = array(); // Массив функций, на которые будут заменены системные теги
+
+ // Если уже имеются данные об установленных модулях
+ if (null !== $this->install_modules)
+ {
+ // Циклически обрабатываем каждый модуль
+ foreach ($this->install_modules as $row)
+ {
+ // Если в запросе пришел вызов модуля или у модуля есть функция вызываемая тегом,
+ // который присутствует в шаблоне
+ if ((isset($_REQUEST['module']) && $_REQUEST['module'] == $row->ModuleSysName) ||
+ (1 == $row->ModuleIsFunction && !empty($row->ModuleAveTag) && 1 == preg_match($row->ModuleAveTag, $template)))
+ {
+ // Проверяем, существует ли для данного модуля функция. Если да,
+ // получаем php код функции.
+ if (function_exists($row->ModuleStatus))
+ {
+ $pattern[] = $row->ModuleAveTag;
+ $replace[] = $row->ModulePHPTag;
+ }
+ else // В противном случае
+ {
+ // Проверяем, существует ли для данного модуля файл module.php в его персональной директории
+ $mod_file = BASE_DIR . '/modules/' . $row->ModuleSysName . '/module.php';
+
+ if (is_file($mod_file) && include_once($mod_file))
+ {
+ // Если файл модуля найден, тогда
+ if ($row->ModuleAveTag)
+ {
+ $pattern[] = $row->ModuleAveTag; // Получаем его системный тег
+
+ // Проверяем, существует ли для данного модуля функция. Если да,
+ // получаем php код функции, в противном случае формируем сообщение с ошибкой
+ $replace[] = function_exists($row->ModuleFunction)
+ ? $row->ModulePHPTag
+ : ($this->_module_error . ' "' . $row->ModuleName . '"');
+ }
+ }
+ // Если файла module.php не существует, формируем сообщение с ошибкой
+ elseif ($row->ModuleAveTag)
+ { $pattern[] = $row->ModuleAveTag;
+ $replace[] = $this->_module_error . ' "' . $row->ModuleName . '"';
+ }
+ }
+ }
+ }
+
+ // Выполняем замену систеного тега на php код и возвращаем результат
+ return preg_replace($pattern, $replace, $template);
+ }
+ else // В противном случае, если список модулей пустой
+ {
+ $this->install_modules = array();
+
+ // Выполняем запрос к БД на получение информации о всех модулях, которые установлены в системе
+ // (именно установлены, а не просто существуют в виде папок)
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX. "_module
+ WHERE
+ ModuleStatus = '1'
+ ");
+
+ // Циклически обрабатываем полученные данные
+ while ($row = $sql->FetchRow())
+ {
+ // Если в запросе пришел параметр module и для данного названия модуля существует
+ // директория или данный модуль имеет функцию и его системный тег указан в каком-либо шаблоне, тогда
+ if ((isset($_REQUEST['module']) && $_REQUEST['module'] == $row->ModuleSysName) ||
+ (1 == $row->ModuleIsFunction && ! empty($row->ModuleAveTag) && 1 == preg_match($row->ModuleAveTag, $template)))
+ {
+ // Проверяем, существует ли для данного модуля файл module.php в его персональной директории
+ $mod_file = BASE_DIR . '/modules/' . $row->ModuleSysName . '/module.php';
+
+ if (is_file($mod_file) && include_once($mod_file))
+ { // Если файл модуля найден, тогда
+ if (! empty($row->ModuleAveTag))
+ {
+ $pattern[] = $row->ModuleAveTag; // Получаем его системный тег
+
+ // Проверяем, существует ли для данного модуля функция. Если да,
+ // получаем php код функции, в противном случае формируем сообщение с ошибкой
+ $replace[] = function_exists($row->ModuleFunction)
+ ? $row->ModulePHPTag
+ : ($this->_module_error . ' "' . $row->ModuleName . '"');
+ }
+ // Сохряняем информацию о модуле
+ $this->install_modules[$row->ModuleSysName] = $row;
+ }
+ elseif ($row->ModuleAveTag) // Если файла module.php не существует, формируем сообщение с ошибкой
+ {
+ $pattern[] = $row->ModuleAveTag;
+ $replace[] = $this->_module_error . ' "' . $row->ModuleName . '"';
+ }
+ }
+ else
+ { // Если у модуля нет функции или тег модуля не используется - просто помещаем в массив информацию о модуле
+ $this->install_modules[$row->ModuleSysName] = $row;
+ }
+ }
+ // Выполняем замену систеного тега на php код и возвращаем результат
+ return preg_replace($pattern, $replace, $template);
+ }
+ }
+
+ /**
+ * Метод, предназанченный для сборки всей страницы в единое целое.
+ *
+ * @param int $id идентификатор документа
+ * @param int $rub_id идентификатор рубрики
+ */
+ function coreSiteFetch($id, $rub_id = '')
+ {
+ global $AVE_DB;
+
+ $main_content = '';
+
+ // Если происходит вызов модуля, получаем соответствующие мета-теги и получаем шаблон модуля
+ if (isset($_REQUEST['module']) && ! empty($_REQUEST['module']))
+ {
+ $out = $this->_coreModuleMetatagsFetch();
+ $out = $this->_coreDocumentTemplateGet('', '', $this->_coreModuleTemplateGet());
+ }
+ // Если происходит вызов системного блока
+ elseif (isset($_REQUEST['sysblock']) && ! empty($_REQUEST['sysblock']))
+ {
+ if (! is_numeric($_REQUEST['sysblock']) && preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $_REQUEST['sysblock']) !== 1)
+ {
+ header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true);
+ exit;
+ }
+
+ // проверяем разрешение на внешнее обращение
+ if (! $this->_sysBlock($_REQUEST['sysblock'], 'sysblock_external'))
+ {
+ header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found', true);
+ exit;
+ }
+
+ // проверяем разрешение на обращение только по Ajax
+ if ($this->_sysBlock($_REQUEST['sysblock'], 'sysblock_ajax'))
+ {
+ if (isAjax())
+ $out = parse_sysblock($_REQUEST['sysblock']);
+ else
+ $this->_coreErrorPage404();
}
else
{
- header('Location:' . ABS_PATH . $get_url . URL_SUFF);
- exit();
+ $out = parse_sysblock($_REQUEST['sysblock']);
}
}
- }
- else
+ // Если происходит вызов запроса
+ elseif (isset($_REQUEST['request']) && ! empty($_REQUEST['request']))
{
- $redirect_alias = $AVE_DB->Query("
- SELECT
- a.document_alias
- FROM
- ".PREFIX."_document_alias_history AS h,
- ".PREFIX."_documents AS a
- WHERE
- h.document_id = a.Id
- AND
- h.document_alias = '" . $get_url . "'
- ")->GetCell();
+ if (! is_numeric($_REQUEST['request']) && preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $_REQUEST['request']) !== 1)
+ $this->_coreErrorPage404();
- if(! empty($redirect_alias))
+ // Определяем рубрику
+ define('RUB_ID', ! empty ($rub_id)
+ ? $rub_id
+ : $this->curentdoc->rubric_id);
+
+ // Проверяем разрешение на внешнее обращение
+ if (! $this->_requestGet($_REQUEST['request'], 'request_external'))
+ $this->_coreErrorPage404();
+
+ // Проверяем разрешение на обращение только по Ajax
+ if ($this->_requestGet($_REQUEST['request'], 'request_ajax'))
+ {
+ if (isAjax())
+ $out = request_parse($_REQUEST['request']);
+ else
+ $this->_coreErrorPage404();
+ }
+ else
+ {
+ $out = request_parse($_REQUEST['request']);
+ }
+ }
+ // В противном случае начинаем вывод документа
+ else
+ {
+ if (! isset($this->curentdoc->Id) && ! $this->_coreCurrentDocumentFetch($id, UGROUP))
+ {
+ // Определяем документ с 404 ошибкой в случае, если документ не найден
+ if ($this->_corePageNotFoundFetch(PAGE_NOT_FOUND_ID, UGROUP))
+ $_REQUEST['id'] = $_GET['id'] = $id = PAGE_NOT_FOUND_ID;
+ }
+
+ // проверяем параметры публикации документа
+ if (! $this->_coreDocumentIsPublished())
+ $this->_coreErrorPage404();
+
+ // Определяем права доступа к документам рубрики
+ define('RUB_ID', ! empty ($rub_id)
+ ? $rub_id
+ : $this->curentdoc->rubric_id);
+
+ $this->_coreRubricPermissionFetch(RUB_ID);
+
+ // Выполняем Код рубрики До загрузки документа
+ ob_start();
+ eval('?>' . $this->curentdoc->rubric_start_code . '');
+ ob_end_clean();
+
+ // Получаем шаблон
+ $out = $this->_coreDocumentTemplateGet(RUB_ID);
+
+ if (! ((isset ($_SESSION[RUB_ID . '_docread']) && $_SESSION[RUB_ID . '_docread'] == 1)
+ || (isset ($_SESSION[RUB_ID . '_alles']) && $_SESSION[RUB_ID . '_alles'] == 1)) )
+ { // читать запрещено - извлекаем ругательство и отдаём вместо контента
+ $main_content = get_settings('message_forbidden');
+ }
+ else
+ {
+ if (isset ($_REQUEST['print']) && $_REQUEST['print'] == 1)
+ { // Увеличиваем счетчик версий для печати
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_documents
+ SET
+ document_count_print = document_count_print + 1
+ WHERE
+ Id = '" . $id . "'
+ ");
+ }
+ else
+ {
+ if (! isset ($_SESSION['doc_view'][$id]))
+ { // Увеличиваем счетчик просмотров (1 раз в пределах сессии)
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_documents
+ SET
+ document_count_view = document_count_view + 1
+ WHERE
+ Id = '" . $id . "'
+ ");
+
+ $_SESSION['doc_view'][$id] = time();
+ }
+
+ $curdate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
+
+ if (! isset($_SESSION['doc_view_dayly['.$curdate.'][' . $id . ']']))
+ {
+ // и подневный счетчик просмотров тоже увеличиваем
+ $curdate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_view_count
+ SET
+ count = count + 1
+ WHERE
+ document_id = '" . $id . "' AND
+ day_id = '".$curdate."'
+ ");
+
+ if (! $AVE_DB->getAffectedRows())
+ {
+ $AVE_DB->Query("
+ INSERT INTO " . PREFIX . "_view_count (
+ document_id,
+ day_id,
+ count
+ )
+ VALUES (
+ '" . $id . "', '".$curdate."', '1'
+ )
+ ");
+ }
+
+ $_SESSION['doc_view_dayly['.$curdate.'][' . $id . ']'] = time();
+ }
+ }
+
+ if (CACHE_DOC_TPL && empty ($_POST) && !(isset ($_SESSION['user_adminmode']) && $_SESSION['user_adminmode'] == 1))
+ {
+ // Кэширование разрешено
+ // Извлекаем скомпилированный шаблон документа из кэша
+ // Если там пусто, пробуем достать из бд
+
+ $cache_id = (int)$this->curentdoc->Id;
+ $cache_id = 'compiled/' . (floor($cache_id / 1000)) . '/' . $cache_id;
+
+ $cache_file = $this->_get_cache_hash();
+
+ $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
+ ? trim($cache_id) . '/'
+ : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
+
+ if (CACHE_DOC_FILE && file_exists($cache_dir . $cache_file))
+ {
+ $main_content = file_get_contents($cache_dir . $cache_file);
+ }
+ else
+ {
+ $main_content = $AVE_DB->Query("
+ SELECT
+ compiled
+ FROM
+ " . PREFIX . "_rubric_template_cache
+ WHERE
+ hash = '" . $cache_file . "'
+ LIMIT 1
+ ")->GetCell();
+ }
+
+ unset($cache_dir, $cache_file, $cache_id);
+ }
+ else
+ { // Кэширование запрещено
+ $main_content = false;
+ }
+
+ // Собираем контент
+ // Если в кеше нет контента, то
+ if (empty($main_content))
+ {
+ // Кэш пустой или отключен, извлекаем и компилируем шаблон
+ if (! empty ($this->curentdoc->rubric_template))
+ {
+ $rubTmpl = $this->curentdoc->rubric_template;
+ }
+ else
+ {
+ // Если документу задан другой шаблон из данной рубрики, то берем его
+ if ($this->curentdoc->rubric_tmpl_id != 0)
+ {
+ $rubTmpl = $AVE_DB->Query("
+ SELECT
+ template
+ FROM
+ " . PREFIX . "_rubric_templates
+ WHERE
+ id = '" . $this->curentdoc->rubric_tmpl_id . "'
+ AND
+ rubric_id = '" . RUB_ID . "'
+ LIMIT 1
+ ")->GetCell();
+ }
+ // Иначе берем стандартный шаблон рубрики
+ else
+ {
+ $rubTmpl = $AVE_DB->Query("
+ SELECT
+ rubric_template
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ Id = '" . RUB_ID . "'
+ LIMIT 1
+ ")->GetCell();
+ }
+ }
+
+ $rubTmpl = trim($rubTmpl);
+
+ // Собираем шаблон рубрики
+ if (empty($rubTmpl))
+ {
+ // Если не задан шаблон рубрики, выводим сообщение
+ $main_content = $this->_rubric_template_empty;
+ }
+ else
+ {
+ // Проверяем теги полей в шаблоне рубрики на условие != ''
+ $main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.'?'.'>', $rubTmpl);
+ $main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.'?'.'>', $main_content);
+ $main_content = str_replace('[tag:if:else]', '', $main_content);
+ $main_content = str_replace('[tag:/if]', '', $main_content);
+
+ // Парсим теги полей документа в шаблоне рубрики
+ $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', 'return_element', $main_content);
+ $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]/', 'document_get_field', $main_content);
+ $main_content = preg_replace_callback('/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', 'return_element', $main_content);
+ $main_content = preg_replace_callback('/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/', 'watermarks', $main_content);
+ $main_content = preg_replace_callback('/\[tag:([r|c|f|t|s]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $main_content);
+
+ // Возвращаем поле из БД документа
+ $main_content = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
+ {
+ return isset($this->curentdoc->{$match[1]})
+ ? $this->curentdoc->{$match[1]}
+ : null;
+ },
+ $main_content
+ );
+
+ // Если пришел вызов на активацию языковых файлов
+ $main_content = preg_replace_callback(
+ '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
+ {
+ global $AVE_Template;
+
+ return $AVE_Template->get_config_vars($match[1]);
+ },
+ $main_content
+ );
+
+ // Удаляем ошибочные теги полей документа в шаблоне рубрики
+ $main_content = preg_replace('/\[tag:watermark:\w*\]/', '', $main_content);
+ $main_content = preg_replace('/\[tag:fld:\d*\]/', '', $main_content);
+ $main_content = preg_replace('/\[tag:doc:\w*\]/', '', $main_content);
+ $main_content = preg_replace('/\[tag:langfile:\w*\]/', '', $main_content);
+
+ if (CACHE_DOC_TPL && empty ($_POST) && !(isset ($_SESSION['user_adminmode']) && $_SESSION['user_adminmode'] == 1))
+ {
+ $cache_id = (int)$this->curentdoc->Id;
+ $cache_id = 'compiled/' . (floor($cache_id / 1000)) . '/' . $cache_id;
+
+ $cache_file = $this->_get_cache_hash();
+
+ $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
+ ? trim($cache_id) . '/'
+ : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
+
+ // кэширование разрешено
+ // сохраняем скомпилированный шаблон в кэш
+ if (CACHE_DOC_FILE)
+ {
+ if(! is_dir($cache_dir))
+ mkdir($cache_dir, 0777, true);
+
+ file_put_contents($cache_dir . $cache_file, $main_content);
+ }
+
+ // кэширование разрешено
+ // сохраняем скомпилированный шаблон в кэш
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_template_cache
+ SET
+ hash = '" . $cache_file . "',
+ rub_id = '" . RUB_ID . "',
+ rub_tmpl_id = '" . $this->curentdoc->rubric_tmpl_id . "',
+ grp_id = '" . UGROUP . "',
+ doc_id = '" . $id . "',
+ compiled = '" . addslashes($main_content) . "'
+ ");
+
+ unset($cache_id, $cache_file, $cache_dir);
+ }
+ }
+ }
+
+ // парсим теги в шаблоне рубрики
+ $main_content = preg_replace_callback(
+ '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
+ create_function('$m','return translate_date(date($m[1], '.$this->curentdoc->document_published.'));
+ '),
+ $main_content
+ );
+
+ $main_content = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $this->curentdoc->document_published)), $main_content);
+ $main_content = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $this->curentdoc->document_published)), $main_content);
+ $main_content = str_replace('[tag:humandate]', human_date($this->curentdoc->document_published), $main_content);
+ $main_content = str_replace('[tag:docauthorid]', $this->curentdoc->document_author_id, $main_content);
+
+ if (preg_match('[tag:docauthor]', $main_content))
+ $main_content = str_replace('[tag:docauthor]', get_username_by_id($this->curentdoc->document_author_id), $main_content);
+ }
+
+ $out = str_replace('[tag:maincontent]', $main_content, $out);
+
+ unset($this->curentdoc->rubric_template, $this->curentdoc->template);
+ }
+ // Конец вывода документа
+
+ //Работа с условиями
+ /*
+ $out = preg_replace('/\[tag:if_exp:?(.*)\]/u', '', $out);
+ $out = str_replace('[tag:if_exp_else]', '', $out);
+ $out = str_replace('[tag:/if_exp]', '', $out);
+
+ */
+
+ // Тут мы вводим в хеадер и футер иньекцию скриптов.
+ if (defined('RUB_ID'))
+ {
+ $replace = array(
+ '[tag:rubheader]' => $this->curentdoc->rubric_header_template . '[tag:rubheader]',
+ '[tag:rubfooter]' => $this->curentdoc->rubric_footer_template . '[tag:rubfooter]'
+ );
+
+ $out = str_replace(array_keys($replace), array_values($replace), $out);
+
+ unset($replace);
+ }
+
+ // Парсим поля запроса
+ $out = preg_replace_callback(
+ '/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/',
+ create_function(
+ '$m',
+ 'return request_get_document_field($m[1], ' . $id . ', $m[2], ' . (defined('RUB_ID') ? RUB_ID : 0) . ');'
+ ),
+ $out
+ );
+
+ // Удаляем ошибочные теги полей документа в шаблоне рубрики
+ $out = preg_replace('/\[tag:rfld:\d*\]/', '', $out);
+
+ // Если в GET запросе пришел параметр print, т.е. страница для печати,
+ // парсим контент, который обрамлен тегами только для печати
+ if (isset ($_REQUEST['print']) && $_REQUEST['print'] == 1)
+ {
+ $out = str_replace(array('[tag:if_print]', '[/tag:if_print]'), '', $out);
+ $out = preg_replace('/\[tag:if_notprint\](.*?)\[\/tag:if_notprint\]/si', '', $out);
+ }
+ else
+ {
+ // В противном случае наоборот, парсим только тот контент, который предназначен НЕ для печати
+ $out = preg_replace('/\[tag:if_print\](.*?)\[\/tag:if_print\]/si', '', $out);
+ $out = str_replace(array('[tag:if_notprint]', '[/tag:if_notprint]'), '', $out);
+ }
+
+ // Парсим теги визуальных блоков
+ $out = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $out);
+
+ // Парсим теги системных блоков
+ $out = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $out);
+
+ // Парсим теги модулей
+ $out = $this->coreModuleTagParse($out);
+
+ // Если в запросе пришел параметр module, т.е. вызов модуля,
+ // проверяем установлен и активен ли модуль
+ if (isset($_REQUEST['module'])
+ && ! (isset($this->install_modules[$_REQUEST['module']])
+ && '1' == $this->install_modules[$_REQUEST['module']]->ModuleStatus) )
+ {
+ // Выводим сообщение о том что такого модуля нет
+ display_notice($this->_module_error);
+ }
+
+ // Парсим теги системы внутренних запросов
+ $out = preg_replace_callback('/\[tag:request:([A-Za-z0-9-_]{1,20}+)\]/', 'request_parse', $out);
+
+ // Парсим теги навигации
+ $out = preg_replace_callback('/\[tag:navigation:([A-Za-z0-9-_]{1,20}+):?([0-9,]*)\]/', 'parse_navigation', $out);
+
+ // Парсим теги скрытого текста
+ $out = parse_hide($out);
+
+ // Если в запросе пришел параметр sysblock, т.е. вызов сис блока,
+ // парсим контент
+ if (isset($_REQUEST['sysblock']) && $_REQUEST['sysblock'] != '')
+ {
+ $search = array(
+ '[tag:mediapath]',
+ '[tag:path]',
+ '[tag:sitename]',
+ '[tag:home]',
+ '[tag:docid]',
+ '[tag:docparent]'
+ );
+
+ $replace = array(
+ ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
+ ABS_PATH,
+ htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
+ get_home_link(),
+ (isset ($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
+ (isset ($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
+ );
+ }
+ // Если в запросе пришел параметр request, т.е. вызов запроса,
+ // парсим контент
+ elseif (isset($_REQUEST['request']) && $_REQUEST['request'] != '')
+ {
+ $search = array(
+ '[tag:mediapath]',
+ '[tag:path]',
+ '[tag:sitename]',
+ '[tag:home]',
+ '[tag:docid]',
+ '[tag:docparent]'
+ );
+
+ $replace = array(
+ ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
+ ABS_PATH,
+ htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
+ get_home_link(),
+ (isset ($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
+ (isset ($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
+ );
+ }
+ else
+ {
+ // В противном случае
+ // парсим остальные теги основного шаблона
+ $search = array(
+ '[tag:mediapath]',
+ '[tag:path]',
+ '[tag:sitename]',
+ '[tag:alias]',
+ '[tag:domain]',
+ '[tag:home]',
+ '[tag:robots]',
+ '[tag:canonical]',
+ '[tag:docid]',
+ '[tag:docparent]'
+ );
+
+ $replace = array(
+ ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/',
+ ABS_PATH,
+ htmlspecialchars(get_settings('site_name'), ENT_QUOTES),
+ (isset($_REQUEST['id'])) ? isset ($this->curentdoc->document_alias) ? $this->curentdoc->document_alias : '' : '',
+ getSiteUrl(),
+ get_home_link(),
+ (isset($this->curentdoc->document_meta_robots) ? $this->curentdoc->document_meta_robots : ''),
+ canonical(isset ($this->curentdoc->document_alias) ? ABS_PATH . $this->curentdoc->document_alias : ''),
+ (isset($this->curentdoc->Id) ? $this->curentdoc->Id : ''),
+ (isset($this->curentdoc->document_parent) ? $this->curentdoc->document_parent : '')
+ );
+ }
+
+ // Если пришел контент из модуля
+ if (defined('MODULE_CONTENT'))
+ {
+ // парсинг тегов при выводе из модуля
+ $search[] = '[tag:maincontent]';
+ $replace[] = MODULE_CONTENT;
+ $search[] = '[tag:title]';
+ $replace[] = htmlspecialchars(defined('MODULE_TITLE') ? MODULE_TITLE : '', ENT_QUOTES);
+ $search[] = '[tag:description]';
+ $replace[] = htmlspecialchars(defined('MODULE_DESCRIPTION') ? MODULE_DESCRIPTION : '', ENT_QUOTES);
+ $search[] = '[tag:keywords]';
+ $replace[] = htmlspecialchars(defined('MODULE_KEYWORDS') ? MODULE_KEYWORDS : '', ENT_QUOTES);
+ }
+ // Или из системного блока
+ elseif (isset($_REQUEST['sysblock']))
+ {
+ // Убираем пустые теги в сис блоке
+ $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
+ $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
+ }
+ // Или из запроса
+ elseif (isset($_REQUEST['request']))
+ {
+ // Убираем пустые теги в сис блоке
+ $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
+ $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
+ }
+ // Иначе
+ else
+ {
+ // Если стоит вкл на генерацию keywords, description
+ if ($this->curentdoc->rubric_meta_gen)
+ {
+ // Генерируем keywords, description на основе
+ // данных документа, если позволяет рубрика
+ require_once(dirname(__FILE__).'/class.meta.php');
+ $meta = new Meta();
+ $res = $meta->generateMeta($main_content);
+ }
+
+ // Убираем пустые теги
+ $main_content = preg_replace('/\[tag:(.+?)\]/', '', $main_content);
+ $main_content = preg_replace('/\[mod_(.+?)\]/', '', $main_content);
+
+ // Парсим keywords, description, title
+ $search[] = '[tag:keywords]';
+ $replace[] = stripslashes(htmlspecialchars((! empty ($this->curentdoc->rubric_meta_gen) ? $res['keywords'] : $this->curentdoc->document_meta_keywords), ENT_QUOTES));
+ $search[] = '[tag:description]';
+ $replace[] = stripslashes(htmlspecialchars((! empty ($this->curentdoc->rubric_meta_gen) ? $res['description'] : $this->curentdoc->document_meta_description), ENT_QUOTES));
+ $search[] = '[tag:title]';
+ $replace[] = stripslashes(htmlspecialchars_decode(pretty_chars($this->curentdoc->document_title)));
+ }
+
+ // Возвращаем поле из БД документа
+ $out = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
+ {
+ return isset($this->curentdoc->{$match[1]})
+ ? $this->curentdoc->{$match[1]}
+ : null;
+ },
+ $out
+ );
+
+ // Если пришел вызов на активацию языковых файлов
+ $out = preg_replace_callback(
+ '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
+ {
+ global $AVE_Template;
+
+ return $AVE_Template->get_config_vars($match[1]);
+ },
+ $out
+ );
+
+ // Убираем пустые теги
+ $out = preg_replace('/\[tag:doc:\d*\]/', '', $out);
+ $out = preg_replace('/\[tag:langfile:\d*\]/', '', $out);
+
+ // Убираем дубликат
+ $search[] = '[tag:maincontent]';
+ $replace[] = '';
+
+ // Парсим линк на версию для печати
+ $search[] = '[tag:printlink]';
+ $replace[] = get_print_link();
+
+ // Парсим тег версии системы
+ $search[] = '[tag:version]';
+ $replace[] = APP_NAME . ' v' . APP_VERSION ;
+
+ // Парсим тег кол-ва просмотра данного документа
+ $search[] = '[tag:docviews]';
+ $replace[] = isset ($this->curentdoc->document_count_view) ? $this->curentdoc->document_count_view : '';
+
+ // Парсим тизер документа
+ $out = preg_replace_callback(
+ '/\[tag:teaser:(\d+)(|:\[(.*?)\])\]/',
+ create_function(
+ '$m',
+ 'return showteaser($m[1], $m[2]);'
+ ),
+ $out
+ );
+
+ // Парсим аватар автора документа
+ if (defined('RUB_ID'))
+ $out = preg_replace_callback(
+ '/\[tag:docauthoravatar:(\d+)\]/',
+ create_function(
+ '$m',
+ 'return getAvatar('.intval($this->curentdoc->document_author_id).', $m[1]);'
+ ),
+ $out
+ );
+
+ // Парсим теги языковых условий
+ if (defined('RUB_ID'))
+ {
+ $out = preg_replace('/\[tag:lang:([a-zA-Z0-9-_]+)\]/', 'curentdoc->document_lang == "$1") { ?>', $out);
+ }
+ else
+ {
+ $out = preg_replace('/\[tag:lang:([a-zA-Z0-9-_]+)\]/', '', $out);
+ }
+
+ $out = str_replace('[tag:/lang]', '', $out);
+
+ // Парсим хлебные крошки
+ if (preg_match('/\[tag:breadcrumb]/u', $out))
+ {
+ $out = preg_replace_callback('/\[tag:breadcrumb\]/', 'get_breadcrumb', $out);
+ }
+
+ // Парсим остальные теги основного шаблона
+ $out = str_replace($search, $replace, $out);
+
+ unset ($search, $replace); //Убираем данные
+
+ // Парсим теги для combine.php
+ $out = preg_replace_callback('/\[tag:(css|js):([^ :\/]+):?(\S+)*\]/', array($this, '_parse_combine'), $out);
+
+ // ЧПУ
+ $out = str_ireplace('"//"','"/"', str_ireplace('///','/', rewrite_link($out)));
+
+ unset($main_content);
+
+ // Выводим собранный документ
+ echo $out;
+ }
+
+ /**
+ * Метод, предназначенный для формирования ЧПУ, а также для поиска документа и разбора
+ * дополнительных параметров в URL
+ *
+ * @param string $get_url Строка символов
+ *
+ */
+ function coreUrlParse($get_url = '')
+ {
+ global $AVE_DB;
+
+ // Если нужны параметры GET, можно отключить
+ $get_url = (strpos($get_url, ABS_PATH . '?') === 0
+ ? ''
+ : $get_url);
+
+ if (substr($get_url, 0, strlen(ABS_PATH . 'index.php')) != ABS_PATH . 'index.php' AND strpos($get_url, '?') !== false)
+ $get_url = substr($get_url, 0, strpos($get_url, '?'));
+
+ $get_url = rawurldecode($get_url);
+ $get_url = mb_substr($get_url, strlen(ABS_PATH));
+
+ // Сохранение старого урла для првоерки использования суффикса
+ $test_url = $get_url;
+
+ if (mb_substr($get_url, - strlen(URL_SUFF)) == URL_SUFF)
+ {
+ $get_url = mb_substr($get_url, 0, - strlen(URL_SUFF));
+ }
+
+ // Разбиваем строку параметров на отдельные части
+ $get_url = explode('/', $get_url);
+
+ if (isset ($get_url['index']))
+ {
+ unset ($get_url['index']);
+ }
+
+ if (isset ($get_url['print']))
+ {
+ $_GET['print'] = $_REQUEST['print'] = 1;
+ unset ($get_url['print']);
+ }
+
+ // Определяем, используется ли у нас разделение документа по страницам
+ $pages = preg_grep('/^(a|art)?page-\d+$/i', $get_url);
+
+ if (! empty ($pages))
+ {
+ $get_url = implode('/', array_diff($get_url, $pages));
+ $pages = implode('/', $pages);
+
+ preg_replace_callback(
+ '/(page|apage|artpage)-(\d+)/i',
+ create_function(
+ '$matches',
+ '$_GET[$matches[1]] = $matches[2]; $_REQUEST[$matches[1]] = $matches[2];'
+ ),
+ $pages
+ );
+ }
+ // В противном случае формируем окончательную ссылку для документа
+ else
+ {
+ $get_url = implode('/', $get_url);
+ }
+
+ //-- Проверяем есть ли данный URL в таблице алиасов модулей
+ $sql = "
+ SELECT
+ module_name,
+ module_action,
+ module_link
+ FROM
+ " . PREFIX . "_modules_aliases
+ WHERE
+ module_url = '" . str_ireplace("'", "\'", $get_url) . "'
+ ";
+
+ $query = $AVE_DB->Query($sql)->FetchRow();
+
+ if ($query)
+ {
+ //-- Передаем глобальные перемененные
+ $_GET['module'] = $_REQUEST['module'] = $query->module_name;
+ $_GET['action'] = $_REQUEST['action'] = $query->module_action;
+
+ $get_url = ABS_PATH . $query->module_link;
+ }
+
+ // проверка на наличие id в запросе
+ if (! empty($_REQUEST['id']))
+ {
+ $get_url = $AVE_DB->Query("
+ SELECT
+ document_alias
+ FROM
+ " . PREFIX . "_documents
+ WHERE
+ Id = '" . (int)$_REQUEST['id'] . "'
+ ")->GetCell();
+ }
+ // Выполняем запрос к БД на получение всей необходимой
+ // информации о документе
+
+ // Экранируем поступающий URL
+ $get_url = $AVE_DB->EscStr($get_url);
+
+ if (mb_strlen($get_url) > 255)
+ $get_url = '';
+
+ // Забираем нужные данные
+ $sql = $AVE_DB->Query("
+ SELECT
+ doc.*,
+ rubric_permission,
+ rubric_template,
+ rubric_meta_gen,
+ rub.rubric_header_template,
+ rub.rubric_footer_template,
+ rub.rubric_start_code,
+ template_text,
+ other.template
+ FROM
+ " . PREFIX . "_documents AS doc
+ JOIN
+ " . PREFIX . "_rubrics AS rub
+ ON rub.Id = doc.rubric_id
+ JOIN
+ " . PREFIX . "_templates AS tpl
+ ON tpl.Id = rubric_template_id
+ JOIN
+ " . PREFIX . "_rubric_permissions AS prm
+ ON doc.rubric_id = prm.rubric_id
+ LEFT JOIN
+ " . PREFIX . "_rubric_templates AS other
+ ON doc.rubric_id = other.rubric_id AND doc.rubric_tmpl_id = other.id
+ WHERE
+ user_group_id = '" . UGROUP . "'
+ AND
+ " . (! empty ($get_url)
+ ? "document_alias = '" . str_ireplace("'", "\'", $get_url) . "'"
+ : (! empty($_REQUEST['id'])
+ ? "doc.Id =" . intval($_REQUEST['id'])
+ : "doc.Id = 1")) . "
+ LIMIT 1
+ ");
+
+ if ($this->curentdoc = $sql->FetchRow())
+ {
+ if ($this->curentdoc->rubric_tmpl_id != 0)
+ {
+ $this->curentdoc->rubric_template = (($this->curentdoc->template != '')
+ ? $this->curentdoc->template
+ : $this->curentdoc->rubric_template);
+
+ unset($this->curentdoc->template);
+ }
+
+ // Глобальные переменные
+ $_GET['id'] = $_REQUEST['id'] = $this->curentdoc->Id;
+ $_GET['doc'] = $_REQUEST['doc'] = $this->curentdoc->document_alias;
+
+ // Назначаем язык пользователю, в завивисомтси от языка документа
+ if ($this->curentdoc->Id != PAGE_NOT_FOUND_ID OR $this->curentdoc->document_lang == '--')
+ $_SESSION['user_language'] = $this->curentdoc->document_lang;
+
+ // Перенаправление на адреса с суффиксом
+ if (
+ $test_url !== $get_url . URL_SUFF
+ && ! $pages && $test_url
+ && ! $_REQUEST['print']
+ && ! $_REQUEST['module']
+ && ! $_REQUEST['tag']
+ && REWRITE_MODE
+ )
{
header('HTTP/1.1 301 Moved Permanently');
- header('Location:' . ABS_PATH . $redirect_alias . URL_SUFF);
- exit();
+
+ if ($this->curentdoc->Id == 1)
+ {
+ header('Location:' . ABS_PATH);
+ exit();
+ }
+ else
+ {
+ header('Location:' . ABS_PATH . $get_url . URL_SUFF);
+ exit();
+ }
}
-
- if(! (! empty($_REQUEST['sysblock']) || ! empty($_REQUEST['module']) || ! empty($_REQUEST['request'])))
- $_GET['id'] = $_REQUEST['id'] = PAGE_NOT_FOUND_ID;
}
- }
-}
+ else
+ {
+ $sql = "
+ SELECT
+ a.document_alias
+ FROM
+ ".PREFIX."_document_alias_history AS h,
+ ".PREFIX."_documents AS a
+ WHERE
+ h.document_id = a.Id
+ AND
+ h.document_alias = '" . $get_url . "'
+ ";
-?>
+ $redirect_alias = $AVE_DB->Query($sql)->GetCell();
+
+ if (! empty($redirect_alias))
+ {
+ header('HTTP/1.1 301 Moved Permanently');
+ header('Location:' . ABS_PATH . $redirect_alias . URL_SUFF);
+ exit();
+ }
+
+ if (! (! empty($_REQUEST['sysblock']) || ! empty($_REQUEST['module']) || ! empty($_REQUEST['request'])))
+ $_GET['id'] = $_REQUEST['id'] = PAGE_NOT_FOUND_ID;
+ }
+ }
+ }
+?>
\ No newline at end of file
diff --git a/class/class.database.php b/class/class.database.php
index 02e2313..7693e49 100755
--- a/class/class.database.php
+++ b/class/class.database.php
@@ -591,7 +591,8 @@ class AVE_DB
foreach ((array)$stack as $call)
{
- if (@$call['class'] == __CLASS__) continue;
+ if (@$call['class'] == __CLASS__)
+ continue;
$function = $call['function'];
@@ -611,7 +612,8 @@ class AVE_DB
}
-/************************* Внешние методы класса *************************/
+ /************************* Внешние методы класса *************************/
+
/**
* Метод, предназначенный для выполнения запроса к MySQL
@@ -657,31 +659,39 @@ class AVE_DB
*/
public function Query($query, $TTL = null, $cache_id = '', $log = true)
{
+ // Если это документ, то меняем расположение
if (substr($cache_id, 0, 3) == 'doc')
{
$cache_id = (int)str_replace('doc_', '', $cache_id);
$cache_id = 'doc/' . (floor($cache_id / 1000)) . '/' . $cache_id;
}
+ // Принудительная фильтрация запроса
//$query = filter_var($query, FILTER_SANITIZE_STRING);
$result = array();
- $TTL = strtoupper(substr(trim($query), 0, 6)) == 'SELECT' ? $TTL : null;
-/*
- // Не знаю кто поставил эту заглушку, но я выкл ее
- if (defined('ACP')) $TTL = null;
-*/
- if ($TTL && $TTL != "nocache")
+ // Если это SELECT - то отслеживаем кеширование
+ $TTL = strtoupper(substr(trim($query), 0, 6)) == 'SELECT'
+ ? $TTL
+ : null;
+
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE)
+ $TTL = null;
+
+ if ($TTL && ($TTL != 'nocache' AND $TTL != null))
{
$cache_file = md5($query);
- $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > '' ? trim($cache_id) . '/' : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
+ $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
+ ? trim($cache_id) . '/'
+ : substr($cache_file, 0, 2) . '/' . substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
- if(! file_exists($cache_dir))
+ if (! file_exists($cache_dir))
mkdir($cache_dir, 0777, true);
- if(! (file_exists($cache_dir . $cache_file) && ($TTL == -1 ? true : @time() - @filemtime($cache_dir . $cache_file) < $TTL)))
+ if (! (file_exists($cache_dir . $cache_file) && ($TTL == -1 ? true : time() - filemtime($cache_dir . $cache_file) < $TTL)))
{
$res = $this->Real_Query($query, $log);
@@ -702,6 +712,7 @@ class AVE_DB
return $this->Real_Query($query, $log);
}
+
/**
* This method is needed for prepared statements. They require
* the data type of the field to be bound with "i" s", etc.
@@ -737,6 +748,7 @@ class AVE_DB
return '';
}
+
/**
* Метод, предназначенный для экранирования специальных символов в строках для использования в выражениях SQL
*
@@ -753,6 +765,7 @@ class AVE_DB
return $value;
}
+
/**
* Метод, предназначенный для экранирования специальных символов в строках для использования в выражениях SQL
*
@@ -763,13 +776,26 @@ class AVE_DB
{
$value = htmlspecialchars($value);
- $value = strtr($value, array(
+ $search = array(
+ '<' => '<',
+ ';' => ':',
+ '|' => '|',
+ '&' => '&',
+ '>' => '>',
+ "'" => ''',
+ '"' => '"',
+ ')' => ')',
+ '(' => '(',
'{' => '{',
'}' => '}',
'$' => '$',
- '>' => '>',
- "'" => "'"
- ));
+ '>' => '>'
+ );
+
+ $value = str_replace(array_keys($search), array_values($search), $value);
+ $value = str_ireplace('%3Cscript', '', $value);
+
+ $value = filter_var($value, FILTER_SANITIZE_STRING);
if (! is_array($value))
{
@@ -808,18 +834,23 @@ class AVE_DB
*/
public function NumAllRows($query, $TTL = null, $cache_id = '')
{
- if ($TTL)
- {
- $cache_file = md5($query).'.count';
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE)
+ $TTL = null;
- $cache_dir = BASE_DIR.'/cache/sql/'.(trim($cache_id) > ''
- ? trim($cache_id).'/'
- : substr($cache_file, 0, 2).'/'.substr($cache_file, 2, 2).'/'.substr($cache_file, 4, 2).'/');
+ if ($TTL AND ($TTL != "nocache" AND $TTL != null))
+ {
+ // Кол-во
+ $cache_file = md5($query) . '.count';
+
+ $cache_dir = BASE_DIR . '/cache/sql/' . (trim($cache_id) > ''
+ ? trim($cache_id) . '/'
+ : substr($cache_file, 0, 2) . '/'. substr($cache_file, 2, 2) . '/' . substr($cache_file, 4, 2) . '/');
if (! file_exists($cache_dir))
mkdir($cache_dir, 0777, true);
- if (! (file_exists($cache_dir.$cache_file) && ($TTL==-1 ? true : @time()-@filemtime($cache_dir.$cache_file) < $TTL)))
+ if (! (file_exists($cache_dir . $cache_file) && ($TTL == -1 ? true : time() - filemtime($cache_dir . $cache_file) < $TTL)))
{
if ($query <> $this->_last_query)
{
@@ -1147,5 +1178,27 @@ class AVE_DB
return rrmdir($cache_dir);
}
+
+ /**
+ * Метод, предназначенный для очищения кеша запросов
+ *
+ * @param $cache_id
+ * @return bool
+ */
+ public function clear_request($cache_id)
+ {
+ $request = request_get_settings($cache_id);
+
+ $cache_from_id = BASE_DIR . '/cache/sql/request/settings/' . (trim($request->Id) > ''
+ ? trim($request->Id) . '/'
+ : '');
+
+ $cache_from_alias = BASE_DIR . '/cache/sql/request/settings/' . (trim($request->request_alias) > ''
+ ? trim($request->request_alias) . '/'
+ : '');
+
+ return (rrmdir($cache_from_id) AND rrmdir($cache_from_alias));
+ }
+
} // End AVE_DB class
?>
\ No newline at end of file
diff --git a/class/class.docs.php b/class/class.docs.php
index 0a07a97..60042a2 100755
--- a/class/class.docs.php
+++ b/class/class.docs.php
@@ -182,13 +182,82 @@ class AVE_Document
return $field;
}
-/**
- * Внутренние методы
- */
- /**
- * Управление Документами
- */
+ function _get_rubric_fields ($id)
+ {
+ global $AVE_DB;
+
+ $sql = "
+ SELECT
+ Id,
+ rubric_field_type,
+ rubric_field_numeric
+ FROM
+ ".PREFIX."_rubric_fields
+ WHERE
+ rubric_id = '" . $id . "'
+ ";
+
+ $query = $AVE_DB->Query($sql);
+
+ $ids = array();
+
+ while ($row = $query->FetchAssocArray())
+ {
+ $ids[$row['Id']]['rubric_field_type'] = $row['rubric_field_type'];
+ $ids[$row['Id']]['rubric_field_numeric'] = (int)$row['rubric_field_numeric'];
+ }
+
+ return $ids;
+ }
+
+
+ function _get_document_text_fields ($id)
+ {
+ global $AVE_DB;
+
+ $sql = "
+ SELECT
+ rubric_field_id
+ FROM
+ ".PREFIX."_document_fields_text
+ WHERE
+ document_id = '" . $id . "'
+ ";
+
+ $query = $AVE_DB->Query($sql);
+
+ $ids = array();
+
+ while ($row = $query->GetCell())
+ array_push($ids, $row);
+
+ return $ids;
+ }
+
+
+ function _get_rubric ($id)
+ {
+ global $AVE_DB;
+
+ if (! $id)
+ return false;
+
+ $sql = "
+ SELECT
+ rubric_alias,
+ rubric_alias_history,
+ rubric_code_start,
+ rubric_code_end
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ Id = '" . $id . "'
+ ";
+
+ return $AVE_DB->Query($sql)->FetchRow();
+ }
+
/**
* Метод, предназначенный для получения списка документов в Панели управления
@@ -209,6 +278,9 @@ class AVE_Document
$ex_docstatus = '';
$navi_docstatus = '';
+ // При смене страницы убираем из сессии параметры выборки документов
+ unset ($_SESSION['search_query']);
+
// Если в запросе пришел параметр на поиск документа по названию
if (!empty($_REQUEST['QueryTitel']))
{
@@ -428,6 +500,9 @@ class AVE_Document
$db_sort = 'ORDER BY doc.Id DESC';
$navi_sort = '&sort=id_desc';
+ // Параметры вывборки документов
+ $search_query = base64_encode($_SERVER['QUERY_STRING']);
+
// Если в запросе используется параметр сортировки
if (!empty($_REQUEST['sort']))
{
@@ -597,6 +672,9 @@ class AVE_Document
// Циклически обрабатываем полученные данные с целью приведения некоторых из них к удобочитаемому виду
while ($row = $sql->FetchRow())
{
+ // Запомниаем в сесии, параметры выборки для документа
+ $_SESSION['search_query'][$row->Id] = $search_query;
+
// Определяем количество комментариев, оставленных для данного документа
$row->ist_remark = $AVE_DB->Query("
SELECT
@@ -1085,23 +1163,27 @@ class AVE_Document
/**
* Метод, предназначенный для сохранения документа в БД
*
- * @param int $rubric_id идентификатор Рубрики
- * @param int $document_id идентификатор Документа
- * @param array $data Документ в массиве структура - хитрая
- * @param bool $update_non_exists_fields Изменять поля на пустые
- * значения у не переданных полей или не надо
- * @param bool $rubric_cod Использовать код рубрики или не надо
- * возвращает номер документа если все удачно и false если все плохо
+ * @param int $rubric_id Идентификатор Рубрики
+ * @param int $document_id Идентификатор Документа или null, если документ новый
+ * @param array $data Документ в массиве структура - хитрая
+ * @param bool $update_non_exists_fields Изменять поля на пустые значения у не переданных полей или не надо
+ * @param bool $rubric_code Использовать код рубрики или не надо
+ * @param bool $revisions Использовать ревизии документов
+ * @param bool $logs Писать системные сообщения в журнал
+ * @param bool $generate Генерировать Meta
+ *
+ * return int/bool Возвращает номер документа если все удачно или false если все плохо
*/
- function documentSave($rubric_id, $document_id, $data, $update_non_exists_fields = false, $rubric_code = true, $revisions = true, $logs = true, $generate = true)
+ function documentSave ($rubric_id, $document_id, $data, $update_non_exists_fields = false, $rubric_code = true, $revisions = true, $logs = true, $generate = true)
{
global $AVE_DB, $AVE_Template;
//-- Проверяем входящие данные -- //
- $rubric_id = (int)$rubric_id;
- $document_id = (int)$document_id;
+ // Если отсутсвует рубрика, ничего не делаем
+ if(! $rubric_id)
+ return false;
// Если отсутсвуют данные, ничего не делаем
if(! isset($data))
@@ -1111,30 +1193,21 @@ class AVE_Document
if(! isset($data['feld']))
return false;
+ $rubric_id = (int)$rubric_id;
+ $document_id = (int)$document_id;
+
// Определяем тип опреации
$oper = 'INSERT';
// Забираем параметры рубрики
- $_rubric = $AVE_DB->Query("
- SELECT
- rubric_alias,
- rubric_alias_history,
- rubric_code_start,
- rubric_code_end
- FROM
- " . PREFIX . "_rubrics
- WHERE
- Id = '" . $rubric_id . "'
- ")->FetchRow();
+ $_rubric = $this->_get_rubric($rubric_id);
// Запускаем триггер перед сохранением
- Hooks::trigger('DocumentBeforeSave', array('rubric_id' => $rubric_id, 'document_id' => $document_id, 'data' => $data));
+ Hooks::trigger('DocumentBeforeSave', array('rubric_id' => $rubric_id, 'document_id' => $document_id, 'data' => $data, 'requests' => $_REQUEST));
// Выполняем стартовый код рубрики
if ($rubric_code)
- {
- eval ('?>' . $_rubric->rubric_code_start . '');
- }
+ eval ('?'.'>' . $_rubric->rubric_code_start . '<'.'?');
// Если нет данных для сохранения, перкращаем сохранение и переходим на страницу документов
if (empty($data))
@@ -1154,6 +1227,7 @@ class AVE_Document
|| (defined('UGROUP') && UGROUP == 1) ))
return false;
+ // Title документа
$data['document_title'] = $_url = empty($data['document_title'])
? $AVE_Template->get_config_vars('DOC_WITHOUT_TITLE')
: $data['document_title'];
@@ -1332,7 +1406,7 @@ class AVE_Document
else
{
// Если оператор INSERT
- // Если новый алиас документа, сопадает с алиасом в истории, просто стираем историю
+ // Если новый алиас документа, совпадает с алиасом в истории, просто стираем историю
$AVE_DB->Query("
DELETE FROM
". PREFIX . "_document_alias_history
@@ -1378,9 +1452,9 @@ class AVE_Document
$fields = array();
// Получаем структуру документа
- if($oper == 'INSERT')
+ if ($oper == 'INSERT')
{
- $sql = $AVE_DB->Query("
+ $sql = "
SELECT
*
FROM
@@ -1389,28 +1463,29 @@ class AVE_Document
rubric_id = '" . $rubric_id . "'
ORDER BY
rubric_field_position ASC
- ");
+ ";
}
else
{
- $sql = $AVE_DB->Query("
+ $sql = "
SELECT
- doc.Id AS df_id,
rub.*,
rubric_field_default,
- doc.field_value
+ df.field_value
FROM
" . PREFIX . "_rubric_fields AS rub
LEFT JOIN
- " . PREFIX . "_document_fields AS doc
+ " . PREFIX . "_document_fields AS df
ON rubric_field_id = rub.Id
WHERE
document_id = '" . $document_id . "'
ORDER BY
rubric_field_position ASC
- ");
+ ";
}
+ $query = $AVE_DB->Query($sql);
+
// Если пришел вызов поля, который связан с модулем
if (isset($data['field_module']))
{
@@ -1420,18 +1495,18 @@ class AVE_Document
$mod_function = (string)$mod_val . '_document_save';
- $fields = $mod_function($mod_key, $mod_val, $sql, $data['feld'][$mod_key], $mod_key, $rubric_id);
+ $fields = $mod_function($mod_key, $mod_val, $query, $data['feld'][$mod_key], $mod_key, $rubric_id);
}
}
else
{
- while ($row = $sql->FetchRow())
+ while ($row = $query->FetchRow())
{
- array_push($fields, $row);
+ $fields[$row->Id] = $row;
}
}
- unset($sql);
+ unset($sql, $query);
$where = ($oper == 'UPDATE' ? 'WHERE Id = ' . $document_id : '');
$author = ($oper != 'UPDATE' ? 'document_author_id = ' . $_SESSION['user_id'] . ',' : '');
@@ -1518,8 +1593,13 @@ class AVE_Document
if ($logs)
reportLog(($oper=='INSERT'
? $AVE_Template->get_config_vars('DOC_SAVE_ADD')
- : $AVE_Template->get_config_vars('DOC_SAVE_EDIT'))
- . $AVE_Template->get_config_vars('DOC_SAVE_LOG_DOC') .' (' . $data['document_title'] . ' Id: ' . $document_id . ')');
+ : $AVE_Template->get_config_vars('DOC_SAVE_EDIT')) . $AVE_Template->get_config_vars('DOC_SAVE_LOG_DOC') .' (' . $data['document_title'] . ' Id: ' . $document_id . ')');
+
+ // Получаем ID полей в данной рубрике
+ $rubric_fields = $this->_get_rubric_fields($rubric_id);
+
+ // Получаем ID текстовых полей в данном документе
+ $document_text_fields = $this->_get_document_text_fields($document_id);
// Циклически обрабатываем поля документа
foreach ($fields as $k => $v)
@@ -1535,23 +1615,10 @@ class AVE_Document
? $data['feld'][$fld_id]
: $v->rubric_field_default);
- if (! $AVE_DB->Query("
- SELECT 1
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- Id = '" . $fld_id . "'
- AND
- rubric_id = '" . $rubric_id . "'
- LIMIT 1
- ")->NumRows())
- {
- continue;
- }
-
/* ------------------------------------------------------------------- */
- if(! is_array($fld_val))
+ // Если значение поля не является массивом
+ if (! is_array ($fld_val))
{
// Если запрещено использование php кода, тогда обнуляем данные поля
if (! check_permission('document_php'))
@@ -1565,23 +1632,13 @@ class AVE_Document
$fld_val = pretty_chars($fld_val);
}
- $field_rubric = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- Id = '" . $fld_id . "'
- ")->FetchRow();
-
// Отправляем полученные данные в функцию поля, в раздел "Save"
// для преобразования перед сохранением
- $func = 'get_field_' . $field_rubric->rubric_field_type;
+ $func = 'get_field_' . $rubric_fields[$fld_id]['rubric_field_type'];
- if (is_callable($func))
- {
+ // Если вызывается функция
+ if (is_callable ($func))
$fld_val = $func($fld_val, 'save', $fld_id, '', 0, $x, 0, 0, 0);
- }
//-- Собираем запрос к БД на добавление нового поля с его содержимым --//
@@ -1597,9 +1654,9 @@ class AVE_Document
? ''
: "rubric_field_id = '" . $fld_id . "', document_id = '" . $document_id . "',");
- $fval = (is_array($fld_val)
- ? serialize($fld_val)
- : ($fld_val));
+ $fval = is_array ($fld_val)
+ ? serialize ($fld_val)
+ : $fld_val;
$substr = 500;
@@ -1607,22 +1664,22 @@ class AVE_Document
$substr = 499;
// Сохраняем первые 500 символов
- $f_val_500 = mb_substr($fval, 0, $substr);
+ $f_val_500 = mb_substr ($fval, 0, $substr);
// Проверяем чтобы не было в конце слеша - \
if (mb_substr($f_val_500, 498, 1) == '\\')
$slash = true;
if ($slash)
- $f_val_500 = rtrim($f_val_500, '\\');
+ $f_val_500 = rtrim ($f_val_500, '\\');
$sql = "
$operator
SET
$insert
field_value = '" . $f_val_500 . "',
- field_number_value = '" . (($field_rubric->rubric_field_numeric)
- ? preg_replace('/[^\d.]/', '', $fld_val)
+ field_number_value = '" . (($rubric_fields[$fld_id]['rubric_field_numeric'])
+ ? preg_replace ('/[^\d.]/', '', $fld_val)
: 0) . "',
document_in_search = '" . $search . "'
$where
@@ -1636,27 +1693,21 @@ class AVE_Document
if (mb_strlen($fval) > $substr)
{
// Проверяем есть ли запись о поле в БД
- $check_field = $AVE_DB->Query("
- SELECT
- Id
- FROM
- " .PREFIX . "_document_fields_text
- WHERE
- document_id = '" . $document_id . "'
- AND
- rubric_field_id='" . $fld_id . "'
- ")->GetCell();
+ $check_field = false;
- $operator = ($check_field > 0
+ if (in_array ($fld_id, $document_text_fields))
+ $check_field = true;
+
+ $operator = ($check_field
? "UPDATE " . PREFIX . "_document_fields_text"
: "INSERT INTO " . PREFIX . "_document_fields_text"
);
- $where = ($check_field > 0
+ $where = ($check_field
? "WHERE document_id = '" . $document_id . "' AND rubric_field_id = '" . $fld_id . "'"
: '');
- $insert = ($check_field > 0
+ $insert = ($check_field
? ''
: "rubric_field_id = '" . $fld_id . "', document_id = '" . $document_id . "',");
@@ -1701,22 +1752,20 @@ class AVE_Document
doc_id = '" . $document_id . "'
");
- // Выполняем код рубрики, после сохранения
- if ($rubric_code)
- {
- eval ('?>' . $_rubric->rubric_code_end . '');
- }
-
// Запускаем триггер после сохранения
Hooks::trigger('DocumentAfterSave', array('rubric_id' => $rubric_id, 'document_id' => $document_id, 'data' => $data, 'field_module' => $data['field_module']));
+ // Выполняем код рубрики, после сохранения
+ if ($rubric_code)
+ eval ('?>' . $_rubric->rubric_code_end . '');
+
// Чистим кеш
$AVE_DB->clearcache('rub_' . $rubric_id);
$AVE_DB->clearcache('doc_' . $document_id);
$AVE_DB->clearcompile('doc_' . $document_id);
$AVE_DB->clearcacherequest('doc_' . $document_id);
- unset($_rubric);
+ unset ($_rubric, $fields);
// Дополнительные обработки
if ($generate)
@@ -1819,7 +1868,9 @@ class AVE_Document
$innavi = check_permission_acp('navigation_new') ? '&innavi=1' : '';
// Определяем статус документа
- $document_status = !empty($_REQUEST['document_status']) ? (int)$_REQUEST['document_status'] : '0';
+ $document_status = ! empty($_REQUEST['document_status'])
+ ? (int)$_REQUEST['document_status']
+ : '0';
// Если статус документа не определен
if (empty($document_status) && $_SESSION['user_group'] != 1)
@@ -1832,7 +1883,7 @@ class AVE_Document
// которые пользователь ввел в поля документа
foreach ($_POST['feld'] as $val)
{
- if (!empty($val))
+ if (! empty($val))
{
$newtext .= $val;
$newtext .= "\n---------------------\n";
@@ -1850,6 +1901,7 @@ class AVE_Document
$body_to_admin = str_replace('%N%', "\n", $body_to_admin);
$body_to_admin = str_replace('%TITLE%', stripslashes($_POST['document_title']), $body_to_admin);
$body_to_admin = str_replace('%USER%', "'" . $_SESSION['user_name'] . "'", $body_to_admin);
+
send_mail(
$system_mail,
$body_to_admin . $text,
@@ -2201,6 +2253,7 @@ class AVE_Document
groups.Id AS group_id,
rub.*,
rubric_field_default,
+ rubric_field_alias,
doc.field_value,
field_more.field_value as field_value_more
FROM
@@ -2263,6 +2316,7 @@ class AVE_Document
$fields_list[$group_id]['fields'][$field->Id]['Id'] = $field->Id;
$fields_list[$group_id]['fields'][$field->Id]['rubric_id'] = $row->rubric_id;
$fields_list[$group_id]['fields'][$field->Id]['rubric_field_title'] = $field->rubric_field_title;
+ $fields_list[$group_id]['fields'][$field->Id]['rubric_field_alias'] = $field->rubric_field_alias;
$fields_list[$group_id]['fields'][$field->Id]['rubric_field_description'] = $field->rubric_field_description;
$fields_list[$group_id]['fields'][$field->Id]['result'] = $field->field;
}
@@ -3693,10 +3747,47 @@ class AVE_Document
exit;
}
+ $search_query = $_SESSION['search_query'][$document_id] ? true : false;
+
+ $AVE_Template->assign('search_query', $search_query);
$AVE_Template->assign($document);
$AVE_Template->assign('content', $AVE_Template->fetch('documents/form_after.tpl'));
}
+
+ /**
+ * Редирект сохраненного документа на раздел, учитывая фильтр
+ *
+ */
+ function documentSaveRedirect()
+ {
+ $document_id = isset($_REQUEST['document_id'])
+ ? (int)$_REQUEST['document_id']
+ : 0;
+
+ // Если не пришел $documet_id
+ if (! $document_id)
+ {
+ header('Location:index.php?do=docs&cp=' . SESSION);
+ exit;
+ }
+
+ // Параметры поиска
+ $search_query = base64_decode($_SESSION['search_query'][$document_id]);
+
+ $search_query = $search_query
+ ? $search_query
+ : 'do=docs&cp=' . SESSION;
+
+ // Убираем из сессии данный документ
+ unset ($_SESSION['search_query'][$document_id]);
+
+ // Переходим на страницу
+ header('Location: index.php?' . $search_query);
+ exit;
+ }
+
+
/**
* Метод, предназначенный для смены автора документа
*
diff --git a/class/class.modules.php b/class/class.modules.php
index d4b285f..941a7db 100644
--- a/class/class.modules.php
+++ b/class/class.modules.php
@@ -1,406 +1,497 @@
moduleListGet();
-
- // Определяем директорию, где хранятся модули
- $d = dir(BASE_DIR . '/modules');
-
- // Циклически обрабатываем директории
- while (false !== ($entry = $d->read()))
- {
- if (substr($entry, 0, 1) == '.') continue;
-
- $module_dir = $d->path . '/' . $entry;
- if (!is_dir($module_dir)) continue;
-
- $modul = array();
- if (!(is_file($module_dir . '/module.php') && @include($module_dir . '/module.php')))
- {
- // Если не удалось подключить основной файл модуля module.php - Фиксируем ошибку
- $modules['errors'][] = $entry;
- continue;
- }
-
- // Дополняем массив с данными модуля
- $modul['permission'] = check_permission('mod_'. $modul['ModuleSysName']);
- $row = isset($modules_db[$modul['ModuleName']]) ? $modules_db[$modul['ModuleName']] : false;
-
- // установленные модули
- if ($row)
- {
- $modul['status'] = $row->ModuleStatus;
- $modul['id'] = $row->Id;
- $modul['need_update'] = ($row->ModuleVersion != $modul['ModuleVersion']);
- $modul['ModuleVersion'] = $row->ModuleVersion;
- $modul['template'] = ($row->ModuleTemplate ? $row->ModuleTemplate : 0);
- }
- // неустановленные модули
- else
- {
- $modul['status'] = false;
- $modul['id'] = $modul['ModuleSysName'];
- $modul['template'] = (!empty($modul['ModuleTemplate']) ? $modul['ModuleTemplate'] : '');
- }
- // записываем в массив
- $modules[$modul['ModuleSysName']] = $modul;
- }
- $d->Close();
- return $modules;
- }
-
-/**
- * Внешние методы
-*/
-
- /**
- * Метод, преданзначеный для выода модулей
+ * AVE.cms
+ *
+ * @package AVE.cms
+ * @version 3.x
+ * @filesource
+ * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
*/
- function moduleList()
+
+ class AVE_Module
{
- global $AVE_DB, $AVE_Template;
+ public $_modules = array();
- $assign = array(); // Массив для передачи в Smarty
- $errors = array(); // Массив с ошибками
-
- // Получаем список всех шаблонов
- $sql = $AVE_DB->Query("
- SELECT Id, template_title
- FROM " . PREFIX . "_templates
- ");
- while ($row = $sql->FetchRow())
+ function __construct()
{
- $assign['all_templates'][$row->Id] = htmlspecialchars($row->template_title, ENT_QUOTES);
+ $this->_modules = $this->getModules();
}
- $author_title = $AVE_Template->get_config_vars('MODULES_AUTHOR');
- $modules = $this->getModules();
- foreach ($modules as $module)
+ /**
+ * Метод, который обрабатывает все module.php и записывает как свойство класса списки модулей
+ */
+ function getModules()
{
- $module['info'] = $module['ModuleDescription'] . (!$module['ModuleAutor'] ? ' ' : "$author_title " . $module['ModuleAutor'] . " ") . '' . $module['ModuleCopyright'] . ' ';
- // установленные модули
- if ($module['status'] !== false)
+ $modules = array();
+
+ // Получаем из БД информацию о всех установленных модулях
+ $modules_db = $this->moduleListGet();
+
+ // Определяем директорию, где хранятся модули
+ $d = dir(BASE_DIR . '/modules');
+
+ // Циклически обрабатываем директории
+ while (false !== ($entry = $d->read()))
{
- $installed_modules[$module['ModuleName']] = $module;
- }
- // неустановленные модули
- else
- {
- $not_installed_modules[$module['ModuleName']] = $module;
+ if (substr($entry, 0, 1) == '.')
+ continue;
+
+ if (! is_dir(BASE_DIR . '/modules/' . $entry))
+ continue;
+
+ $AVE_Template = new AVE_Template(BASE_DIR . '/admin/templates');
+
+ $_no_lang_file = false;
+
+ // Языковой файл
+ $lang_file = BASE_DIR . '/modules/'.$entry.'/lang/' . $_SESSION['user_language'] . '.txt';
+
+ // Отдаем смарти переменные
+ if (file_exists($lang_file))
+ $AVE_Template->config_load($lang_file, 'name');
+ else
+ $_no_lang_file = true;
+
+ $module_dir = $d->path . '/' . $entry;
+
+ if (! is_dir($module_dir))
+ continue;
+
+ $module = array();
+
+ if (! (is_file($module_dir . '/info.php') && @include($module_dir . '/info.php')))
+ {
+ // Если не удалось подключить основной файл модуля module.php - Фиксируем ошибку
+ $modules['errors'][] = $entry;
+ continue;
+ }
+
+ $module['ModuleName'] = !$_no_lang_file
+ ? $AVE_Template->get_config_vars('MODULE_NAME')
+ : 'No name';
+
+ $module['ModuleDescription'] = !$_no_lang_file
+ ? $AVE_Template->get_config_vars('MODULE_DESCRIPTION')
+ : 'No description';
+
+ // Дополняем массив с данными модуля
+ $module['permission'] = check_permission('mod_'. $module['ModuleSysName']);
+
+ // Установлен/Не установлен по системному имени
+ $row = isset($modules_db[$module['ModuleSysName']])
+ ? $modules_db[$module['ModuleSysName']]
+ : false;
+
+ // установленные модули
+ if ($row)
+ {
+ $module['status'] = $row->ModuleStatus;
+ $module['id'] = $row->Id;
+ $module['need_update'] = ($row->ModuleVersion != $module['ModuleVersion']);
+ $module['template'] = ($row->ModuleTemplate ? $row->ModuleTemplate : 0);
+ $module['ModuleVersion'] = $row->ModuleVersion;
+ }
+ // неустановленные модули
+ else
+ {
+ $module['status'] = false;
+ $module['id'] = $module['ModuleSysName'];
+ $module['template'] = (! empty($module['ModuleTemplate']) ? $module['ModuleTemplate'] : '');
+ }
+
+ // записываем в массив
+ $modules[$module['ModuleSysName']] = $module;
+
+ unset ($module);
}
+
+ // Закрываем папку
+ $d->Close();
+
+ return $modules;
}
- !empty($installed_modules) ? ksort($installed_modules) : $installed_modules = '';
- !empty($not_installed_modules) ? ksort($not_installed_modules) : $not_installed_modules = '';
- $assign['installed_modules'] = $installed_modules;
- $assign['not_installed_modules'] = $not_installed_modules;
-
- // Массив с ошибками
- if(!empty($modules['errors'])){
- foreach ($modules['errors'] as $error)
- {
- $assign['errors'][] = $AVE_Template->get_config_vars('MODULES_ERROR') . $error;
- }
- }
- // Передаем данные в шаблон и отображаем страницу со списком модулей
- $AVE_Template->assign($assign);
- $AVE_Template->assign('content', $AVE_Template->fetch('modules/modules.tpl'));
- }
-
- /**
- * Метод, предназначенный для обновления в БД информации о шаблонах модулей
- *
- */
- function moduleOptionsSave()
- {
- global $AVE_DB;
-
- // Циклически обрабатываем массив с информацией о шаблонах модулей
- foreach ($_POST['Template'] as $id => $template_id)
+ /**
+ * Метод, преданзначеный для выода модулей
+ *
+ */
+ function moduleList()
{
- // Обновление информации о шаблоне модуля
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_module
- SET ModuleTemplate = '" . (int)$template_id . "'
- WHERE Id = '" . (int)$id . "'
+ global $AVE_DB, $AVE_Template;
+
+ $assign = array(); // Массив для передачи в Smarty
+ $errors = array(); // Массив с ошибками
+
+ // Получаем список всех шаблонов
+ $sql = $AVE_DB->Query("
+ SELECT
+ Id,
+ template_title
+ FROM
+ " . PREFIX . "_templates
");
- }
- // Выполянем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
- }
+ while ($row = $sql->FetchRow())
+ $assign['all_templates'][$row->Id] = htmlspecialchars($row->template_title, ENT_QUOTES);
- /**
- * Метод, предназанченный для установки или переустановки модуля
- *
- */
- function moduleInstall()
- {
- global $AVE_DB, $AVE_Template;
+ // Заголовок: Автор модуля
+ $author_title = $AVE_Template->get_config_vars('MODULES_AUTHOR');
- // Получаем данные модуля
- $modules = $this->getModules();
- $modul = $modules[MODULE_PATH];
+ // Получаем список всех модулей
+ $modules = $this->_modules;
- // Удаляем информацию о модуле в таблице module
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_module
- WHERE ModuleSysName = '" . MODULE_PATH . "'
- ");
-
- // Определяем, имеет ли модуль возможность настройки в Панели управления
- $modul['ModuleAdminEdit'] = (!empty($modul['ModuleAdminEdit'])) ? $modul['ModuleAdminEdit'] : 0;
-
- // Определяем, имеет ли модуль возможность смены шаблона
- $modul['ModuleTemplate'] = ($modul['ModuleTemplate']) ? $modul['ModuleTemplate'] : 0;
-
- // Добавляем информацию о модуле в таблицу module
- $AVE_DB->Query("
- INSERT " . PREFIX . "_module
- SET
- ModuleName = '" . $modul['ModuleName'] . "',
- ModuleStatus = '1',
- ModuleAveTag = '" . $modul['ModuleAveTag'] . "',
- ModulePHPTag = '" . $modul['ModulePHPTag'] . "',
- ModuleFunction = '" . $modul['ModuleFunction'] . "',
- ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "',
- ModuleSysName = '" . MODULE_PATH . "',
- ModuleVersion = '" . $modul['ModuleVersion'] . "',
- ModuleTemplate = '" . $modul['ModuleTemplate'] . "',
- ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "'
- ");
-
- // Подключаем файл с запросами к БД для данного модуля
- $module_sql_deinstall = array();
- $module_sql_install = array();
- $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
- if (is_file($sql_file) && @include($sql_file))
- {
- // Выполняем запросы удаления таблиц модуля
- // из массива $module_sql_deinstall файла sql.php
- foreach ($module_sql_deinstall as $sql)
+ foreach ($modules as $module)
{
- $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ $module['info'] = $module['ModuleDescription'] . (! $module['ModuleAutor']
+ ? ' '
+ : "$author_title " . $module['ModuleAutor'] . " ") . '' . $module['ModuleCopyright'] . ' ';
+ // установленные модули
+ if ($module['status'] !== false)
+ $installed_modules[$module['ModuleSysName']] = $module;
+ // неустановленные модули
+ else
+ $not_installed_modules[$module['ModuleSysName']] = $module;
}
- // Выполняем запросы создания таблиц и данных модуля
- // из массива $module_sql_install файла sql.php
- foreach ($module_sql_install as $sql)
+ ! empty($installed_modules)
+ ? ksort($installed_modules)
+ : $installed_modules = '';
+
+ ! empty($not_installed_modules)
+ ? ksort($not_installed_modules)
+ : $not_installed_modules = '';
+
+ $assign['installed_modules'] = $installed_modules;
+ $assign['not_installed_modules'] = $not_installed_modules;
+
+ // Массив с ошибками
+ if (! empty($modules['errors']))
{
- $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ foreach ($modules['errors'] as $error)
+ {
+ $assign['errors'][] = $AVE_Template->get_config_vars('MODULES_ERROR') . $error;
+ }
}
+
+ // Передаем данные в шаблон и отображаем страницу со списком модулей
+ $AVE_Template->assign($assign);
+ $AVE_Template->assign('content', $AVE_Template->fetch('modules/modules.tpl'));
}
- // Сохраняем системное сообщение в журнал
- ($_REQUEST['action'] == "reinstall") ? reportLog($AVE_Template->get_config_vars('MODULES_ACTION_REINSTALL') . ' (' . $modul['ModuleName'] . ')') : reportLog($AVE_Template->get_config_vars('MODULES_ACTION_INSTALL') . ' (' . $modul['ModuleName'] . ')');
- // Выполняем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
- }
- /**
- * Метод, предназначенный для обновления модуля при увеличении номера версии модуля
- *
- */
- function moduleUpdate()
- {
- global $AVE_DB, $AVE_Template;
-
- // Подключаем файл с запросами к БД для данного модуля
- $module_sql_update = array();
- $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
- $mod_file = BASE_DIR . '/modules/' . MODULE_PATH . '/module.php';
- if (file_exists($mod_file) && file_exists($sql_file))
+ /**
+ * Метод получения списка модулей
+ *
+ * @param int $status статус возвращаемых модулей
+ * 1 - активные модули
+ * 0 - неактивные модули
+ * если не указано возвращает модули без учета статуса
+ * @return array
+ */
+ function moduleListGet($status = null)
{
- include($mod_file);
- include($sql_file);
- // Выполняем запросы обновления модуля
- // из массива $module_sql_update файла sql.php
- foreach ($module_sql_update as $sql)
+ global $AVE_DB;
+
+ $modules = array();
+
+ // Условие, определяющее статус документа для запроса к БД
+ $where_status = ($status !== null)
+ ? "WHERE ModuleStatus = '" . (int)$status . "'"
+ : '';
+
+ // Выполняем запрос к БД и получаем список документов,
+ // согласно статусу, либо все модули, если статус не указан
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_module
+ " . $where_status . "
+ ORDER BY
+ ModuleName ASC
+ ");
+
+ while ($row = $sql->FetchRow())
+ $modules[$row->ModuleSysName] = $row;
+
+ // Возвращаем список модулей
+ return $modules;
+ }
+
+
+ /**
+ * Метод, предназначенный для обновления в БД информации о шаблонах модулей
+ *
+ */
+ function moduleOptionsSave()
+ {
+ global $AVE_DB;
+
+ // Циклически обрабатываем массив с информацией о шаблонах модулей
+ foreach ($_POST['Template'] as $id => $template_id)
{
- $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ // Обновление информации о шаблоне модуля
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_module
+ SET
+ ModuleTemplate = '" . (int)$template_id . "'
+ WHERE
+ Id = '" . (int)$id . "'
+ ");
}
+
+ // Выполянем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
}
- // Обновляем модуль, если в нем не применяется (отсутствует) файл sql.php
- elseif (file_exists($mod_file) && file_exists($sql_file) === false)
+
+ /**
+ * Метод, предназанченный для установки или переустановки модуля
+ *
+ */
+ function moduleInstall()
{
- include($mod_file);
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_module
- SET
- ModuleName = '" . $modul['ModuleName'] . "',
- ModuleStatus = '1',
- ModuleAveTag = '" . $modul['ModuleAveTag'] . "',
- ModulePHPTag = '" . $modul['ModulePHPTag'] . "',
- ModuleFunction = '" . $modul['ModuleFunction'] . "',
- ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "',
- ModuleSysName = '" . MODULE_PATH . "',
- ModuleVersion = '" . $modul['ModuleVersion'] . "',
- ModuleTemplate = '" . $modul['ModuleTemplate'] . "',
- ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "'
- WHERE
- ModuleSysName = '" . MODULE_PATH . "'
- ");
- }
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')');
+ global $AVE_DB, $AVE_Template;
- // Выполянем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
- }
+ // Получаем данные модуля
+ $modules = $this->_modules;
- /**
- * Метод, предназанченный для удаление модуля
- *
- */
- function moduleDelete()
- {
- global $AVE_DB, $AVE_Template;
+ $modul = $modules[MODULE_PATH];
- // Подключаем файл с запросами к БД для данного модуля
- $module_sql_deinstall = array();
- $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
- if (is_file($sql_file) && @include($sql_file))
- {
- // Выполняем запросы удаления таблиц модуля
- // из массива $module_sql_deinstall файла sql.php
- foreach ($module_sql_deinstall as $sql)
+ // Удаляем информацию о модуле в таблице module
+ $AVE_DB->Query("
+ DELETE
+ FROM
+ " . PREFIX . "_module
+ WHERE
+ ModuleSysName = '" . MODULE_PATH . "'
+ ");
+
+ // Определяем, имеет ли модуль возможность настройки в Панели управления
+ $modul['ModuleAdminEdit'] = (!empty($modul['ModuleAdminEdit']))
+ ? $modul['ModuleAdminEdit']
+ : 0;
+
+ // Определяем, имеет ли модуль возможность смены шаблона
+ $modul['ModuleTemplate'] = ($modul['ModuleTemplate'])
+ ? $modul['ModuleTemplate']
+ : 0;
+
+ // Добавляем информацию о модуле в таблицу module
+ $AVE_DB->Query("
+ INSERT INTO
+ " . PREFIX . "_module
+ SET
+ ModuleName = '" . $modul['ModuleName'] . "',
+ ModuleStatus = '1',
+ ModuleAveTag = '" . $modul['ModuleAveTag'] . "',
+ ModulePHPTag = '" . $modul['ModulePHPTag'] . "',
+ ModuleFunction = '" . $modul['ModuleFunction'] . "',
+ ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "',
+ ModuleSysName = '" . MODULE_PATH . "',
+ ModuleVersion = '" . $modul['ModuleVersion'] . "',
+ ModuleTemplate = '" . $modul['ModuleTemplate'] . "',
+ ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "'
+ ");
+
+ // Подключаем файл с запросами к БД для данного модуля
+ $module_sql_deinstall = array();
+ $module_sql_install = array();
+ $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
+
+ if (is_file($sql_file) && @include($sql_file))
{
- $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ // Выполняем запросы удаления таблиц модуля
+ // из массива $module_sql_deinstall файла sql.php
+ foreach ($module_sql_deinstall as $sql)
+ {
+ $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ }
+
+ // Выполняем запросы создания таблиц и данных модуля
+ // из массива $module_sql_install файла sql.php
+ foreach ($module_sql_install as $sql)
+ {
+ $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ }
}
+ // Сохраняем системное сообщение в журнал
+ ($_REQUEST['action'] == "reinstall")
+ ? reportLog($AVE_Template->get_config_vars('MODULES_ACTION_REINSTALL') . ' (' . $modul['ModuleName'] . ')')
+ : reportLog($AVE_Template->get_config_vars('MODULES_ACTION_INSTALL') . ' (' . $modul['ModuleName'] . ')');
+
+ // Выполняем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
}
- // Удаляем информацию о модуле в таблице module
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_module
- WHERE ModuleSysName = '" . MODULE_PATH . "'
- ");
-
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('MODULES_ACTION_DELETE') .' (' . MODULE_PATH . ')');
-
- // Выполянем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
- }
-
- /**
- * Метод, предназначенный для отключения/включение модуля в Панели управления
- *
- */
- function moduleStatusChange()
- {
- global $AVE_DB, $AVE_Template;
-
- $status = $AVE_DB->Query("
- SELECT ModuleName, ModuleStatus FROM " . PREFIX . "_module
- WHERE ModuleSysName = '" . MODULE_PATH . "'
- ")->FetchRow();
-
- $ModuleStatus = ($status->ModuleStatus == "0" || $status->ModuleStatus == NULL) ? "1" : "0";
-
- // Выполняем запрос к БД на смену статуса модуля
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_module
- SET
- ModuleStatus = '".$ModuleStatus."'
- WHERE
- ModuleSysName = '" . MODULE_PATH . "'
- ");
-
- // Сохраняем системное сообщение в журнал
- reportLog((($ModuleStatus == "0") ? $AVE_Template->get_config_vars('MODULES_ACTION_OFFLINE') : $AVE_Template->get_config_vars('MODULES_ACTION_ONLINE')) . ' (' . $status->ModuleName . ')');
-
- // Выполняем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
- }
-
- /**
- * Метод получения списка модулей
- *
- * @param int $status статус возвращаемых модулей
- * 1 - активные модули
- * 0 - неактивные модули
- * если не указано возвращает модули без учета статуса
- * @return array
- */
- function moduleListGet($status = null)
- {
- global $AVE_DB;
-
- $modules = array();
-
- // Условие, определяющее статус документа для запроса к БД
- $where_status = ($status !== null) ? "WHERE ModuleStatus = '" . (int)$status . "'" : '';
-
- // Выполняем запрос к БД и получаем список документов,
- // согласно статусу, либо все модули, если статус не указан
- $sql = $AVE_DB->Query("
- SELECT * FROM " . PREFIX . "_module
- " . $where_status . "
- ORDER BY ModuleName ASC
- ");
- while ($row = $sql->FetchRow())
+ /**
+ * Метод, предназначенный для обновления модуля при увеличении номера версии модуля
+ *
+ */
+ function moduleUpdate()
{
- $modules[$row->ModuleName] = $row;
+ global $AVE_DB, $AVE_Template;
+
+ // Подключаем файл с запросами к БД для данного модуля
+ $module_sql_update = array();
+
+ $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
+
+ $mod_file = BASE_DIR . '/modules/' . MODULE_PATH . '/module.php';
+
+ if (file_exists($mod_file) && file_exists($sql_file))
+ {
+ include($mod_file);
+ include($sql_file);
+ // Выполняем запросы обновления модуля
+ // из массива $module_sql_update файла sql.php
+ foreach ($module_sql_update as $sql)
+ {
+ $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ }
+ }
+ // Обновляем модуль, если в нем не применяется (отсутствует) файл sql.php
+ elseif (file_exists($mod_file) && file_exists($sql_file) === false)
+ {
+ include($mod_file);
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_module
+ SET
+ ModuleName = '" . $modul['ModuleName'] . "',
+ ModuleStatus = '1',
+ ModuleAveTag = '" . $modul['ModuleAveTag'] . "',
+ ModulePHPTag = '" . $modul['ModulePHPTag'] . "',
+ ModuleFunction = '" . $modul['ModuleFunction'] . "',
+ ModuleIsFunction = '" . $modul['ModuleIsFunction'] . "',
+ ModuleSysName = '" . MODULE_PATH . "',
+ ModuleVersion = '" . $modul['ModuleVersion'] . "',
+ ModuleTemplate = '" . $modul['ModuleTemplate'] . "',
+ ModuleAdminEdit = '" . $modul['ModuleAdminEdit'] . "'
+ WHERE
+ ModuleSysName = '" . MODULE_PATH . "'
+ ");
+ }
+ // Сохраняем системное сообщение в журнал
+ reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')');
+
+ // Выполянем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
}
- // Возвращаем список модулей
- return $modules;
- }
- function moduleRemove($dir)
- {
- global $AVE_DB, $AVE_Template;
+ /**
+ * Метод, предназанченный для удаление модуля
+ *
+ */
+ function moduleDelete()
+ {
+ global $AVE_DB, $AVE_Template;
- $directory = BASE_DIR . '/modules/' . $dir;
+ // Подключаем файл с запросами к БД для данного модуля
+ $module_sql_deinstall = array();
- $files = glob($directory . '*', GLOB_MARK);
- foreach($files as $file){
- if(substr($file, -1) == '/')
- moduleRemove($file);
- else
- unlink($file);
+ $sql_file = BASE_DIR . '/modules/' . MODULE_PATH . '/sql.php';
+
+ if (is_file($sql_file) && @include($sql_file))
+ {
+ // Выполняем запросы удаления таблиц модуля
+ // из массива $module_sql_deinstall файла sql.php
+ foreach ($module_sql_deinstall as $sql)
+ {
+ $AVE_DB->Query(str_replace('CPPREFIX', PREFIX, $sql));
+ }
+ }
+
+ // Удаляем информацию о модуле в таблице module
+ $AVE_DB->Query("
+ DELETE
+ FROM
+ " . PREFIX . "_module
+ WHERE
+ ModuleSysName = '" . MODULE_PATH . "'
+ ");
+
+ // Сохраняем системное сообщение в журнал
+ reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_DELETE') .' (' . MODULE_PATH . ')');
+
+ // Выполянем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
}
- rrmdir($directory);
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('MODULES_ACTION_REMOVE') . ' (' . $dir . ')');
+ /**
+ * Метод, предназначенный для отключения/включение модуля в Панели управления
+ *
+ */
+ function moduleStatusChange()
+ {
+ global $AVE_DB, $AVE_Template;
- // Выполянем обновление страницы со списком модулей
- header('Location:index.php?do=modules&cp=' . SESSION);
- exit;
+ $status = $AVE_DB->Query("
+ SELECT
+ ModuleName,
+ ModuleStatus
+ FROM
+ " . PREFIX . "_module
+ WHERE
+ ModuleSysName = '" . MODULE_PATH . "'
+ ")->FetchRow();
+
+ $ModuleStatus = ($status->ModuleStatus == "0" || $status->ModuleStatus == NULL)
+ ? "1"
+ : "0";
+
+ // Выполняем запрос к БД на смену статуса модуля
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_module
+ SET
+ ModuleStatus = '".$ModuleStatus."'
+ WHERE
+ ModuleSysName = '" . MODULE_PATH . "'
+ ");
+
+ // Сохраняем системное сообщение в журнал
+ reportLog ((($ModuleStatus == "0")
+ ? $AVE_Template->get_config_vars('MODULES_ACTION_OFFLINE')
+ : $AVE_Template->get_config_vars('MODULES_ACTION_ONLINE')) . ' (' . $status->ModuleName . ')');
+
+ // Выполняем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
+ }
+
+
+ function moduleRemove($dir)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $directory = BASE_DIR . '/modules/' . $dir;
+
+ $files = glob($directory . '*', GLOB_MARK);
+
+ foreach ($files as $file)
+ {
+ if(substr($file, -1) == '/')
+ moduleRemove($file);
+ else
+ unlink($file);
+ }
+
+ rrmdir ($directory);
+
+ // Сохраняем системное сообщение в журнал
+ reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_REMOVE') . ' (' . $dir . ')');
+
+ // Выполянем обновление страницы со списком модулей
+ header('Location:index.php?do=modules&cp=' . SESSION);
+ exit;
+ }
}
-}
-
?>
\ No newline at end of file
diff --git a/class/class.navigation.php b/class/class.navigation.php
index 93d7a88..f30e777 100644
--- a/class/class.navigation.php
+++ b/class/class.navigation.php
@@ -193,7 +193,8 @@
// Выполняем запрос к БД и получаем всю информацию о данном меню
$row = $AVE_DB->Query("
- SELECT *
+ SELECT
+ *
FROM
" . PREFIX . "_navigation
WHERE
@@ -241,7 +242,8 @@
");
//-- Стираем кеш навигации
- $this->clearCahe($navigation_id, $_REQUEST['alias']);
+ $this->clearCache($navigation_id, $_REQUEST['alias']);
+ $this->clearCacheId($navigation_id, $_REQUEST['alias']);
if ($sql === false)
{
@@ -362,7 +364,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($navigation_id, $sql->alias);
+ $this->clearCache($navigation_id, $sql->alias);
//-- Выполняем запрос к БД на удаление общей информации и шаблона оформления меню
$AVE_DB->Query("DELETE FROM " . PREFIX . "_navigation WHERE navigation_id = '" . $navigation_id . "'");
@@ -630,7 +632,7 @@
")->GetCell();
//-- Стираем кеш навигации
- $this->clearCahe($_REQUEST['navigation_id'], $alias);
+ $this->clearCache($_REQUEST['navigation_id'], $alias);
$AVE_Template->assign('select_tpl', 'navigation/select.tpl');
$AVE_Template->assign('items', $items);
@@ -714,7 +716,7 @@
")->GetCell();
//-- Стираем кеш навигации
- $this->clearCahe($_REQUEST['navigation_id'], $alias);
+ $this->clearCache($_REQUEST['navigation_id'], $alias);
}
else
{
@@ -756,7 +758,7 @@
")->GetCell();
//-- Стираем кеш навигации
- $this->clearCahe($_REQUEST['navigation_id'], $alias);
+ $this->clearCache($_REQUEST['navigation_id'], $alias);
}
$message = 'Пункт меню успешно сохранен';
@@ -939,7 +941,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
// Выполняем обновление страницы
header('Location:' . get_referer_admin_link());
@@ -995,7 +997,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
// Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('NAVI_REPORT_ACT') . " (id: $row->navigation_item_id)");
@@ -1054,7 +1056,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
// Сохраняем системное сообщение в журнал
reportLog($AVE_Template->get_config_vars('NAVI_REPORT_DEACT') . " (id: $row->navigation_item_id)");
@@ -1103,7 +1105,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
$AVE_Template->assign('item', $item);
$AVE_Template->assign('content', $AVE_Template->fetch('navigation/item.tpl'));
@@ -1152,7 +1154,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
if (isAjax())
{
@@ -1248,7 +1250,7 @@
")->FetchRow();
//-- Стираем кеш навигации
- $this->clearCahe($nav->navigation_id, $nav->alias);
+ $this->clearCache($nav->navigation_id, $nav->alias);
echo json_encode(
array(
@@ -1260,7 +1262,7 @@
}
- function clearCahe($id, $alias = '')
+ function clearCache($id, $alias = '')
{
if (file_exists(BASE_DIR . '/cache/sql/nav/template-' . $id . '.cache'))
unlink(BASE_DIR . '/cache/sql/nav/template-' . $id . '.cache');
@@ -1275,5 +1277,27 @@
unlink(BASE_DIR . '/cache/sql/nav/items-' . $alias . '.cache');
}
+
+ function clearCacheId($id, $alias = '')
+ {
+ $dir_id = BASE_DIR . '/cache/sql/nav_' . $id;
+ $dir_alias = BASE_DIR . '/cache/sql/nav_' . $alias;
+
+ if (file_exists($dir_id))
+ {
+ foreach (glob($dir_id . '/*') as $file)
+ {
+ unlink($file);
+ }
+ }
+
+ if (file_exists($dir_alias))
+ {
+ foreach (glob($dir_alias . '/*') as $file)
+ {
+ unlink($file);
+ }
+ }
+ }
}
?>
diff --git a/class/class.request.php b/class/class.request.php
index 7479c20..1c5fe0f 100644
--- a/class/class.request.php
+++ b/class/class.request.php
@@ -476,9 +476,11 @@ class AVE_Request
$sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$_REQUEST['rubric_id']);
+ $AVE_DB->clear_request($request_id);
+
while ($row = $sql->FetchRow())
{
- $AVE_DB->clearcacherequest('doc_'.$row->Id);
+ $AVE_DB->clearcacherequest('doc_' . $row->Id);
}
// Сохраняем системное сообщение в журнал
@@ -813,11 +815,15 @@ class AVE_Request
// require(BASE_DIR . '/functions/func.parserequest.php');
request_get_condition_sql_string($request_id, true);
- if (! isAjax()){
+ if (! isAjax())
+ {
header('Location:index.php?do=request&action=conditions&rubric_id=' . $_REQUEST['rubric_id'] . '&Id=' . $request_id . '&cp=' . SESSION);
exit;
- }else{
- if (!$message){
+ }
+ else
+ {
+ if (! $message)
+ {
$message = $AVE_Template->get_config_vars('REQUEST_COND_NEW_SUC');
$header = $AVE_Template->get_config_vars('REQUEST_SUCCESS');
$theme = 'accept';
diff --git a/class/class.rubs.php b/class/class.rubs.php
index 410de9a..56d3e3d 100755
--- a/class/class.rubs.php
+++ b/class/class.rubs.php
@@ -1,510 +1,1157 @@
Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields_group
- WHERE
- rubric_id = '" . $rubric_id . "'
- ORDER BY
- group_position ASC
- ");
-
- $groups = array();
-
- while($row = $sql->FetchRow())
- {
- array_push($groups, $row);
- }
-
- return $groups;
- }
-
-
-/**
- * ВНЕШНИЕ МЕТОДЫ
- */
-
- /**
- * Вывод списка рубрик
+ * @package AVE.cms
+ * @version 3.x
+ * @filesource
+ * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
*/
- function rubricList()
- {
- global $AVE_DB, $AVE_Template;
-
- $rubrics = array();
- $num = $AVE_DB->Query("SELECT COUNT(*) FROM " . PREFIX . "_rubrics")->GetCell();
-
- $page_limit = $this->_limit;
- $pages = ceil($num / $page_limit);
- $set_start = get_current_page() * $page_limit - $page_limit;
-
- if ($num > $page_limit)
- {
- $page_nav = " {t} ";
- $page_nav = get_pagination($pages, 'page', $page_nav);
- $AVE_Template->assign('page_nav', $page_nav);
- }
-
- $sql = $AVE_DB->Query("
- SELECT
- rub.*,
- COUNT(doc.Id) AS doc_count,
- (SELECT count(*) FROM " . PREFIX . "_rubric_fields AS fld WHERE fld.rubric_id = rub.Id) AS fld_count,
- (SELECT count(*) FROM " . PREFIX . "_rubric_templates AS tmpls WHERE tmpls.rubric_id = rub.Id) AS tmpls_count
- FROM
- " . PREFIX . "_rubrics AS rub
- LEFT JOIN
- " . PREFIX . "_documents AS doc
- ON rubric_id = rub.Id
- GROUP BY rub.Id
- ORDER BY rub.rubric_position
- LIMIT " . $set_start . "," . $page_limit
- );
-
- while ($row = $sql->FetchRow())
- {
- array_push($rubrics, $row);
- }
-
- $AVE_Template->assign('rubrics', $rubrics);
- }
/**
- * создание рубрики
- *
+ * Класс работы с рубриками
*/
- function rubricNew()
+ class AVE_Rubric
{
- global $AVE_DB, $AVE_Template;
- switch ($_REQUEST['sub'])
+ /**
+ * СВОЙСТВА
+ */
+
+ /**
+ * Количество рубрик на странице
+ *
+ * @public int
+ */
+ public $_limit = 30;
+
+ /**
+ * ВНУТРЕННИЕ МЕТОДЫ
+ */
+
+ function get_rubric_fields_group($rubric_id)
{
- case '':
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/rubnew.tpl'));
- break;
- case 'save':
- $errors = array();
+ global $AVE_DB, $AVE_Template;
- if (empty($_POST['rubric_title']))
- {
- array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_NAME'));
- }
- else
- {
- $name_exist = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_rubrics
- WHERE rubric_title = '" . $_POST['rubric_title'] . "'
- LIMIT 1
- ")->NumRows();
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_rubric_fields_group
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ ORDER BY
+ group_position ASC
+ ");
- if ($name_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NAME_EXIST'));
+ $groups = array();
- if (!empty($_POST['rubric_alias']))
+ while($row = $sql->FetchRow())
+ {
+ array_push($groups, $row);
+ }
+
+ return $groups;
+ }
+
+
+ /**
+ * ВНЕШНИЕ МЕТОДЫ
+ */
+
+ /**
+ * Вывод списка рубрик
+ *
+ */
+ function rubricList()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubrics = array();
+ $num = $AVE_DB->Query("SELECT COUNT(*) FROM " . PREFIX . "_rubrics")->GetCell();
+
+ $page_limit = $this->_limit;
+ $pages = ceil($num / $page_limit);
+ $set_start = get_current_page() * $page_limit - $page_limit;
+
+ if ($num > $page_limit)
+ {
+ $page_nav = " {t} ";
+ $page_nav = get_pagination($pages, 'page', $page_nav);
+ $AVE_Template->assign('page_nav', $page_nav);
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rub.*,
+ COUNT(doc.Id) AS doc_count,
+ (SELECT count(*) FROM " . PREFIX . "_rubric_fields AS fld WHERE fld.rubric_id = rub.Id) AS fld_count,
+ (SELECT count(*) FROM " . PREFIX . "_rubric_templates AS tmpls WHERE tmpls.rubric_id = rub.Id) AS tmpls_count
+ FROM
+ " . PREFIX . "_rubrics AS rub
+ LEFT JOIN
+ " . PREFIX . "_documents AS doc
+ ON rubric_id = rub.Id
+ GROUP BY rub.Id
+ ORDER BY rub.rubric_position
+ LIMIT " . $set_start . "," . $page_limit
+ );
+
+ while ($row = $sql->FetchRow())
+ {
+ array_push($rubrics, $row);
+ }
+
+ $AVE_Template->assign('rubrics', $rubrics);
+ }
+
+ /**
+ * создание рубрики
+ *
+ */
+ function rubricNew()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ switch ($_REQUEST['sub'])
+ {
+ case '':
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/rubnew.tpl'));
+ break;
+
+ case 'save':
+ $errors = array();
+
+ if (empty($_POST['rubric_title']))
{
- if (preg_match(TRANSLIT_URL ? '/[^\%HYa-z0-9\/_-]+/' : '/[^\%HYa-zа-яА-Яёїєі0-9\/_-]+/u', $_POST['rubric_alias']))
+ array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_NAME'));
+ }
+ else
+ {
+ $name_exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubrics
+ WHERE rubric_title = '" . $_POST['rubric_title'] . "'
+ LIMIT 1
+ ")->NumRows();
+
+ if ($name_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NAME_EXIST'));
+
+ if (!empty($_POST['rubric_alias']))
{
- array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_BAD_CHAR'));
+ if (preg_match(TRANSLIT_URL ? '/[^\%HYa-z0-9\/_-]+/' : '/[^\%HYa-zа-яА-Яёїєі0-9\/_-]+/u', $_POST['rubric_alias']))
+ {
+ array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_BAD_CHAR'));
+ }
+ else
+ {
+ $prefix_exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubrics
+ WHERE rubric_alias = '" . $_POST['rubric_alias'] . "'
+ LIMIT 1
+ ")->NumRows();
+
+ if ($prefix_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_EXIST'));
+ }
+ }
+
+ if (!empty($errors))
+ {
+ $AVE_Template->assign('errors', $errors);
+ $AVE_Template->assign('templates', get_all_templates());
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/rubnew.tpl'));
}
else
{
- $prefix_exist = $AVE_DB->Query("
- SELECT 1
+ $position = (int)$AVE_DB->Query("
+ SELECT MAX(rubric_position)
FROM " . PREFIX . "_rubrics
- WHERE rubric_alias = '" . $_POST['rubric_alias'] . "'
- LIMIT 1
- ")->NumRows();
+ ")->GetCell() + 1;
- if ($prefix_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_EXIST'));
- }
- }
-
- if (!empty($errors))
- {
- $AVE_Template->assign('errors', $errors);
- $AVE_Template->assign('templates', get_all_templates());
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/rubnew.tpl'));
- }
- else
- {
- $position = (int)$AVE_DB->Query("
- SELECT MAX(rubric_position)
- FROM " . PREFIX . "_rubrics
- ")->GetCell() + 1;
-
- $AVE_DB->Query("
- INSERT " . PREFIX . "_rubrics
- SET
- rubric_title = '" . $_POST['rubric_title'] . "',
- rubric_alias = '" . $_POST['rubric_alias'] . "',
- rubric_template_id = '" . intval($_POST['rubric_template_id']) . "',
- rubric_author_id = '" . $_SESSION['user_id'] . "',
- rubric_created = '" . time() . "',
- rubric_position = '" . $position . "'
- ");
-
- $iid = $AVE_DB->InsertId();
-
- // Выставляем всем право на просмотр рубрики, админу - все права
- $sql_user = $AVE_DB->Query("
- SELECT
- grp.*,
- COUNT(usr.Id) AS UserCount
- FROM
- " . PREFIX . "_user_groups AS grp
- LEFT JOIN
- " . PREFIX . "_users AS usr
- ON usr.user_group = grp.user_group
- GROUP BY grp.user_group
- ");
- while ($row = $sql_user->FetchRow())
- {
$AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_permissions
+ INSERT " . PREFIX . "_rubrics
SET
- rubric_id = '" . $iid . "',
- user_group_id = '" . $row->user_group . "',
- rubric_permission = '". (($row->user_group == 1) ? "alles|docread|new|newnow|editown|editall|delrev" : "docread")."'
+ rubric_title = '" . $_POST['rubric_title'] . "',
+ rubric_alias = '" . $_POST['rubric_alias'] . "',
+ rubric_template_id = '" . intval($_POST['rubric_template_id']) . "',
+ rubric_author_id = '" . $_SESSION['user_id'] . "',
+ rubric_created = '" . time() . "',
+ rubric_position = '" . $position . "'
");
+
+ $iid = $AVE_DB->InsertId();
+
+ // Выставляем всем право на просмотр рубрики, админу - все права
+ $sql_user = $AVE_DB->Query("
+ SELECT
+ grp.*,
+ COUNT(usr.Id) AS UserCount
+ FROM
+ " . PREFIX . "_user_groups AS grp
+ LEFT JOIN
+ " . PREFIX . "_users AS usr
+ ON usr.user_group = grp.user_group
+ GROUP BY grp.user_group
+ ");
+ while ($row = $sql_user->FetchRow())
+ {
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_permissions
+ SET
+ rubric_id = '" . $iid . "',
+ user_group_id = '" . $row->user_group . "',
+ rubric_permission = '". (($row->user_group == 1) ? "alles|docread|new|newnow|editown|editall|delrev" : "docread")."'
+ ");
+ }
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_NEW_RUBRIC') . ' - ' . stripslashes(htmlspecialchars($_POST['rubric_title'], ENT_QUOTES)) . ' (id: '.$iid.')');
+
+ header('Location:index.php?do=rubs&action=edit&Id=' . $iid . '&cp=' . SESSION);
+ exit;
+ }
+ }
+ break;
+ }
+ }
+
+ /**
+ * Запись настроек рубрики
+ *
+ */
+ function quickSave()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ if (check_permission_acp('rubric_edit'))
+ {
+ foreach ($_POST['rubric_title'] as $rubric_id => $rubric_title)
+ {
+ if (!empty($rubric_title))
+ {
+ $set_rubric_title = '';
+ $set_rubric_alias = '';
+
+ $name_exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubrics
+ WHERE
+ rubric_title = '" . $rubric_title . "'
+ AND
+ Id != '" . $rubric_id . "'
+ LIMIT 1
+ ")->NumRows();
+
+ if (!$name_exist)
+ {
+ $set_rubric_title = "rubric_title = '" . $rubric_title . "',";
}
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_NEW_RUBRIC') . ' - ' . stripslashes(htmlspecialchars($_POST['rubric_title'], ENT_QUOTES)) . ' (id: '.$iid.')');
-
- header('Location:index.php?do=rubs&action=edit&Id=' . $iid . '&cp=' . SESSION);
- exit;
- }
- }
- break;
- }
- }
-
- /**
- * Запись настроек рубрики
- *
- */
- function quickSave()
- {
- global $AVE_DB, $AVE_Template;
-
- if (check_permission_acp('rubric_edit'))
- {
- foreach ($_POST['rubric_title'] as $rubric_id => $rubric_title)
- {
- if (!empty($rubric_title))
- {
- $set_rubric_title = '';
- $set_rubric_alias = '';
-
- $name_exist = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_rubrics
- WHERE
- rubric_title = '" . $rubric_title . "'
- AND
- Id != '" . $rubric_id . "'
- LIMIT 1
- ")->NumRows();
-
- if (!$name_exist)
- {
- $set_rubric_title = "rubric_title = '" . $rubric_title . "',";
- }
-
- if (isset($_POST['rubric_alias'][$rubric_id]) && $_POST['rubric_alias'][$rubric_id] != '')
- {
- $pattern = TRANSLIT_URL ? '/[^\%HYa-z0-9\/_-]+/' : '/[^\%HYa-zа-яА-Яёїєі0-9\/_-]+/u';
- if (!(preg_match($pattern, $_POST['rubric_alias'][$rubric_id])))
+ if (isset($_POST['rubric_alias'][$rubric_id]) && $_POST['rubric_alias'][$rubric_id] != '')
{
- $prefix_exist = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_rubrics
- WHERE
- rubric_alias = '" . $_POST['rubric_alias'][$rubric_id] . "'
- AND
- Id != '" . $rubric_id . "'
- LIMIT 1
- ")->NumRows();
-
- if (!$prefix_exist)
+ $pattern = TRANSLIT_URL ? '/[^\%HYa-z0-9\/_-]+/' : '/[^\%HYa-zа-яА-Яёїєі0-9\/_-]+/u';
+ if (!(preg_match($pattern, $_POST['rubric_alias'][$rubric_id])))
{
- $set_rubric_alias = "rubric_alias = '" . trim(preg_replace($pattern, '', $_POST['rubric_alias'][$rubric_id]), '/') . "',";
+ $prefix_exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubrics
+ WHERE
+ rubric_alias = '" . $_POST['rubric_alias'][$rubric_id] . "'
+ AND
+ Id != '" . $rubric_id . "'
+ LIMIT 1
+ ")->NumRows();
+
+ if (!$prefix_exist)
+ {
+ $set_rubric_alias = "rubric_alias = '" . trim(preg_replace($pattern, '', $_POST['rubric_alias'][$rubric_id]), '/') . "',";
+ }
}
}
- }
- else
- {
- $set_rubric_alias = "rubric_alias = '',";
- }
+ else
+ {
+ $set_rubric_alias = "rubric_alias = '',";
+ }
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- " . $set_rubric_title . "
- " . $set_rubric_alias . "
- rubric_meta_gen = '" . (isset($_POST['rubric_meta_gen'][$rubric_id]) ? $_POST['rubric_meta_gen'][$rubric_id] : '0') . "',
- rubric_alias_history = '" . (isset($_POST['rubric_alias_history'][$rubric_id]) ? $_POST['rubric_alias_history'][$rubric_id] : '0') . "',
- rubric_template_id = '" . (int)$_POST['rubric_template_id'][$rubric_id] . "',
- rubric_docs_active = '" . (isset($_POST['rubric_docs_active'][$rubric_id]) ? $_POST['rubric_docs_active'][$rubric_id] : '0') . "'
- WHERE
- Id = '" . $rubric_id . "'
- ");
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubrics
+ SET
+ " . $set_rubric_title . "
+ " . $set_rubric_alias . "
+ rubric_meta_gen = '" . (isset($_POST['rubric_meta_gen'][$rubric_id]) ? $_POST['rubric_meta_gen'][$rubric_id] : '0') . "',
+ rubric_alias_history = '" . (isset($_POST['rubric_alias_history'][$rubric_id]) ? $_POST['rubric_alias_history'][$rubric_id] : '0') . "',
+ rubric_template_id = '" . (int)$_POST['rubric_template_id'][$rubric_id] . "',
+ rubric_docs_active = '" . (isset($_POST['rubric_docs_active'][$rubric_id]) ? $_POST['rubric_docs_active'][$rubric_id] : '0') . "'
+ WHERE
+ Id = '" . $rubric_id . "'
+ ");
+ }
+ }
+
+ $message = $AVE_Template->get_config_vars('RUBRIK_REP_QUICKSAVE_T');
+ $header = $AVE_Template->get_config_vars('RUBRIK_REP_QUICKSAVE_H');
+ $theme = 'accept';
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_QUICKSAVE'));
+
+ if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = 'run') {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ } else {
+ $page = !empty($_REQUEST['page']) ? '&page=' . $_REQUEST['page'] : '' ;
+ header('Location:index.php?do=rubs' . $page . '&cp=' . SESSION);
}
}
-
- $message = $AVE_Template->get_config_vars('RUBRIK_REP_QUICKSAVE_T');
- $header = $AVE_Template->get_config_vars('RUBRIK_REP_QUICKSAVE_H');
- $theme = 'accept';
-
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_QUICKSAVE'));
-
- if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = 'run') {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- } else {
- $page = !empty($_REQUEST['page']) ? '&page=' . $_REQUEST['page'] : '' ;
- header('Location:index.php?do=rubs' . $page . '&cp=' . SESSION);
- }
- }
- }
-
- /**
- * Копирование рубрики
- *
- */
- function rubricCopy()
- {
- global $AVE_DB, $AVE_Template;
-
- $rubric_id = (int)$_REQUEST['Id'];
-
- $errors = array();
-
- if (empty($_REQUEST['rubric_title']))
- {
- array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_NAME'));
- }
- else
- {
- $name_exist = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_rubrics
- WHERE rubric_title = '" . $_POST['rubric_title'] . "'
- LIMIT 1
- ")->NumRows();
-
- if ($name_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NAME_EXIST'));
}
- if (!empty($_POST['rubric_alias']))
+ /**
+ * Копирование рубрики
+ *
+ */
+ function rubricCopy()
{
- if (preg_match(TRANSLIT_URL ? '/[^\%HYa-z0-9\/-]+/' : '/[^\%HYa-zа-яёїєі0-9\/_-]+/', $_POST['rubric_alias']))
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['Id'];
+
+ $errors = array();
+
+ if (empty($_REQUEST['rubric_title']))
{
- array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_BAD_CHAR'));
+ array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_NAME'));
}
else
{
- $prefix_exist = $AVE_DB->Query("
+ $name_exist = $AVE_DB->Query("
SELECT 1
FROM " . PREFIX . "_rubrics
- WHERE rubric_alias = '" . $_POST['rubric_alias'] . "'
+ WHERE rubric_title = '" . $_POST['rubric_title'] . "'
LIMIT 1
")->NumRows();
- if ($prefix_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_EXIST'));
+ if ($name_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NAME_EXIST'));
}
- }
- $row = $AVE_DB->Query("
- SELECT *
- FROM " . PREFIX . "_rubrics
- WHERE Id = '" . $rubric_id . "'
- ")->FetchRow();
+ if (!empty($_POST['rubric_alias']))
+ {
+ if (preg_match(TRANSLIT_URL ? '/[^\%HYa-z0-9\/-]+/' : '/[^\%HYa-zа-яёїєі0-9\/_-]+/', $_POST['rubric_alias']))
+ {
+ array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_BAD_CHAR'));
+ }
+ else
+ {
+ $prefix_exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubrics
+ WHERE rubric_alias = '" . $_POST['rubric_alias'] . "'
+ LIMIT 1
+ ")->NumRows();
- if (!$row) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_RUBRIK'));
+ if ($prefix_exist) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_PREFIX_EXIST'));
+ }
+ }
- if (!empty($errors))
- {
- $AVE_Template->assign('errors', $errors);
- }
- else
- {
- $AVE_DB->Query("
- INSERT " . PREFIX . "_rubrics
- SET
- rubric_title = '" . $_POST['rubric_title'] . "',
- rubric_alias = '" . $_POST['rubric_alias'] . "',
- rubric_template = '" . addslashes($row->rubric_template) . "',
- rubric_template_id = '" . addslashes($row->rubric_template_id) . "',
- rubric_author_id = '" . (int)$_SESSION['user_id'] . "',
- rubric_created = '" . time() . "',
- rubric_teaser_template = '" . addslashes($row->rubric_teaser_template) . "',
- rubric_header_template = '" . addslashes($row->rubric_header_template) . "',
- rubric_admin_teaser_template = '" . addslashes($row->rubric_admin_teaser_template) . "'
- ");
- $iid = $AVE_DB->InsertId();
+ $row = $AVE_DB->Query("
+ SELECT *
+ FROM " . PREFIX . "_rubrics
+ WHERE Id = '" . $rubric_id . "'
+ ")->FetchRow();
- $sql = $AVE_DB->Query("
- SELECT
- user_group_id,
- rubric_permission
- FROM " . PREFIX . "_rubric_permissions
- WHERE rubric_id = '" . $rubric_id . "'
- ");
- while ($row = $sql->FetchRow())
+ if (!$row) array_push($errors, $AVE_Template->get_config_vars('RUBRIK_NO_RUBRIK'));
+
+ if (!empty($errors))
+ {
+ $AVE_Template->assign('errors', $errors);
+ }
+ else
{
$AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_permissions
+ INSERT " . PREFIX . "_rubrics
SET
- rubric_id = '" . $iid . "',
- user_group_id = '" . (int)$row->user_group_id . "',
- rubric_permission = '" . addslashes($row->rubric_permission) . "'
+ rubric_title = '" . $_POST['rubric_title'] . "',
+ rubric_alias = '" . $_POST['rubric_alias'] . "',
+ rubric_template = '" . addslashes($row->rubric_template) . "',
+ rubric_template_id = '" . addslashes($row->rubric_template_id) . "',
+ rubric_author_id = '" . (int)$_SESSION['user_id'] . "',
+ rubric_created = '" . time() . "',
+ rubric_teaser_template = '" . addslashes($row->rubric_teaser_template) . "',
+ rubric_header_template = '" . addslashes($row->rubric_header_template) . "',
+ rubric_footer_template = '" . addslashes($row->rubric_footer_template) . "',
+ rubric_admin_teaser_template = '" . addslashes($row->rubric_admin_teaser_template) . "'
");
+ $iid = $AVE_DB->InsertId();
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ user_group_id,
+ rubric_permission
+ FROM " . PREFIX . "_rubric_permissions
+ WHERE rubric_id = '" . $rubric_id . "'
+ ");
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_permissions
+ SET
+ rubric_id = '" . $iid . "',
+ user_group_id = '" . (int)$row->user_group_id . "',
+ rubric_permission = '" . addslashes($row->rubric_permission) . "'
+ ");
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rubric_field_title,
+ rubric_field_alias,
+ rubric_field_type,
+ rubric_field_position,
+ rubric_field_default,
+ rubric_field_template,
+ rubric_field_template_request,
+ rubric_field_description
+ FROM " . PREFIX . "_rubric_fields
+ WHERE rubric_id = '" . $rubric_id . "'
+ ORDER BY rubric_field_position ASC
+ ");
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_fields
+ SET
+ rubric_id = '" . $iid . "',
+ rubric_field_title = '" . addslashes($row->rubric_field_title) . "',
+ rubric_field_alias = '" . addslashes($row->rubric_field_alias) . "',
+ rubric_field_type = '" . addslashes($row->rubric_field_type) . "',
+ rubric_field_position = '" . (int)$row->rubric_field_position . "',
+ rubric_field_default = '" . addslashes($row->rubric_field_default) . "',
+ rubric_field_template = '" . addslashes($row->rubric_field_template) . "',
+ rubric_field_template_request = '" . addslashes($row->rubric_field_template_request) . "',
+ rubric_field_description = '" . addslashes($row->rubric_field_description) . "'
+ ");
+ }
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_COPY') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (id: '.$rubric_id.')');
+
+ echo '';
+ }
+ }
+
+ /**
+ * Удаление рубрики
+ *
+ */
+ function rubricDelete()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['Id'];
+
+ if ($rubric_id <= 1)
+ {
+ header('Location:index.php?do=rubs&cp=' . SESSION);
+ exit;
}
- $sql = $AVE_DB->Query("
- SELECT
- rubric_field_title,
- rubric_field_alias,
- rubric_field_type,
- rubric_field_position,
- rubric_field_default,
- rubric_field_template,
- rubric_field_template_request,
- rubric_field_description
- FROM " . PREFIX . "_rubric_fields
+ $rubric_not_empty = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_documents
WHERE rubric_id = '" . $rubric_id . "'
- ORDER BY rubric_field_position ASC
- ");
- while ($row = $sql->FetchRow())
+ LIMIT 1
+ ")->GetCell();
+
+ if (!$rubric_not_empty)
{
$AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_fields
- SET
- rubric_id = '" . $iid . "',
- rubric_field_title = '" . addslashes($row->rubric_field_title) . "',
- rubric_field_alias = '" . addslashes($row->rubric_field_alias) . "',
- rubric_field_type = '" . addslashes($row->rubric_field_type) . "',
- rubric_field_position = '" . (int)$row->rubric_field_position . "',
- rubric_field_default = '" . addslashes($row->rubric_field_default) . "',
- rubric_field_template = '" . addslashes($row->rubric_field_template) . "',
- rubric_field_template_request = '" . addslashes($row->rubric_field_template_request) . "',
- rubric_field_description = '" . addslashes($row->rubric_field_description) . "'
+ DELETE
+ FROM " . PREFIX . "_rubrics
+ WHERE Id = '" . $rubric_id . "'
");
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_fields
+ WHERE rubric_id = '" . $rubric_id . "'
+ ");
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_permissions
+ WHERE rubric_id = '" . $rubric_id . "'
+ ");
+ // Очищаем кэш шаблона документов рубрики
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_template_cache
+ WHERE rub_id = '" . $rubric_id . "'
+ ");
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_DEL_RUBRIC') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (id: '.$rubric_id.')');
}
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_COPY') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (id: '.$rubric_id.')');
-
- echo '';
- }
- }
-
- /**
- * Удаление рубрики
- *
- */
- function rubricDelete()
- {
- global $AVE_DB, $AVE_Template;
-
- $rubric_id = (int)$_REQUEST['Id'];
-
- if ($rubric_id <= 1)
- {
header('Location:index.php?do=rubs&cp=' . SESSION);
exit;
}
- $rubric_not_empty = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_documents
- WHERE rubric_id = '" . $rubric_id . "'
- LIMIT 1
- ")->GetCell();
-
- if (!$rubric_not_empty)
+ /**
+ * Вывод списка полей рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricFieldShow($rubric_id = 0, $ajax)
{
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubrics
- WHERE Id = '" . $rubric_id . "'
- ");
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_fields
- WHERE rubric_id = '" . $rubric_id . "'
- ");
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_permissions
- WHERE rubric_id = '" . $rubric_id . "'
- ");
- // Очищаем кэш шаблона документов рубрики
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_template_cache
- WHERE rub_id = '" . $rubric_id . "'
- ");
+ global $AVE_DB, $AVE_Template;
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_DEL_RUBRIC') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (id: '.$rubric_id.')');
+ if(check_permission_acp('rubric_edit'))
+ {
+ // Поля
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.*, b.group_title, b.group_description, b.group_position
+ FROM
+ " . PREFIX . "_rubric_fields AS a
+ LEFT JOIN
+ " . PREFIX . "_rubric_fields_group AS b
+ ON a.rubric_field_group = b.Id
+ WHERE
+ a.rubric_id = '" . $rubric_id . "'
+ ORDER BY
+ b.group_position ASC, a.rubric_field_position ASC
+ ");
+
+ $fields_list = array();
+
+ while ($row = $sql->FetchRow())
+ {
+ $group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
+
+ $fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
+ $fields_list[$group_id]['group_title'] = $row->group_title;
+ $fields_list[$group_id]['group_description'] = $row->group_description;
+ $fields_list[$group_id]['fields'][$row->Id]['Id'] = $row->Id;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_id'] = $row->rubric_id;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_group'] = $row->rubric_field_group;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_alias'] = $row->rubric_field_alias;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_title'] = $row->rubric_field_title;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_type'] = $row->rubric_field_type;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_numeric'] = $row->rubric_field_numeric;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_default'] = $row->rubric_field_default;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_search'] = $row->rubric_field_search;
+ }
+
+ $fields_list = msort($fields_list, 'group_position');
+
+ $AVE_Template->assign('groups_count', count($fields_list));
+ $AVE_Template->assign('fields_list', $fields_list);
+
+ // Группы полей
+ $fields_groups = array();
+
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM " . PREFIX . "_rubric_fields_group
+ WHERE rubric_id = '" . $rubric_id . "'
+ ORDER BY group_position ASC
+ ");
+
+ while ($row = $sql->FetchRow())
+ {
+ array_push($fields_groups, $row);
+ }
+
+ $AVE_Template->assign('fields_groups', $fields_groups);
+
+
+ // Права
+ $groups = array();
+
+ $sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_user_groups");
+
+ while ($row = $sql->FetchRow())
+ {
+ $row->doall = ($row->user_group == 1) ? ' disabled="disabled" checked="checked"' : '';
+ $row->doall_h = ($row->user_group == 1) ? 1 : '';
+
+ $rubric_permission = $AVE_DB->Query("
+ SELECT rubric_permission
+ FROM " . PREFIX . "_rubric_permissions
+ WHERE user_group_id = '" . $row->user_group . "'
+ AND rubric_id = '" . $rubric_id . "'
+ ")->GetCell();
+
+ $row->permissions = @explode('|', $rubric_permission);
+
+ array_push($groups,$row);
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT rubric_title, rubric_linked_rubric, rubric_description
+ FROM " . PREFIX . "_rubrics
+ WHERE id = '" . $rubric_id . "'
+ LIMIT 1
+ ");
+
+ $rubrik = $sql->FetchRow();
+
+ $rubrik->rubric_linked_rubric = ($rubrik->rubric_linked_rubric != '0') ? unserialize($rubrik->rubric_linked_rubric) : array();
+
+ $AVE_Template->assign('rubric', $rubrik);
+ $AVE_Template->assign('groups', $groups);
+ $AVE_Template->assign('fields', get_field_type());
+ $AVE_Template->assign('rubs', $this->rubricShow());
+
+ if (isAjax())
+ {
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields.tpl'));
+ }
+ else
+ {
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields_list.tpl'));
+ }
+ }
+ else
+ {
+ header('Location:index.php?do=rubs&cp=' . SESSION);
+ exit;
+ }
}
- header('Location:index.php?do=rubs&cp=' . SESSION);
- exit;
- }
- /**
- * Вывод списка полей рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricFieldShow($rubric_id = 0, $ajax)
- {
- global $AVE_DB, $AVE_Template;
-
- if(check_permission_acp('rubric_edit'))
+ /**
+ * Вывод списка полей рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricRulesShow($rubric_id = 0)
{
+ global $AVE_DB, $AVE_Template;
+
+ if (check_permission_acp('rubric_edit'))
+ {
+ // Права
+ $groups = array();
+
+ $sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_user_groups");
+
+ while ($row = $sql->FetchRow())
+ {
+ $row->doall = ($row->user_group == 1) ? ' disabled="disabled" checked="checked"' : '';
+ $row->doall_h = ($row->user_group == 1) ? 1 : '';
+
+ $rubric_permission = $AVE_DB->Query("
+ SELECT rubric_permission
+ FROM " . PREFIX . "_rubric_permissions
+ WHERE user_group_id = '" . $row->user_group . "'
+ AND rubric_id = '" . $rubric_id . "'
+ ")->GetCell();
+
+ $row->permissions = @explode('|', $rubric_permission);
+
+ array_push($groups,$row);
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT rubric_title, rubric_linked_rubric, rubric_description
+ FROM " . PREFIX . "_rubrics
+ WHERE id = '" . $rubric_id . "'
+ LIMIT 1
+ ");
+
+ $rubric = $sql->FetchRow();
+
+ $AVE_Template->assign('rubric', $rubric);
+ $AVE_Template->assign('groups', $groups);
+
+ if (isAjax())
+ {
+
+ }
+ else
+ {
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/rules.tpl'));
+ }
+ }
+ else
+ {
+ header('Location:index.php?do=rubs&cp=' . SESSION);
+ exit;
+ }
+ }
+
+
+
+ /**
+ * Вывод списка рубрик
+ *
+ * @param int $rubric_id идентификатор текущей рубрики
+ */
+ function rubricShow($RubLink=null)
+ {
+ global $AVE_DB;
+
+ if ($RubLink!==null) {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubrics
+ SET
+ rubric_linked_rubric = '" . serialize($_REQUEST['rubric_linked']) . "'
+ WHERE
+ Id = '" . (int)$_REQUEST['Id'] . "'
+ ");
+ header('Location:index.php?do=rubs&action=edit&Id=' . (int)$_REQUEST['Id'] . '&cp=' . SESSION);
+ exit;
+ }
+ else
+ {
+ $rubs = array();
+ $sql = $AVE_DB->Query("
+ SELECT rubric_title, Id
+ FROM " . PREFIX . "_rubrics
+ ORDER BY rubric_position ASC
+ ");
+
+ while ($row = $sql->FetchRow())
+ {
+ array_push($rubs,$row);
+ }
+ return $rubs;
+ }
+ }
+
+ /**
+ * Создание нового поля рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricFieldNew($rubric_id = 0, $ajax)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ if (!empty($_POST['title_new']))
+ {
+ $position = (int)$AVE_DB->Query("
+ SELECT MAX(rubric_field_position)
+ FROM " . PREFIX . "_rubric_fields
+ WHERE rubric_id = '" . $rubric_id . "'
+ ")->GetCell() + 1;
+
+ if ($_POST['rub_type_new'] == 'dropdown')
+ {
+ $rubric_field_default = trim($_POST['default_value']);
+ $rubric_field_default = preg_split('/\s*,\s*/', $rubric_field_default);
+ $rubric_field_default = implode(',', $rubric_field_default);
+ }
+ else
+ {
+ $rubric_field_default = $_POST['default_value'];
+ }
+
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_fields
+ SET
+ rubric_id = '" . $rubric_id . "',
+ rubric_field_group = '" . (($_POST['group_new'] != '') ? (int)$_POST['group_new'] : '0') . "',
+ rubric_field_title = '" . $_POST['title_new'] . "',
+ rubric_field_type = '" . $_POST['rub_type_new'] . "',
+ rubric_field_position = '" . $position . "',
+ rubric_field_default = '" . $rubric_field_default . "',
+ rubric_field_numeric = '" . (($_POST['rubric_field_numeric'] == 1) ? $_POST['rubric_field_numeric'] : '0') . "',
+ rubric_field_search = '" . (($_POST['rubric_field_search'] == 1) ? $_POST['rubric_field_search'] : '0') . "'
+ ");
+
+ $UpdateRubricField = $AVE_DB->InsertId();
+
+ $sql = $AVE_DB->Query("
+ SELECT Id
+ FROM " . PREFIX . "_documents
+ WHERE rubric_id = '" . $rubric_id . "'
+ ");
+
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_document_fields
+ SET
+ rubric_field_id = '" . $UpdateRubricField . "',
+ document_id = '" . $row->Id . "'
+ ");
+ }
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_NEW_FIELD').' (' . stripslashes(htmlspecialchars($_POST['title_new'], ENT_QUOTES)) . ') '. stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)). ' (id: '.$rubric_id.')');
+ } else {
+
+ if (!$ajax){
+
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+
+ }else{
+
+ $message = $AVE_Template->get_config_vars('RUBRIK_EMPTY_MESSAGE');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'error';
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+ }
+ if (!$ajax){
+
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+
+ }else{
+
+ $message = $AVE_Template->get_config_vars('RUBRIK_FILD_SAVED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'accept';
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+ }
+
+
+ /**
+ * Редактирование кода для рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricCodeEdit($rubric_id = 0)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ switch ($_REQUEST['sub']) {
+
+ case '':
+ $code = $AVE_DB->Query("
+ SELECT
+ rubric_code_start,
+ rubric_code_end,
+ rubric_start_code
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ Id = '" . $rubric_id . "'
+ ")->FetchRow();
+
+ $AVE_Template->assign('code', $code);
+ $AVE_Template->assign('rubric_title', $this->rubricNameByIdGet($rubric_id)->rubric_title);
+ $AVE_Template->assign('formaction', 'index.php?do=rubs&action=code&sub=save&Id=' . $rubric_id . '&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/code.tpl'));
+ break;
+
+ case 'save':
+ $sql = $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubrics
+ SET
+ rubric_start_code = '" . $_POST['rubric_start_code'] . "',
+ rubric_code_start = '" . $_POST['rubric_code_start'] . "',
+ rubric_code_end = '" . $_POST['rubric_code_end'] . "'
+ WHERE
+ Id = '" . $rubric_id . "'
+ ");
+
+ $AVE_DB->clearcache('rub_' . $rubric_id);
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ Id
+ FROM
+ " . PREFIX . "_documents
+ WHERE
+ rubric_id = " . $rubric_id . "
+ ");
+
+ while ($row = $sql->GetCell())
+ {
+ $AVE_DB->clearcache('doc_' . $row);
+ $AVE_DB->clearcompile('doc_' . $row);
+ }
+
+ if ($sql->_result === false)
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED_ERR');
+ $header = $AVE_Template->get_config_vars('RUBRIK_CODE_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_CODE_SUCCESS');
+ $theme = 'accept';
+ reportLog($AVE_Template->get_config_vars('RUBRIK_CODE_UPDATE') . " (" . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ") (id: $rubric_id)");
+ }
+
+ if (isAjax())
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+ else
+ {
+ header('Location:index.php?do=rubs&action=code&Id=' . $rubric_id . '&cp=' . SESSION);
+ }
+ exit;
+ }
+ }
+
+ /**
+ * Редактирование кода для рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricCode($rubric_id = 0)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $sql = $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubrics
+ SET
+ rubric_start_code = '" . $_POST['rubric_start_code'] . "',
+ rubric_code_start = '" . $_POST['rubric_code_start'] . "',
+ rubric_code_end = '" . $_POST['rubric_code_end'] . "'
+ WHERE
+ Id = '" . $rubric_id . "'
+ ");
+
+ if ($sql->_result === false)
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED_ERR');
+ $header = $AVE_Template->get_config_vars('RUBRIK_CODE_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_CODE_SUCCESS');
+ $theme = 'accept';
+ reportLog($AVE_Template->get_config_vars('RUBRIK_CODE_UPDATE') . " (" . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ") (id: $rubric_id)");
+ }
+
+ if (isAjax())
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+ else
+ {
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ }
+ exit;
+ }
+
+ /**
+ * Редактирование описания рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricDesc($rubric_id = 0)
+ {
+ global $AVE_DB;
+
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubrics
+ SET
+ rubric_description = '" . $_POST['rubric_description'] . "'
+ WHERE
+ Id = '" . $rubric_id . "'
+ ");
+
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+ }
+
+ /**
+ * Управление полями рубрики
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricFieldSave($rubric_id = 0)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ foreach ($_POST['title'] as $id => $title)
+ {
+ if (!empty($title))
+ {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubric_fields
+ SET
+ rubric_field_title = '" . $title . "',
+ rubric_field_numeric = '" . $_POST['rubric_field_numeric'][$id] . "',
+ rubric_field_search = '" . $_POST['rubric_field_search'][$id] . "'
+ WHERE
+ Id = '" . $id . "'
+ ");
+ // Очищаем кэш шаблона документов рубрики
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_template_cache
+ WHERE rub_id = '" . $rubric_id . "'
+ ");
+
+ $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
+
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->clearcache('doc_'.$row->Id);
+ $AVE_DB->clearcompile('doc_'.$row->Id);
+ $AVE_DB->clearcacherequest('doc_'.$row->Id);
+ }
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_FIELD_EDIT') . ' (' . stripslashes($title) . ') '.$AVE_Template->get_config_vars('RUBRIK_REPORT_RUB').' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
+ }
+ }
+
+ foreach ($_POST['del'] as $id => $Del)
+ {
+ if (!empty($Del))
+ {
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_fields
+ WHERE Id = '" . $id . "'
+ AND rubric_id = '" . $rubric_id . "'
+ ");
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_document_fields
+ WHERE rubric_field_id = '" . $id . "'
+ ");
+ // Очищаем кэш шаблона документов рубрики
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_rubric_template_cache
+ WHERE rub_id = '" . $rubric_id . "'
+ ");
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_FIELD_DEL') . ' (' . stripslashes($_POST['title'][$id]) . ') '.$AVE_Template->get_config_vars('RUBRIK_REPORT_RUB').' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
+ }
+ }
+
+ $AVE_DB->clearcache('rub_'.$rubric_id);
+
+ $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
+
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->clearcache('doc_'.$row->Id);
+ $AVE_DB->clearcompile('doc_'.$row->Id);
+ }
+
+ $message = $AVE_Template->get_config_vars('RUBRIK_FILDS_SAVED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'accept';
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_FILDS_REPORT') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
+
+ if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1') {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ } else {
+ $AVE_Template->assign('message', $message);
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ }
+ exit;
+ }
+
+ /**
+ * Сортировка полей рубрики
+ *
+ * @param array $sorted последовательность id полей
+ */
+ function rubricFieldsSort()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ foreach ($_REQUEST['sort'] as $position => $field_id)
+ {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubric_fields
+ SET
+ rubric_field_position = '" . (int)$position . "'
+ WHERE
+ Id = '" . (int)$field_id . "'
+ ");
+ }
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_SORTE_FIELDS'));
+
+ if (isAjax()){
+ $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'accept';
+
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+
+ }
+
+ /**
+ * Сортировка рубрик
+ *
+ * @param array $sorted последовательность id полей
+ */
+ function rubricsSort()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ foreach ($_REQUEST['sort'] as $position => $rub_id)
+ {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubrics
+ SET
+ rubric_position = '" . (int)$position . "'
+ WHERE
+ Id = '" . (int)$rub_id . "'
+ ");
+ }
+
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_SORTE'));
+
+ if (isAjax()){
+ $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'accept';
+
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+
+ }
+
+ /**
+ * Вывод шаблона рубрики
+ *
+ * @param int $show
+ * @param int $extern
+ */
+ function rubricTemplateShow($show = '', $extern = '0')
+ {
+ global $AVE_DB, $AVE_Template;
+
+ if ($extern == 1)
+ {
+ $fetchId = (isset($_REQUEST['rubric_id']) && is_numeric($_REQUEST['rubric_id'])) ? $_REQUEST['rubric_id'] : 0;
+ }
+ else
+ {
+ $fetchId = (isset($_REQUEST['Id']) && is_numeric($_REQUEST['Id'])) ? $_REQUEST['Id'] : 0;
+ }
+
+ $rubric = $AVE_DB->Query("
+ SELECT
+ rubric_title,
+ rubric_template,
+ rubric_header_template,
+ rubric_footer_template,
+ rubric_teaser_template,
+ rubric_admin_teaser_template,
+ rubric_description
+ FROM " . PREFIX . "_rubrics
+ WHERE Id = '" . $fetchId . "'
+ ")
+ ->FetchRow();
+
// Поля
$sql = $AVE_DB->Query("
SELECT
@@ -515,17 +1162,21 @@ class AVE_Rubric
" . PREFIX . "_rubric_fields_group AS b
ON a.rubric_field_group = b.Id
WHERE
- a.rubric_id = '" . $rubric_id . "'
+ a.rubric_id = '" . $fetchId . "'
ORDER BY
b.group_position ASC, a.rubric_field_position ASC
");
$fields_list = array();
+ $drop_down_fields = array();
while ($row = $sql->FetchRow())
{
$group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
+ if ($row->rubric_field_type == 'drop_down' || $row->rubric_field_type == 'drop_down_key')
+ array_push($drop_down_fields, $row->Id);
+
$fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
$fields_list[$group_id]['group_title'] = $row->group_title;
$fields_list[$group_id]['group_description'] = $row->group_description;
@@ -545,352 +1196,362 @@ class AVE_Rubric
$AVE_Template->assign('groups_count', count($fields_list));
$AVE_Template->assign('fields_list', $fields_list);
- // Группы полей
- $fields_groups = array();
+ $AVE_Template->assign('field_array', get_field_type());
+
+ if ($show == 1 )
+ $rubric->rubric_template = stripslashes($_POST['rubric_template']);
+
+ if ($extern == 1)
+ {
+ $AVE_Template->assign('ddid', implode(',', $drop_down_fields));
+ }
+ else
+ {
+ $AVE_Template->assign('rubric', $rubric);
+ $AVE_Template->assign('formaction', 'index.php?do=rubs&action=template&sub=save&Id=' . $fetchId . '&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/form.tpl'));
+ }
+ }
+
+ /**
+ * Редактирование шаблона рубрики
+ *
+ * @param string $data
+ */
+ function rubricTemplateSave($Rtemplate, $Htemplate = '', $Ttemplate = '', $Atemplate = '', $Ftemplate = '')
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['Id'];
$sql = $AVE_DB->Query("
- SELECT *
- FROM " . PREFIX . "_rubric_fields_group
- WHERE rubric_id = '" . $rubric_id . "'
- ORDER BY group_position ASC
+ UPDATE
+ " . PREFIX . "_rubrics
+ SET
+ rubric_template = '" . ($Rtemplate) . "',
+ rubric_header_template = '" . $Htemplate . "',
+ rubric_footer_template = '" . $Ftemplate . "',
+ rubric_teaser_template = '" . $Ttemplate . "',
+ rubric_admin_teaser_template = '" . $Atemplate . "'
+ WHERE
+ Id = '" . $rubric_id . "'
");
+ // Очищаем кэш шаблона документов рубрики
+ $AVE_DB->Query("
+ DELETE
+ FROM
+ " . PREFIX . "_rubric_template_cache
+ WHERE
+ rub_id = '" . $rubric_id . "'
+ ");
+
+ if ($sql === false)
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL_ERR');
+ $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL');
+ $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
+ $theme = 'accept';
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_TEMPL_RUB') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
+ }
+
+ $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
+
while ($row = $sql->FetchRow())
{
- array_push($fields_groups, $row);
+ $AVE_DB->clearcache('doc_'.$row->Id);
+ $AVE_DB->clearcompile('doc_'.$row->Id);
}
- $AVE_Template->assign('fields_groups', $fields_groups);
-
-
- // Права
- $groups = array();
-
- $sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_user_groups");
-
- while ($row = $sql->FetchRow())
- {
- $row->doall = ($row->user_group == 1) ? ' disabled="disabled" checked="checked"' : '';
- $row->doall_h = ($row->user_group == 1) ? 1 : '';
-
- $rubric_permission = $AVE_DB->Query("
- SELECT rubric_permission
- FROM " . PREFIX . "_rubric_permissions
- WHERE user_group_id = '" . $row->user_group . "'
- AND rubric_id = '" . $rubric_id . "'
- ")->GetCell();
-
- $row->permissions = @explode('|', $rubric_permission);
-
- array_push($groups,$row);
- }
-
- $sql = $AVE_DB->Query("
- SELECT rubric_title, rubric_linked_rubric, rubric_description
- FROM " . PREFIX . "_rubrics
- WHERE id = '" . $rubric_id . "'
- LIMIT 1
- ");
-
- $rubrik = $sql->FetchRow();
-
- $rubrik->rubric_linked_rubric = ($rubrik->rubric_linked_rubric != '0') ? unserialize($rubrik->rubric_linked_rubric) : array();
-
- $AVE_Template->assign('rubric', $rubrik);
- $AVE_Template->assign('groups', $groups);
- $AVE_Template->assign('fields', get_field_type());
- $AVE_Template->assign('rubs', $this->rubricShow());
-
if (isAjax())
{
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields.tpl'));
- }
- else
- {
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields_list.tpl'));
- }
- }
- else
- {
- header('Location:index.php?do=rubs&cp=' . SESSION);
- exit;
- }
- }
-
- /**
- * Вывод списка рубрик
- *
- * @param int $rubric_id идентификатор текущей рубрики
- */
- function rubricShow($RubLink=null)
- {
- global $AVE_DB;
-
- if ($RubLink!==null) {
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_linked_rubric = '" . serialize($_REQUEST['rubric_linked']) . "'
- WHERE
- Id = '" . (int)$_REQUEST['Id'] . "'
- ");
- header('Location:index.php?do=rubs&action=edit&Id=' . (int)$_REQUEST['Id'] . '&cp=' . SESSION);
- exit;
- }
- else
- {
- $rubs = array();
- $sql = $AVE_DB->Query("
- SELECT rubric_title, Id
- FROM " . PREFIX . "_rubrics
- ORDER BY rubric_position ASC
- ");
-
- while ($row = $sql->FetchRow())
- {
- array_push($rubs,$row);
- }
- return $rubs;
- }
- }
-
- /**
- * Создание нового поля рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricFieldNew($rubric_id = 0, $ajax)
- {
- global $AVE_DB, $AVE_Template;
-
- if (!empty($_POST['title_new']))
- {
- $position = (int)$AVE_DB->Query("
- SELECT MAX(rubric_field_position)
- FROM " . PREFIX . "_rubric_fields
- WHERE rubric_id = '" . $rubric_id . "'
- ")->GetCell() + 1;
-
- if ($_POST['rub_type_new'] == 'dropdown')
- {
- $rubric_field_default = trim($_POST['default_value']);
- $rubric_field_default = preg_split('/\s*,\s*/', $rubric_field_default);
- $rubric_field_default = implode(',', $rubric_field_default);
- }
- else
- {
- $rubric_field_default = $_POST['default_value'];
- }
-
- $AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_fields
- SET
- rubric_id = '" . $rubric_id . "',
- rubric_field_group = '" . (($_POST['group_new'] != '') ? (int)$_POST['group_new'] : '0') . "',
- rubric_field_title = '" . $_POST['title_new'] . "',
- rubric_field_type = '" . $_POST['rub_type_new'] . "',
- rubric_field_position = '" . $position . "',
- rubric_field_default = '" . $rubric_field_default . "',
- rubric_field_numeric = '" . (($_POST['rubric_field_numeric'] == 1) ? $_POST['rubric_field_numeric'] : '0') . "',
- rubric_field_search = '" . (($_POST['rubric_field_search'] == 1) ? $_POST['rubric_field_search'] : '0') . "'
- ");
-
- $UpdateRubricField = $AVE_DB->InsertId();
-
- $sql = $AVE_DB->Query("
- SELECT Id
- FROM " . PREFIX . "_documents
- WHERE rubric_id = '" . $rubric_id . "'
- ");
-
- while ($row = $sql->FetchRow())
- {
- $AVE_DB->Query("
- INSERT " . PREFIX . "_document_fields
- SET
- rubric_field_id = '" . $UpdateRubricField . "',
- document_id = '" . $row->Id . "'
- ");
- }
-
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('RUBRIK_LOG_NEW_FIELD').' (' . stripslashes(htmlspecialchars($_POST['title_new'], ENT_QUOTES)) . ') '. stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)). ' (id: '.$rubric_id.')');
- } else {
-
- if (!$ajax){
-
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
-
- }else{
-
- $message = $AVE_Template->get_config_vars('RUBRIK_EMPTY_MESSAGE');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'error';
echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
exit;
}
+ else
+ {
+ $AVE_Template->assign('message', $message);
+ header('Location:index.php?do=rubs&cp=' . SESSION);
+ exit;
+ }
+
}
- if (!$ajax){
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
+ /**
+ * Управление правами доступа к документам рубрик
+ *
+ * @param int $rubric_id идентификатор рубрики
+ */
+ function rubricPermissionSave($rubric_id = 0)
+ {
+ global $AVE_DB, $AVE_Template;
- }else{
+ if (check_permission_acp('rubric_perms') && is_numeric($rubric_id) && $rubric_id > 0)
+ {
+ foreach ($_POST['user_group'] as $key => $user_group_id)
+ {
+ $exist = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_rubric_permissions
+ WHERE user_group_id = '" . $user_group_id . "'
+ AND rubric_id = '" . $rubric_id . "'
+ LIMIT 1
+ ")->NumRows();
- $message = $AVE_Template->get_config_vars('RUBRIK_FILD_SAVED');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'accept';
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- }
- }
-
-
- /**
- * Редактирование кода для рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricCodeEdit($rubric_id = 0)
- {
- global $AVE_DB, $AVE_Template;
-
- switch ($_REQUEST['sub']) {
-
- case '':
- $code = $AVE_DB->Query("
- SELECT rubric_code_start, rubric_code_end, rubric_start_code
- FROM " . PREFIX . "_rubrics
- WHERE
- Id = '" . $rubric_id . "'
- ")->FetchRow();
-
- $AVE_Template->assign('code', $code);
- $AVE_Template->assign('rubric_title', $this->rubricNameByIdGet($rubric_id)->rubric_title);
- $AVE_Template->assign('formaction', 'index.php?do=rubs&action=code&sub=save&Id=' . $rubric_id . '&cp=' . SESSION);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/code.tpl'));
- break;
-
- case 'save':
- $sql = $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_start_code = '" . $_POST['rubric_start_code'] . "',
- rubric_code_start = '" . $_POST['rubric_code_start'] . "',
- rubric_code_end = '" . $_POST['rubric_code_end'] . "'
- WHERE
- Id = '" . $rubric_id . "'
- ");
-
- if ($sql->_result === false) {
- $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED_ERR');
- $header = $AVE_Template->get_config_vars('RUBRIK_CODE_ERROR');
- $theme = 'error';
- }else{
- $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED');
- $header = $AVE_Template->get_config_vars('RUBRIK_CODE_SUCCESS');
- $theme = 'accept';
- reportLog($AVE_Template->get_config_vars('RUBRIK_CODE_UPDATE') . " (" . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ") (id: $rubric_id)");
+ $rubric_permission = @implode('|', $_POST['perm'][$key]);
+ if ($exist)
+ {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubric_permissions
+ SET rubric_permission = '" . $rubric_permission . "'
+ WHERE user_group_id = '" . $user_group_id . "'
+ AND rubric_id = '" . $rubric_id . "'
+ ");
+ }
+ else
+ {
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_rubric_permissions
+ SET
+ rubric_id = '" . $rubric_id . "',
+ user_group_id = '" . $user_group_id . "',
+ rubric_permission = '" . $rubric_permission . "'
+ ");
+ }
}
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_PERMS');
+ $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
+ $theme = 'accept';
+ reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_PERMISION') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
if (isAjax()) {
echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
} else {
- header('Location:index.php?do=rubs&action=code&Id=' . $rubric_id . '&cp=' . SESSION);
+ header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
}
- exit;
- }
- }
-
- /**
- * Редактирование кода для рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricCode($rubric_id = 0)
- {
- global $AVE_DB, $AVE_Template;
-
- $sql = $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_code_start = '" . $_POST['rubric_code_start'] . "',
- rubric_code_end = '" . $_POST['rubric_code_end'] . "'
- WHERE
- Id = '" . $rubric_id . "'
- ");
-
- if ($sql->_result === false) {
- $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED_ERR');
- $header = $AVE_Template->get_config_vars('RUBRIK_CODE_ERROR');
- $theme = 'error';
- }else{
- $message = $AVE_Template->get_config_vars('RUBRIK_CODE_SAVED');
- $header = $AVE_Template->get_config_vars('RUBRIK_CODE_SUCCESS');
- $theme = 'accept';
- reportLog($AVE_Template->get_config_vars('RUBRIK_CODE_UPDATE') . " (" . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ") (id: $rubric_id)");
+ }
}
- if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1') {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- } else {
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- }
- exit;
- }
-
- /**
- * Редактирование описания рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricDesc($rubric_id = 0)
- {
- global $AVE_DB;
-
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_description = '" . $_POST['rubric_description'] . "'
- WHERE
- Id = '" . $rubric_id . "'
- ");
-
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
- }
-
- /**
- * Управление полями рубрики
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricFieldSave($rubric_id = 0)
- {
- global $AVE_DB, $AVE_Template;
-
- foreach ($_POST['title'] as $id => $title)
+ /**
+ * Получить наименование и URL-префикс Рубрики по идентификатору
+ *
+ * @param int $rubric_id идентификатор Рубрики
+ * @return object наименование Рубрики
+ */
+ function rubricNameByIdGet($rubric_id = 0)
{
- if (!empty($title))
+ global $AVE_DB;
+
+ static $rubrics = array();
+
+ if (!isset($rubrics[$rubric_id]))
+ {
+ $rubrics[$rubric_id] = $AVE_DB->Query("
+ SELECT
+ rubric_title,
+ rubric_alias,
+ rubric_description
+ FROM " . PREFIX . "_rubrics
+ WHERE Id = '" . $rubric_id . "'
+ LIMIT 1
+ ")->FetchRow();
+ }
+
+ return $rubrics[$rubric_id];
+ }
+
+ /**
+ * Формирование прав доступа Групп пользователей на все Рубрики
+ *
+ */
+ function rubricPermissionFetch()
+ {
+ global $AVE_DB, $AVE_Document, $AVE_Template;
+
+ $items = array();
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ Id,
+ rubric_title,
+ rubric_docs_active
+ FROM
+ " . PREFIX . "_rubrics
+ ORDER
+ BY rubric_position
+ ");
+
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_Document->documentPermissionFetch($row->Id);
+
+ if (defined('UGROUP') && UGROUP == 1) $row->Show = 1;
+ elseif (isset($_SESSION[$row->Id . '_editown']) && $_SESSION[$row->Id . '_editown'] == 1) $row->Show = 1;
+ elseif (isset($_SESSION[$row->Id . '_editall']) && $_SESSION[$row->Id . '_editall'] == 1) $row->Show = 1;
+ elseif (isset($_SESSION[$row->Id . '_new']) && $_SESSION[$row->Id . '_new'] == 1) $row->Show = 1;
+ elseif (isset($_SESSION[$row->Id . '_newnow']) && $_SESSION[$row->Id . '_newnow'] == 1) $row->Show = 1;
+ elseif (isset($_SESSION[$row->Id . '_alles']) && $_SESSION[$row->Id . '_alles'] == 1) $row->Show = 1;
+
+ array_push($items, $row);
+ }
+
+ $AVE_Template->assign('rubrics', $items);
+ }
+
+ /**
+ * Получить
+ */
+ function rubricAliasAdd()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.rubric_title,
+ b.rubric_field_title,
+ b.rubric_field_alias
+ FROM
+ " . PREFIX . "_rubrics AS a
+ JOIN
+ " . PREFIX . "_rubric_fields AS b
+ WHERE
+ a.Id = '" . $_REQUEST['rubric_id'] . "'
+ AND
+ b.Id = '" . $_REQUEST['field_id'] . "'
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign($sql);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/alias.tpl'));
+ }
+
+ function rubricAliasCheck($rubric_id, $field_id, $value)
+ {
+
+ global $AVE_DB, $AVE_Template;
+
+ $errors = array();
+
+ if(!intval($rubric_id)>0){
+ $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_RUBID');
+ }
+
+ if(!intval($field_id)>0) {
+ $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_FIELDID');
+ };
+
+ if(!preg_match('/^[A-Za-z][[:word:]]{0,19}$/', $value)) {
+ $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_MATCH');
+ };
+
+ //Проверяем есть такой алиас уже
+ $res = $AVE_DB->Query("
+ SELECT COUNT(*)
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ Id <> " . intval($field_id) . "
+ AND rubric_id = " . intval($rubric_id) . "
+ AND rubric_field_alias = '" . addslashes($value) . "'
+ ")->GetCell();
+
+ if($res>0){
+ $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_MATCH');
+ };
+
+ if (empty($errors))
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_rubric_fields
SET
- rubric_field_title = '" . $title . "',
- rubric_field_numeric = '" . $_POST['rubric_field_numeric'][$id] . "',
- rubric_field_search = '" . $_POST['rubric_field_search'][$id] . "'
+ rubric_field_alias = '" . addslashes($value) . "'
WHERE
- Id = '" . $id . "'
- ");
- // Очищаем кэш шаблона документов рубрики
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_template_cache
- WHERE rub_id = '" . $rubric_id . "'
+ Id = '" . intval($field_id) . "'
+ AND rubric_id = '" . intval($rubric_id) . "'
");
+ $AVE_Template->assign('success', true);
+ }
+ else
+ {
+ $AVE_Template->assign('errors', $errors);
+ }
- $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.rubric_title,
+ b.rubric_field_title,
+ b.rubric_field_alias
+ FROM " . PREFIX . "_rubrics AS a
+ JOIN
+ " . PREFIX . "_rubric_fields AS b
+ WHERE a.Id = '" . $_REQUEST['rubric_id'] . "'
+ AND b.Id = '" . $_REQUEST['field_id'] . "'
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign($sql);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/alias.tpl'));
+ }
+
+ function rubricFieldTemplate() {
+ global $AVE_DB, $AVE_Template;
+
+ $field = $AVE_DB->Query("
+ SELECT
+ a.rubric_title,
+ b.rubric_field_default,
+ b.rubric_field_title,
+ b.rubric_field_template,
+ b.rubric_field_template_request,
+ b.rubric_field_description
+ FROM " . PREFIX . "_rubrics AS a
+ JOIN
+ " . PREFIX . "_rubric_fields AS b
+ WHERE a.Id = '" . $_REQUEST['rubric_id'] . "'
+ AND b.Id = '" . $_REQUEST['field_id'] . "'
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign($field);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/field_template.tpl'));
+ }
+
+ function rubricFieldTemplateSave($id, $rubric_id) {
+ global $AVE_DB, $AVE_Template;
+
+ $sql = $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubric_fields
+ SET
+ rubric_field_default = '" . $_POST['rubric_field_default'] . "',
+ rubric_field_template = '" . $_POST['rubric_field_template'] . "',
+ rubric_field_template_request = '" . $_POST['rubric_field_template_request'] . "',
+ rubric_field_description = '" . $_POST['rubric_field_description'] . "'
+ WHERE
+ Id = '" . $id . "'
+ ");
+
+ if ($sql->_result === false) {
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL_ERR');
+ $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
+ $theme = 'error';
+
+ if (isAjax() && !$_REQUEST['save']) {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ } else {
+ $this->rubricFieldTemplate();
+ exit;
+ }
+
+ }else{
+
+ $AVE_DB->clearcache('rub_'.$rubric_id);
+
+ $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents");
while ($row = $sql->FetchRow())
{
@@ -899,25 +1560,6 @@ class AVE_Rubric
$AVE_DB->clearcacherequest('doc_'.$row->Id);
}
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_FIELD_EDIT') . ' (' . stripslashes($title) . ') '.$AVE_Template->get_config_vars('RUBRIK_REPORT_RUB').' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
- }
- }
-
- foreach ($_POST['del'] as $id => $Del)
- {
- if (!empty($Del))
- {
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_fields
- WHERE Id = '" . $id . "'
- AND rubric_id = '" . $rubric_id . "'
- ");
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_document_fields
- WHERE rubric_field_id = '" . $id . "'
- ");
// Очищаем кэш шаблона документов рубрики
$AVE_DB->Query("
DELETE
@@ -925,1085 +1567,472 @@ class AVE_Rubric
WHERE rub_id = '" . $rubric_id . "'
");
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_FIELD_DEL') . ' (' . stripslashes($_POST['title'][$id]) . ') '.$AVE_Template->get_config_vars('RUBRIK_REPORT_RUB').' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
- }
- }
-
- $AVE_DB->clearcache('rub_'.$rubric_id);
-
- $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
-
- while ($row = $sql->FetchRow())
- {
- $AVE_DB->clearcache('doc_'.$row->Id);
- $AVE_DB->clearcompile('doc_'.$row->Id);
- }
-
- $message = $AVE_Template->get_config_vars('RUBRIK_FILDS_SAVED');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'accept';
-
- reportLog($AVE_Template->get_config_vars('RUBRIK_FILDS_REPORT') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
-
- if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] = '1') {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- } else {
- $AVE_Template->assign('message', $message);
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- }
- exit;
- }
-
- /**
- * Сортировка полей рубрики
- *
- * @param array $sorted последовательность id полей
- */
- function rubricFieldsSort()
- {
- global $AVE_DB, $AVE_Template;
-
- foreach ($_REQUEST['sort'] as $position => $field_id)
- {
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubric_fields
- SET
- rubric_field_position = '" . (int)$position . "'
- WHERE
- Id = '" . (int)$field_id . "'
- ");
- }
-
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_SORTE_FIELDS'));
-
- if (isAjax()){
- $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'accept';
-
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- }
-
- }
-
- /**
- * Сортировка рубрик
- *
- * @param array $sorted последовательность id полей
- */
- function rubricsSort()
- {
- global $AVE_DB, $AVE_Template;
-
- foreach ($_REQUEST['sort'] as $position => $rub_id)
- {
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_position = '" . (int)$position . "'
- WHERE
- Id = '" . (int)$rub_id . "'
- ");
- }
-
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_SORTE'));
-
- if (isAjax()){
- $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'accept';
-
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- }
-
- }
-
- /**
- * Вывод шаблона рубрики
- *
- * @param int $show
- * @param int $extern
- */
- function rubricTemplateShow($show = '', $extern = '0')
- {
- global $AVE_DB, $AVE_Template;
-
- if ($extern == 1)
- {
- $fetchId = (isset($_REQUEST['rubric_id']) && is_numeric($_REQUEST['rubric_id'])) ? $_REQUEST['rubric_id'] : 0;
- }
- else
- {
- $fetchId = (isset($_REQUEST['Id']) && is_numeric($_REQUEST['Id'])) ? $_REQUEST['Id'] : 0;
- }
-
- $rubric = $AVE_DB->Query("
- SELECT
- rubric_title,
- rubric_template,
- rubric_header_template,
- rubric_teaser_template,
- rubric_admin_teaser_template,
- rubric_description
- FROM " . PREFIX . "_rubrics
- WHERE Id = '" . $fetchId . "'
- ")
- ->FetchRow();
-
- // Поля
- $sql = $AVE_DB->Query("
- SELECT
- a.*, b.group_title, b.group_description, b.group_position
- FROM
- " . PREFIX . "_rubric_fields AS a
- LEFT JOIN
- " . PREFIX . "_rubric_fields_group AS b
- ON a.rubric_field_group = b.Id
- WHERE
- a.rubric_id = '" . $fetchId . "'
- ORDER BY
- b.group_position ASC, a.rubric_field_position ASC
- ");
-
- $fields_list = array();
- $drop_down_fields = array();
-
- while ($row = $sql->FetchRow())
- {
- $group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
-
- if ($row->rubric_field_type == 'drop_down' || $row->rubric_field_type == 'drop_down_key')
- array_push($drop_down_fields, $row->Id);
-
- $fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
- $fields_list[$group_id]['group_title'] = $row->group_title;
- $fields_list[$group_id]['group_description'] = $row->group_description;
- $fields_list[$group_id]['fields'][$row->Id]['Id'] = $row->Id;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_id'] = $row->rubric_id;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_group'] = $row->rubric_field_group;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_alias'] = $row->rubric_field_alias;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_title'] = $row->rubric_field_title;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_type'] = $row->rubric_field_type;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_numeric'] = $row->rubric_field_numeric;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_default'] = $row->rubric_field_default;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_search'] = $row->rubric_field_search;
- }
-
- $fields_list = msort($fields_list, 'group_position');
-
- $AVE_Template->assign('groups_count', count($fields_list));
- $AVE_Template->assign('fields_list', $fields_list);
-
- $AVE_Template->assign('field_array', get_field_type());
-
- if ($show == 1 )
- $rubric->rubric_template = stripslashes($_POST['rubric_template']);
-
- if ($extern == 1)
- {
- $AVE_Template->assign('ddid', implode(',', $drop_down_fields));
- }
- else
- {
- $AVE_Template->assign('rubric', $rubric);
- $AVE_Template->assign('formaction', 'index.php?do=rubs&action=template&sub=save&Id=' . $fetchId . '&cp=' . SESSION);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/form.tpl'));
- }
- }
-
- /**
- * Редактирование шаблона рубрики
- *
- * @param string $data
- */
- function rubricTemplateSave($Rtemplate, $Htemplate = '', $Ttemplate = '', $Atemplate = '')
- {
- global $AVE_DB, $AVE_Template;
-
- $rubric_id = (int)$_REQUEST['Id'];
-
- $sql = $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubrics
- SET
- rubric_template = '" . ($Rtemplate) . "',
- rubric_header_template = '" . $Htemplate . "',
- rubric_teaser_template = '" . $Ttemplate . "',
- rubric_admin_teaser_template = '" . $Atemplate . "'
- WHERE Id = '" . $rubric_id . "'
- ");
-
- // Очищаем кэш шаблона документов рубрики
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_template_cache
- WHERE rub_id = '" . $rubric_id . "'
- ");
-
- if ($sql === false) {
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL_ERR');
- $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
- $theme = 'error';
- } else {
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL');
- $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
- $theme = 'accept';
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_TEMPL_RUB') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
- }
-
- $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents WHERE rubric_id = ".$rubric_id);
-
- while ($row = $sql->FetchRow())
- {
- $AVE_DB->clearcache('doc_'.$row->Id);
- $AVE_DB->clearcompile('doc_'.$row->Id);
- }
-
- if (isAjax()) {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- } else {
- $AVE_Template->assign('message', $message);
- header('Location:index.php?do=rubs&cp=' . SESSION);
- exit;
- }
-
- }
-
- /**
- * Управление правами доступа к документам рубрик
- *
- * @param int $rubric_id идентификатор рубрики
- */
- function rubricPermissionSave($rubric_id = 0)
- {
- global $AVE_DB, $AVE_Template;
-
- if (check_permission_acp('rubric_perms') && is_numeric($rubric_id) && $rubric_id > 0)
- {
- foreach ($_POST['user_group'] as $key => $user_group_id)
- {
- $exist = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_rubric_permissions
- WHERE user_group_id = '" . $user_group_id . "'
- AND rubric_id = '" . $rubric_id . "'
- LIMIT 1
- ")->NumRows();
-
- $rubric_permission = @implode('|', $_POST['perm'][$key]);
- if ($exist)
- {
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubric_permissions
- SET rubric_permission = '" . $rubric_permission . "'
- WHERE user_group_id = '" . $user_group_id . "'
- AND rubric_id = '" . $rubric_id . "'
- ");
- }
- else
- {
- $AVE_DB->Query("
- INSERT " . PREFIX . "_rubric_permissions
- SET
- rubric_id = '" . $rubric_id . "',
- user_group_id = '" . $user_group_id . "',
- rubric_permission = '" . $rubric_permission . "'
- ");
- }
- }
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_PERMS');
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL');
$header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
$theme = 'accept';
- reportLog($AVE_Template->get_config_vars('RUBRIK_REPORT_PERMISION') . ' (' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ') (Id:' . $rubric_id . ')');
- if (isAjax()) {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- } else {
- header('Location:index.php?do=rubs&action=edit&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
+ if (isAjax()) {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
}
+
}
- }
- /**
- * Получить наименование и URL-префикс Рубрики по идентификатору
- *
- * @param int $rubric_id идентификатор Рубрики
- * @return object наименование Рубрики
- */
- function rubricNameByIdGet($rubric_id = 0)
- {
- global $AVE_DB;
-
- static $rubrics = array();
-
- if (!isset($rubrics[$rubric_id]))
+ function rubricFieldChange($field_id, $rubric_id)
{
- $rubrics[$rubric_id] = $AVE_DB->Query("
- SELECT
- rubric_title,
- rubric_alias,
- rubric_description
- FROM " . PREFIX . "_rubrics
- WHERE Id = '" . $rubric_id . "'
- LIMIT 1
- ")->FetchRow();
- }
-
- return $rubrics[$rubric_id];
- }
-
- /**
- * Формирование прав доступа Групп пользователей на все Рубрики
- *
- */
- function rubricPermissionFetch()
- {
- global $AVE_DB, $AVE_Document, $AVE_Template;
-
- $items = array();
-
- $sql = $AVE_DB->Query("
- SELECT
- Id,
- rubric_title,
- rubric_docs_active
- FROM
- " . PREFIX . "_rubrics
- ORDER
- BY rubric_position
- ");
-
- while ($row = $sql->FetchRow())
- {
- $AVE_Document->documentPermissionFetch($row->Id);
-
- if (defined('UGROUP') && UGROUP == 1) $row->Show = 1;
- elseif (isset($_SESSION[$row->Id . '_editown']) && $_SESSION[$row->Id . '_editown'] == 1) $row->Show = 1;
- elseif (isset($_SESSION[$row->Id . '_editall']) && $_SESSION[$row->Id . '_editall'] == 1) $row->Show = 1;
- elseif (isset($_SESSION[$row->Id . '_new']) && $_SESSION[$row->Id . '_new'] == 1) $row->Show = 1;
- elseif (isset($_SESSION[$row->Id . '_newnow']) && $_SESSION[$row->Id . '_newnow'] == 1) $row->Show = 1;
- elseif (isset($_SESSION[$row->Id . '_alles']) && $_SESSION[$row->Id . '_alles'] == 1) $row->Show = 1;
-
- array_push($items, $row);
- }
-
- $AVE_Template->assign('rubrics', $items);
- }
-
- /**
- * Получить
- */
- function rubricAliasAdd()
- {
- global $AVE_DB, $AVE_Template;
+ global $AVE_DB, $AVE_Template;
$sql = $AVE_DB->Query("
SELECT
- a.rubric_title,
- b.rubric_field_title,
- b.rubric_field_alias
+ *
FROM
- " . PREFIX . "_rubrics AS a
- JOIN
- " . PREFIX . "_rubric_fields AS b
+ " . PREFIX . "_rubric_fields
WHERE
- a.Id = '" . $_REQUEST['rubric_id'] . "'
+ rubric_id = '" . $rubric_id . "'
AND
- b.Id = '" . $_REQUEST['field_id'] . "'
+ Id = " . $field_id . "
")->FetchAssocArray();
- $AVE_Template->assign($sql);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/alias.tpl'));
- }
-
- function rubricAliasCheck($rubric_id, $field_id, $value)
- {
-
- global $AVE_DB, $AVE_Template;
-
- $errors = array();
-
- if(!intval($rubric_id)>0){
- $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_RUBID');
+ $AVE_Template->assign('rf', $sql);
+ $AVE_Template->assign('fields', get_field_type());
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/change.tpl'));
}
- if(!intval($field_id)>0) {
- $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_FIELDID');
- };
-
- if(!preg_match('/^[A-Za-z][[:word:]]{0,19}$/', $value)) {
- $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_MATCH');
- };
-
- //Проверяем есть такой алиас уже
- $res = $AVE_DB->Query("
- SELECT COUNT(*)
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- Id <> " . intval($field_id) . "
- AND rubric_id = " . intval($rubric_id) . "
- AND rubric_field_alias = '" . addslashes($value) . "'
- ")->GetCell();
-
- if($res>0){
- $errors[] = $AVE_Template->get_config_vars('RUBRIK_ALIAS_MATCH');
- };
-
- if (empty($errors))
+ function rubricFieldChangeSave($field_id, $rubric_id)
{
+ global $AVE_DB, $AVE_Template;
+
$AVE_DB->Query("
UPDATE " . PREFIX . "_rubric_fields
SET
- rubric_field_alias = '" . addslashes($value) . "'
+ rubric_field_type = '" . trim($_POST['rubric_field_type']) . "'
WHERE
- Id = '" . intval($field_id) . "'
- AND rubric_id = '" . intval($rubric_id) . "'
- ");
- $AVE_Template->assign('success', true);
- }
- else
- {
- $AVE_Template->assign('errors', $errors);
- }
-
- $sql = $AVE_DB->Query("
- SELECT
- a.rubric_title,
- b.rubric_field_title,
- b.rubric_field_alias
- FROM " . PREFIX . "_rubrics AS a
- JOIN
- " . PREFIX . "_rubric_fields AS b
- WHERE a.Id = '" . $_REQUEST['rubric_id'] . "'
- AND b.Id = '" . $_REQUEST['field_id'] . "'
- ")->FetchAssocArray();
-
- $AVE_Template->assign($sql);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/alias.tpl'));
- }
-
- function rubricFieldTemplate() {
- global $AVE_DB, $AVE_Template;
-
- $field = $AVE_DB->Query("
- SELECT
- a.rubric_title,
- b.rubric_field_default,
- b.rubric_field_title,
- b.rubric_field_template,
- b.rubric_field_template_request,
- b.rubric_field_description
- FROM " . PREFIX . "_rubrics AS a
- JOIN
- " . PREFIX . "_rubric_fields AS b
- WHERE a.Id = '" . $_REQUEST['rubric_id'] . "'
- AND b.Id = '" . $_REQUEST['field_id'] . "'
- ")->FetchAssocArray();
-
- $AVE_Template->assign($field);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/field_template.tpl'));
- }
-
- function rubricFieldTemplateSave($id, $rubric_id) {
- global $AVE_DB, $AVE_Template;
-
- $sql = $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubric_fields
- SET
- rubric_field_default = '" . $_POST['rubric_field_default'] . "',
- rubric_field_template = '" . $_POST['rubric_field_template'] . "',
- rubric_field_template_request = '" . $_POST['rubric_field_template_request'] . "',
- rubric_field_description = '" . $_POST['rubric_field_description'] . "'
- WHERE
- Id = '" . $id . "'
- ");
-
- if ($sql->_result === false) {
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL_ERR');
- $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
- $theme = 'error';
-
- if (isAjax() && !$_REQUEST['save']) {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- } else {
- $this->rubricFieldTemplate();
- exit;
- }
-
- }else{
-
- $AVE_DB->clearcache('rub_'.$rubric_id);
-
- $sql = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_documents");
-
- while ($row = $sql->FetchRow())
- {
- $AVE_DB->clearcache('doc_'.$row->Id);
- $AVE_DB->clearcompile('doc_'.$row->Id);
- $AVE_DB->clearcacherequest('doc_'.$row->Id);
- }
-
- // Очищаем кэш шаблона документов рубрики
- $AVE_DB->Query("
- DELETE
- FROM " . PREFIX . "_rubric_template_cache
- WHERE rub_id = '" . $rubric_id . "'
- ");
-
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_FLDTPL');
- $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
- $theme = 'accept';
-
- if (isAjax()) {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- }
- }
-
- }
-
- function rubricFieldChange($field_id, $rubric_id)
- {
- global $AVE_DB, $AVE_Template;
-
- $sql = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- rubric_id = '" . $rubric_id . "'
- AND
- Id = " . $field_id . "
- ")->FetchAssocArray();
-
- $AVE_Template->assign('rf', $sql);
- $AVE_Template->assign('fields', get_field_type());
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/change.tpl'));
- }
-
- function rubricFieldChangeSave($field_id, $rubric_id)
- {
- global $AVE_DB, $AVE_Template;
-
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubric_fields
- SET
- rubric_field_type = '" . trim($_POST['rubric_field_type']) . "'
- WHERE
- Id = '" . $field_id . "'
- AND
- rubric_id = '" . $rubric_id . "'
- ");
-
- $sql = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- rubric_id = '" . $rubric_id . "'
- AND
- Id = " . $field_id . "
- ")->FetchAssocArray();
-
- $AVE_Template->assign('rf', $sql);
- $AVE_Template->assign('fields', get_field_type());
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/change.tpl'));
- }
-
-
- function rubricFieldsGroups($rubric_id)
- {
- global $AVE_DB, $AVE_Template;
-
- $sql = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields_group
- WHERE
- rubric_id = '" . $rubric_id . "'
- ORDER BY
- group_position
- ");
-
- $groups = array();
-
- while($row = $sql->FetchRow())
- {
- array_push($groups, $row);
- }
-
- $AVE_Template->assign('rubric', $this->rubricNameByIdGet($rubric_id));
- $AVE_Template->assign('groups', $groups);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields_groups.tpl'));
- }
-
- /**
- * Сортировка групп полей рубрики
- *
- * @param array $sorted последовательность id полей
- */
- function rubricFieldsGroupsSort()
- {
- global $AVE_DB, $AVE_Template;
-
- foreach ($_REQUEST['sort'] as $position => $group_id)
- {
- $position++;
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_rubric_fields_group
- SET
- group_position = '" . (int)$position . "'
- WHERE
- Id = '" . (int)$group_id . "'
- ");
- }
-
- if (isAjax())
- {
- $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
- $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
- $theme = 'accept';
-
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- }
- }
-
-
- function rubricNewGroupFields($rubric_id)
- {
- global $AVE_DB;
-
- $position = $AVE_DB->Query("
- SELECT
- MAX(group_position)
- FROM
- " . PREFIX . "_rubric_fields_group
- WHERE
- rubric_id = '" . $rubric_id . "'
- ")->GetCell();
-
- $position++;
-
- $AVE_DB->Query("
- INSERT
- " . PREFIX . "_rubric_fields_group
- SET
- rubric_id = '" . $rubric_id . "',
- group_position = '" . $position . "',
- group_title= '" . $_REQUEST['group_title'] . "'
- ");
-
- header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
- }
-
-
- function rubricEditGroupFields($rubric_id)
- {
- global $AVE_DB;
-
- foreach($_REQUEST['group_title'] as $k => $v)
- {
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_rubric_fields_group
- SET
- group_title= '" . $v . "'
- WHERE
- Id = '" . $k . "'
- ");
- }
-
- header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
- }
-
- function rubricDelGroupFields($Id, $rubric_id)
- {
- global $AVE_DB;
-
- $AVE_DB->Query("
- DELETE FROM
- " . PREFIX . "_rubric_fields_group
- WHERE
- Id = '" . $Id . "'
- ");
-
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_rubric_fields
- SET
- rubric_field_group = '0'
- WHERE
- rubric_field_group = '" . $Id . "'
- AND
- rubric_id = '" . $rubric_id . "'
- ");
-
- header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
- exit;
- }
-
-
- function rubricFieldGroupChange($field_id, $rubric_id)
- {
-
- global $AVE_DB, $AVE_Template;
-
- $sql = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- rubric_id = '" . $rubric_id . "'
- AND
- Id = " . $field_id . "
- ")->FetchAssocArray();
-
- $AVE_Template->assign('rf', $sql);
- $AVE_Template->assign('groups', $this->get_rubric_fields_group($rubric_id));
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/groups.tpl'));
- }
-
- function rubricFieldGroupChangeSave($field_id, $rubric_id)
- {
- global $AVE_DB, $AVE_Template;
-
- $AVE_DB->Query("
- UPDATE " . PREFIX . "_rubric_fields
- SET
- rubric_field_group = '" . trim($_POST['rubric_field_group']) . "'
- WHERE
- Id = '" . $field_id . "'
- AND
- rubric_id = '" . $rubric_id . "'
- ");
-
- $sql = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- rubric_id = '" . $rubric_id . "'
- AND
- Id = " . $field_id . "
- ")->FetchAssocArray();
-
- $AVE_Template->assign('rf', $sql);
- $AVE_Template->assign('groups', $this->get_rubric_fields_group($rubric_id));
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/groups.tpl'));
- }
-
- // Список дополнительных шаблон для данной рубрики
- function tmplsList()
- {
- global $AVE_DB, $AVE_Template;
-
- $templates = array();
-
- $num = $AVE_DB->Query("
- SELECT
- COUNT(*)
- FROM
- " . PREFIX . "_rubric_templates
- WHERE
- rubric_id = '" . $_REQUEST['Id'] . "'
- ")->GetCell();
-
- $page_limit = $this->_limit;
-
- $pages = ceil($num / $page_limit);
-
- $set_start = get_current_page() * $page_limit - $page_limit;
-
- if ($num > $page_limit)
- {
- $page_nav = " {t} ";
- $page_nav = get_pagination($pages, 'page', $page_nav);
- $AVE_Template->assign('page_nav', $page_nav);
- }
-
- $sql = $AVE_DB->Query("
- SELECT
- rub.*,
- rubrics.rubric_title,
- COUNT(doc.Id) AS doc_count
- FROM
- " . PREFIX . "_rubric_templates AS rub
- LEFT JOIN
- " . PREFIX . "_rubrics AS rubrics
- ON rubrics.Id = rub.rubric_id
- LEFT JOIN
- " . PREFIX . "_documents AS doc
- ON (doc.rubric_id = rub.rubric_id AND doc.rubric_tmpl_id = rub.id)
- WHERE
- rub.rubric_id = '" . (int)$_REQUEST['Id'] . "'
- GROUP
- BY rub.id
- ORDER
- BY rub.id
- LIMIT
- " . $set_start . "," . $page_limit
- );
-
- while ($row = $sql->FetchRow())
- {
- $row->author_id = get_username_by_id($row->author_id);
- array_push($templates, $row);
- }
-
- $rubric = $this->rubricNameByIdGet((int)$_REQUEST['Id']);
-
- $AVE_Template->assign('rubric', $rubric);
- $AVE_Template->assign('templates', $templates);
- }
-
- /**
- * Вывод шаблона рубрики
- *
- * @param int $show
- * @param int $extern
- */
- function tmplsEdit()
- {
- global $AVE_DB, $AVE_Template;
-
- $tmpls_id = (isset($_REQUEST['id']) && is_numeric($_REQUEST['id'])) ? $_REQUEST['id'] : 0;
- $rubric_id = (int)$_REQUEST['rubric_id'];
-
- if ($tmpls_id)
- {
- $template = $AVE_DB->Query("
- SELECT
- title,
- template
- FROM
- " . PREFIX . "_rubric_templates
- WHERE
- id = '" . $tmpls_id . "'
- ")
- ->FetchRow();
- }
-
- if ($_REQUEST['action'] == 'tmpls_from')
- {
- $template = $AVE_DB->Query("
- SELECT
- rubric_title as title,
- rubric_template as template
- FROM
- " . PREFIX . "_rubrics
- WHERE
- Id = '" . $rubric_id . "'
- ")
- ->FetchRow();
- }
-
- if ($_REQUEST['action'] == 'tmpls_copy')
- {
- $template = $AVE_DB->Query("
- SELECT
- title,
- template
- FROM
- " . PREFIX . "_rubric_templates
- WHERE
- id = '" . $_REQUEST['tmpls_id'] . "'
- ")
- ->FetchRow();
- }
-
- // Поля
- $sql = $AVE_DB->Query("
- SELECT
- a.*, b.group_title, b.group_description, b.group_position
- FROM
- " . PREFIX . "_rubric_fields AS a
- LEFT JOIN
- " . PREFIX . "_rubric_fields_group AS b
- ON a.rubric_field_group = b.Id
- WHERE
- a.rubric_id = '" . $rubric_id . "'
- ORDER BY
- b.group_position ASC, a.rubric_field_position ASC
- ");
-
- $fields_list = array();
- $drop_down_fields = array();
-
- while ($row = $sql->FetchRow())
- {
- $group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
-
- if ($row->rubric_field_type == 'drop_down' || $row->rubric_field_type == 'drop_down_key')
- array_push($drop_down_fields, $row->Id);
-
- $fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
- $fields_list[$group_id]['group_title'] = $row->group_title;
- $fields_list[$group_id]['group_description'] = $row->group_description;
- $fields_list[$group_id]['fields'][$row->Id]['Id'] = $row->Id;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_id'] = $row->rubric_id;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_group'] = $row->rubric_field_group;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_alias'] = $row->rubric_field_alias;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_title'] = $row->rubric_field_title;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_type'] = $row->rubric_field_type;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_numeric'] = $row->rubric_field_numeric;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_default'] = $row->rubric_field_default;
- $fields_list[$group_id]['fields'][$row->Id]['rubric_field_search'] = $row->rubric_field_search;
- }
-
- $fields_list = msort($fields_list, 'group_position');
-
- $AVE_Template->assign('groups_count', count($fields_list));
- $AVE_Template->assign('fields_list', $fields_list);
-
- $AVE_Template->assign('field_array', get_field_type());
-
- $rubric = $this->rubricNameByIdGet($rubric_id);
-
- $AVE_Template->assign('rubric', $rubric);
-
- $AVE_Template->assign('template', $template);
-
- $AVE_Template->assign('formaction', 'index.php?do=rubs&action=tmpls_edit&sub=save&id=' . $tmpls_id . '&rubric_id=' . $_REQUEST['rubric_id'] . '&cp=' . SESSION);
- $AVE_Template->assign('content', $AVE_Template->fetch('rubs/tmpls_form.tpl'));
- }
-
-
- /**
- * Редактирование шаблона рубрики
- *
- * @param string $data
- */
- function tmplsSave($template = '', $title = '')
- {
- global $AVE_DB, $AVE_Template;
-
- $tmpls_id = (int)$_REQUEST['id'];
- $rubric_id = (int)$_REQUEST['rubric_id'];
-
- if ($tmpls_id)
- {
- $sql = $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_rubric_templates
- SET
- title = '" . $title . "',
- template = '" . $template . "'
- WHERE
- id = '" . $tmpls_id . "'
- ");
- }
- else
- {
- $sql = $AVE_DB->Query("
- INSERT INTO
- " . PREFIX . "_rubric_templates
- SET
- title = '" . $title . "',
- template = '" . $template . "',
- rubric_id = '" . $rubric_id . "',
- author_id = '" . UID . "',
- created = '" . time() . "'
- ");
-
- $tmpls_id = $AVE_DB->InsertId();
- }
-
- // Очищаем кэш шаблона документов рубрики
- $AVE_DB->Query("
- DELETE
- FROM
- " . PREFIX . "_rubric_template_cache
- WHERE
- rub_id = '" . $rubric_id . "'
- AND
- rub_tmpl_id = '" . $tmpls_id . "'
- ");
-
- if ($sql === false)
- {
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL_ERR');
- $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
- $theme = 'error';
- }
- else
- {
- $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL');
- $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
- $theme = 'accept';
- reportLog($AVE_Template->get_config_vars('RUBRIC_TEMPL_REPORT') . ' ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ' (Id шаблона:' . $tmpls_id . ')');
- }
-
- $sql = $AVE_DB->Query("
- SELECT
- Id
- FROM
- " . PREFIX . "_documents
- WHERE
- rubric_id = ".$rubric_id."
- AND
- rubric_tmpl_id = " . $tmpls_id
- );
-
- while ($row = $sql->FetchRow())
- {
- $AVE_DB->clearcache('doc_'.$row->Id);
- $AVE_DB->clearcompile('doc_'.$row->Id);
- }
-
- if (isAjax())
- {
- echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
- exit;
- }
- else
- {
- $AVE_Template->assign('message', $message);
- header('Location:index.php?do=rubs&action=tmpls&Id='.$rubric_id.'&cp=' . SESSION);
- exit;
- }
- }
-
- function tmplsDelete()
- {
- global $AVE_DB, $AVE_Template;
-
- $rubric_id = (int)$_REQUEST['rubric_id'];
- $tmpls_id = (int)$_REQUEST['tmpls_id'];
-
- $rubric_not_empty = $AVE_DB->Query("
- SELECT 1
- FROM " . PREFIX . "_documents
- WHERE
- rubric_id = '" . $rubric_id . "'
- AND
- rubric_tmpl_id = '" . $tmpls_id . "'
- LIMIT 1
- ")->GetCell();
-
- if (! $rubric_not_empty)
- {
- $AVE_DB->Query("
- DELETE
- FROM
- " . PREFIX . "_rubric_templates
- WHERE
- id = '" . $tmpls_id . "'
+ Id = '" . $field_id . "'
AND
rubric_id = '" . $rubric_id . "'
");
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ AND
+ Id = " . $field_id . "
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign('rf', $sql);
+ $AVE_Template->assign('fields', get_field_type());
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/change.tpl'));
+ }
+
+
+ function rubricFieldsGroups($rubric_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_rubric_fields_group
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ ORDER BY
+ group_position
+ ");
+
+ $groups = array();
+
+ while($row = $sql->FetchRow())
+ {
+ array_push($groups, $row);
+ }
+
+ $AVE_Template->assign('rubric', $this->rubricNameByIdGet($rubric_id));
+ $AVE_Template->assign('groups', $groups);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/fields_groups.tpl'));
+ }
+
+ /**
+ * Сортировка групп полей рубрики
+ *
+ * @param array $sorted последовательность id полей
+ */
+ function rubricFieldsGroupsSort()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ foreach ($_REQUEST['sort'] as $position => $group_id)
+ {
+ $position++;
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubric_fields_group
+ SET
+ group_position = '" . (int)$position . "'
+ WHERE
+ Id = '" . (int)$group_id . "'
+ ");
+ }
+
+ if (isAjax())
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIK_SORTED');
+ $header = $AVE_Template->get_config_vars('RUBRIK_FILDS_SUCCESS');
+ $theme = 'accept';
+
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+ }
+
+
+ function rubricNewGroupFields($rubric_id)
+ {
+ global $AVE_DB;
+
+ $position = $AVE_DB->Query("
+ SELECT
+ MAX(group_position)
+ FROM
+ " . PREFIX . "_rubric_fields_group
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ ")->GetCell();
+
+ $position++;
+
+ $AVE_DB->Query("
+ INSERT
+ " . PREFIX . "_rubric_fields_group
+ SET
+ rubric_id = '" . $rubric_id . "',
+ group_position = '" . $position . "',
+ group_title= '" . $_REQUEST['group_title'] . "'
+ ");
+
+ header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+ }
+
+
+ function rubricEditGroupFields($rubric_id)
+ {
+ global $AVE_DB;
+
+ foreach($_REQUEST['group_title'] as $k => $v)
+ {
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubric_fields_group
+ SET
+ group_title= '" . $v . "'
+ WHERE
+ Id = '" . $k . "'
+ ");
+ }
+
+ header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+ }
+
+ function rubricDelGroupFields($Id, $rubric_id)
+ {
+ global $AVE_DB;
+
+ $AVE_DB->Query("
+ DELETE FROM
+ " . PREFIX . "_rubric_fields_group
+ WHERE
+ Id = '" . $Id . "'
+ ");
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubric_fields
+ SET
+ rubric_field_group = '0'
+ WHERE
+ rubric_field_group = '" . $Id . "'
+ AND
+ rubric_id = '" . $rubric_id . "'
+ ");
+
+ header('Location:index.php?do=rubs&action=fieldsgroups&Id=' . $rubric_id . '&cp=' . SESSION);
+ exit;
+ }
+
+
+ function rubricFieldGroupChange($field_id, $rubric_id)
+ {
+
+ global $AVE_DB, $AVE_Template;
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ AND
+ Id = " . $field_id . "
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign('rf', $sql);
+ $AVE_Template->assign('groups', $this->get_rubric_fields_group($rubric_id));
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/groups.tpl'));
+ }
+
+ function rubricFieldGroupChangeSave($field_id, $rubric_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_rubric_fields
+ SET
+ rubric_field_group = '" . trim($_POST['rubric_field_group']) . "'
+ WHERE
+ Id = '" . $field_id . "'
+ AND
+ rubric_id = '" . $rubric_id . "'
+ ");
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ AND
+ Id = " . $field_id . "
+ ")->FetchAssocArray();
+
+ $AVE_Template->assign('rf', $sql);
+ $AVE_Template->assign('groups', $this->get_rubric_fields_group($rubric_id));
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/groups.tpl'));
+ }
+
+ // Список дополнительных шаблон для данной рубрики
+ function tmplsList()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $templates = array();
+
+ $num = $AVE_DB->Query("
+ SELECT
+ COUNT(*)
+ FROM
+ " . PREFIX . "_rubric_templates
+ WHERE
+ rubric_id = '" . $_REQUEST['Id'] . "'
+ ")->GetCell();
+
+ $page_limit = $this->_limit;
+
+ $pages = ceil($num / $page_limit);
+
+ $set_start = get_current_page() * $page_limit - $page_limit;
+
+ if ($num > $page_limit)
+ {
+ $page_nav = " {t} ";
+ $page_nav = get_pagination($pages, 'page', $page_nav);
+ $AVE_Template->assign('page_nav', $page_nav);
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rub.*,
+ rubrics.rubric_title,
+ COUNT(doc.Id) AS doc_count
+ FROM
+ " . PREFIX . "_rubric_templates AS rub
+ LEFT JOIN
+ " . PREFIX . "_rubrics AS rubrics
+ ON rubrics.Id = rub.rubric_id
+ LEFT JOIN
+ " . PREFIX . "_documents AS doc
+ ON (doc.rubric_id = rub.rubric_id AND doc.rubric_tmpl_id = rub.id)
+ WHERE
+ rub.rubric_id = '" . (int)$_REQUEST['Id'] . "'
+ GROUP
+ BY rub.id
+ ORDER
+ BY rub.id
+ LIMIT
+ " . $set_start . "," . $page_limit
+ );
+
+ while ($row = $sql->FetchRow())
+ {
+ $row->author_id = get_username_by_id($row->author_id);
+ array_push($templates, $row);
+ }
+
+ $rubric = $this->rubricNameByIdGet((int)$_REQUEST['Id']);
+
+ $AVE_Template->assign('rubric', $rubric);
+ $AVE_Template->assign('templates', $templates);
+ }
+
+ /**
+ * Вывод шаблона рубрики
+ *
+ * @param int $show
+ * @param int $extern
+ */
+ function tmplsEdit()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $tmpls_id = (isset($_REQUEST['id']) && is_numeric($_REQUEST['id'])) ? $_REQUEST['id'] : 0;
+ $rubric_id = (int)$_REQUEST['rubric_id'];
+
+ if ($tmpls_id)
+ {
+ $template = $AVE_DB->Query("
+ SELECT
+ title,
+ template
+ FROM
+ " . PREFIX . "_rubric_templates
+ WHERE
+ id = '" . $tmpls_id . "'
+ ")
+ ->FetchRow();
+ }
+
+ if ($_REQUEST['action'] == 'tmpls_from')
+ {
+ $template = $AVE_DB->Query("
+ SELECT
+ rubric_title as title,
+ rubric_template as template
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ Id = '" . $rubric_id . "'
+ ")
+ ->FetchRow();
+ }
+
+ if ($_REQUEST['action'] == 'tmpls_copy')
+ {
+ $template = $AVE_DB->Query("
+ SELECT
+ title,
+ template
+ FROM
+ " . PREFIX . "_rubric_templates
+ WHERE
+ id = '" . $_REQUEST['tmpls_id'] . "'
+ ")
+ ->FetchRow();
+ }
+
+ // Поля
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.*, b.group_title, b.group_description, b.group_position
+ FROM
+ " . PREFIX . "_rubric_fields AS a
+ LEFT JOIN
+ " . PREFIX . "_rubric_fields_group AS b
+ ON a.rubric_field_group = b.Id
+ WHERE
+ a.rubric_id = '" . $rubric_id . "'
+ ORDER BY
+ b.group_position ASC, a.rubric_field_position ASC
+ ");
+
+ $fields_list = array();
+ $drop_down_fields = array();
+
+ while ($row = $sql->FetchRow())
+ {
+ $group_id = ($row->rubric_field_group) ? $row->rubric_field_group : 0;
+
+ if ($row->rubric_field_type == 'drop_down' || $row->rubric_field_type == 'drop_down_key')
+ array_push($drop_down_fields, $row->Id);
+
+ $fields_list[$group_id]['group_position'] = ($row->group_position) ? $row->group_position : 100;
+ $fields_list[$group_id]['group_title'] = $row->group_title;
+ $fields_list[$group_id]['group_description'] = $row->group_description;
+ $fields_list[$group_id]['fields'][$row->Id]['Id'] = $row->Id;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_id'] = $row->rubric_id;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_group'] = $row->rubric_field_group;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_alias'] = $row->rubric_field_alias;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_title'] = $row->rubric_field_title;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_type'] = $row->rubric_field_type;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_numeric'] = $row->rubric_field_numeric;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_default'] = $row->rubric_field_default;
+ $fields_list[$group_id]['fields'][$row->Id]['rubric_field_search'] = $row->rubric_field_search;
+ }
+
+ $fields_list = msort($fields_list, 'group_position');
+
+ $AVE_Template->assign('groups_count', count($fields_list));
+ $AVE_Template->assign('fields_list', $fields_list);
+
+ $AVE_Template->assign('field_array', get_field_type());
+
+ $rubric = $this->rubricNameByIdGet($rubric_id);
+
+ $AVE_Template->assign('rubric', $rubric);
+
+ $AVE_Template->assign('template', $template);
+
+ $AVE_Template->assign('formaction', 'index.php?do=rubs&action=tmpls_edit&sub=save&id=' . $tmpls_id . '&rubric_id=' . $_REQUEST['rubric_id'] . '&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('rubs/tmpls_form.tpl'));
+ }
+
+
+ /**
+ * Редактирование шаблона рубрики
+ *
+ * @param string $data
+ */
+ function tmplsSave($template = '', $title = '')
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $tmpls_id = (int)$_REQUEST['id'];
+ $rubric_id = (int)$_REQUEST['rubric_id'];
+
+ if ($tmpls_id)
+ {
+ $sql = $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_rubric_templates
+ SET
+ title = '" . $title . "',
+ template = '" . $template . "'
+ WHERE
+ id = '" . $tmpls_id . "'
+ ");
+ }
+ else
+ {
+ $sql = $AVE_DB->Query("
+ INSERT INTO
+ " . PREFIX . "_rubric_templates
+ SET
+ title = '" . $title . "',
+ template = '" . $template . "',
+ rubric_id = '" . $rubric_id . "',
+ author_id = '" . UID . "',
+ created = '" . time() . "'
+ ");
+
+ $tmpls_id = $AVE_DB->InsertId();
+ }
+
// Очищаем кэш шаблона документов рубрики
$AVE_DB->Query("
DELETE
@@ -2015,12 +2044,390 @@ class AVE_Rubric
rub_tmpl_id = '" . $tmpls_id . "'
");
- // Сохраняем системное сообщение в журнал
- reportLog($AVE_Template->get_config_vars('RUBRIC_TMPLS_LOG_DEL') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (Id шаблона: '.$rubric_id.')');
+ if ($sql === false)
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL_ERR');
+ $header = $AVE_Template->get_config_vars('RUBRIK_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('RUBRIC_SAVED_TPL');
+ $header = $AVE_Template->get_config_vars('RUBRIC_SUCCESS');
+ $theme = 'accept';
+ reportLog($AVE_Template->get_config_vars('RUBRIC_TEMPL_REPORT') . ' ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title)) . ' (Id шаблона:' . $tmpls_id . ')');
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ Id
+ FROM
+ " . PREFIX . "_documents
+ WHERE
+ rubric_id = ".$rubric_id."
+ AND
+ rubric_tmpl_id = " . $tmpls_id
+ );
+
+ while ($row = $sql->FetchRow())
+ {
+ $AVE_DB->clearcache('doc_'.$row->Id);
+ $AVE_DB->clearcompile('doc_'.$row->Id);
+ }
+
+ if (isAjax())
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+ else
+ {
+ $AVE_Template->assign('message', $message);
+ header('Location:index.php?do=rubs&action=tmpls&Id='.$rubric_id.'&cp=' . SESSION);
+ exit;
+ }
}
- header('Location:index.php?do=rubs&action=tmpls&Id='.$rubric_id.'&cp=' . SESSION);
- exit;
+
+ function tmplsDelete()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['rubric_id'];
+ $tmpls_id = (int)$_REQUEST['tmpls_id'];
+
+ $rubric_not_empty = $AVE_DB->Query("
+ SELECT 1
+ FROM " . PREFIX . "_documents
+ WHERE
+ rubric_id = '" . $rubric_id . "'
+ AND
+ rubric_tmpl_id = '" . $tmpls_id . "'
+ LIMIT 1
+ ")->GetCell();
+
+ if (! $rubric_not_empty)
+ {
+ $AVE_DB->Query("
+ DELETE
+ FROM
+ " . PREFIX . "_rubric_templates
+ WHERE
+ id = '" . $tmpls_id . "'
+ AND
+ rubric_id = '" . $rubric_id . "'
+ ");
+
+ // Очищаем кэш шаблона документов рубрики
+ $AVE_DB->Query("
+ DELETE
+ FROM
+ " . PREFIX . "_rubric_template_cache
+ WHERE
+ rub_id = '" . $rubric_id . "'
+ AND
+ rub_tmpl_id = '" . $tmpls_id . "'
+ ");
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('RUBRIC_TMPLS_LOG_DEL') . ' - ' . stripslashes(htmlspecialchars($this->rubricNameByIdGet($rubric_id)->rubric_title, ENT_QUOTES)) . ' (Id шаблона: '.$rubric_id.')');
+ }
+
+ header('Location:index.php?do=rubs&action=tmpls&Id='.$rubric_id.'&cp=' . SESSION);
+ exit;
+ }
+
+
+
+ function _get_fields_type($type = null)
+ {
+ static $fields;
+
+ if (is_array($fields))
+ return $fields;
+
+ $arr = get_defined_functions();
+
+ $fields = array();
+ $field = array();
+
+ foreach ($arr['user'] as $v)
+ {
+ if (trim(substr($v, 0, strlen('get_field_'))) == 'get_field_')
+ {
+ $d = '';
+
+ $name = @$v('', 'name', '', '', 0, $d);
+
+ $id = substr($v, strlen('get_field_'));
+
+ if ($name != false && is_string($name))
+ $fields[] = array('id' => $id,'name' => (isset($fields_vars[$name])
+ ? $fields_vars[$name]
+ : $name));
+
+ if (! empty($type) && $id == $type)
+ $field = array('id' => $id,'name' => (isset($fields_vars[$name])
+ ? $fields_vars[$name]
+ : $name));
+ }
+ }
+
+ $fields = msort($fields, array('name'));
+
+ return (! empty($type)) ? $field : $fields;
+ }
+
+
+ function ShowFields()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['Id'];
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rubric_field_type
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ rubric_id = '".$rubric_id."'
+ GROUP BY
+ rubric_field_type
+ ");
+
+ $enable = array();
+
+ while ($row = $sql->FetchArray())
+ $enable[] = $row['rubric_field_type'];
+
+ $fields = $this->_get_fields_type();
+
+ foreach ($fields as $field)
+ {
+ $exists[$field['id']]['adm'] = file_exists(BASE_DIR . '/fields/' . $field['id'] . '/tpl/field.tpl');
+ $exists[$field['id']]['doc'] = file_exists(BASE_DIR . '/fields/' . $field['id'] . '/tpl/field-doc.tpl');
+ $exists[$field['id']]['req'] = file_exists(BASE_DIR . '/fields/' . $field['id'] . '/tpl/field-req.tpl');
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rubric_title,
+ rubric_linked_rubric,
+ rubric_description
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ id = '" . $rubric_id . "'
+ LIMIT 1
+ ");
+
+ $rubric = $sql->FetchRow();
+
+ $AVE_Template->assign('rubric', $rubric);
+ $AVE_Template->assign("enable", $enable);
+ $AVE_Template->assign("exists", $exists);
+ $AVE_Template->assign("fields", $fields);
+ $AVE_Template->assign("content", $AVE_Template->fetch('rubs/_fields_list.tpl'));
+ }
+
+
+ function ShowFieldsByType($fld)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $rubric_id = (int)$_REQUEST['rubric_id'];
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.Id,
+ a.rubric_id,
+ a.rubric_field_type,
+ a.rubric_field_title,
+ b.rubric_title
+ FROM
+ " . PREFIX . "_rubric_fields AS a
+ LEFT JOIN
+ " . PREFIX . "_rubrics AS b
+ ON a.rubric_id = b.Id
+ WHERE
+ a.rubric_field_type = '" . $fld ."'
+ AND
+ a.rubric_id = '".$rubric_id."'
+ ORDER BY
+ a.rubric_id
+ ");
+
+ $rubrics = array();
+
+ while ($row = $sql->FetchRow())
+ {
+ $rubrics[$row->rubric_id]['rubric_id'] = $row->rubric_id;
+ $rubrics[$row->rubric_id]['rubric_title'] = $row->rubric_title;
+ $rubrics[$row->rubric_id]['rubric_field_type'] = $row->rubric_field_type;
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['id'] = $row->Id;
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['title'] = $row->rubric_field_title;
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['adm_tpl'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field-' . $row->Id . '.tpl');
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['doc_tpl'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field-doc-' . $row->Id . '.tpl');
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['req_tpl'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field-req-' . $row->Id . '.tpl');
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['adm_main'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field.tpl');
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['doc_main'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field-doc.tpl');
+ $rubrics[$row->rubric_id]['fields'][$row->Id]['req_main'] = file_exists(BASE_DIR . '/fields/' . $fld . '/tpl/field-req.tpl');
+ }
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ rubric_title,
+ rubric_linked_rubric,
+ rubric_description
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ id = '" . $rubric_id . "'
+ LIMIT 1
+ ");
+
+ $rubric = $sql->FetchRow();
+
+ $AVE_Template->assign('rubric', $rubric);
+ $AVE_Template->assign('main', $this->_get_fields_type($fld));
+ $AVE_Template->assign("rubrics", $rubrics);
+ $AVE_Template->assign("content", $AVE_Template->fetch('rubs/_field_list.tpl'));
+ }
+
+
+ function EditFieldTpl($id = '', $fld, $type)
+ {
+ global $AVE_DB, $AVE_Template, $_fm_dir;
+
+ switch ($type)
+ {
+ case 'adm':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-' . $id . '.tpl';
+ $source = BASE_DIR . '/fields/' . $fld . '/tpl/field.tpl';
+ break;
+
+ case 'doc':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-doc-' . $id . '.tpl';
+ $source = BASE_DIR . '/fields/' . $fld . '/tpl/field-doc.tpl';
+ break;
+
+ case 'req':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-req-' . $id . '.tpl';
+ $source = BASE_DIR . '/fields/' . $fld . '/tpl/field-req.tpl';
+ break;
+ }
+
+ if (empty($id))
+ $file = $source;
+
+ if (file_exists($file))
+ $code_text = file_get_contents($file);
+ else
+ $code_text = file_get_contents($source);
+
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.rubric_field_title,
+ b.rubric_title
+ FROM
+ " . PREFIX . "_rubric_fields AS a
+ LEFT JOIN
+ " . PREFIX . "_rubrics AS b
+ ON a.rubric_id = b.Id
+ WHERE
+ a.rubric_field_type = '" . $fld ."'
+ AND
+ a.Id = '" . $id ."'
+ ")->FetchAssocArray();
+
+ $params =
+ array(
+ 'id' => $id,
+ 'fld' => $fld,
+ 'type' => $type,
+ 'func' => (file_exists($file) ? 'edit' : 'new'),
+ 'field' => $sql,
+ );
+
+ $AVE_Template->assign('main', $this->_get_fields_type($fld));
+ $AVE_Template->assign('params', $params);
+ $AVE_Template->assign('code_text', $code_text);
+ $AVE_Template->assign("content", $AVE_Template->fetch('rubs/_field_code.tpl'));
+ }
+
+
+ /**
+ * Сохранение шаблона
+ *
+ */
+ function SaveFieldTpl($id = '', $fld, $type, $func)
+ {
+ switch ($type)
+ {
+ case 'adm':
+ $file = (! empty($id))
+ ? BASE_DIR . '/fields/' . $fld . '/tpl/field-' . $id . '.tpl'
+ : BASE_DIR . '/fields/' . $fld . '/tpl/field.tpl';
+ break;
+
+ case 'doc':
+ $file = (! empty($id))
+ ? BASE_DIR . '/fields/' . $fld . '/tpl/field-doc-' . $id . '.tpl'
+ : BASE_DIR . '/fields/' . $fld . '/tpl/field-doc.tpl';
+ break;
+
+ case 'req':
+ $file = (! empty($id))
+ ? BASE_DIR . '/fields/' . $fld . '/tpl/field-req-' . $id . '.tpl'
+ : BASE_DIR . '/fields/' . $fld . '/tpl/field-req.tpl';
+ break;
+ }
+
+ $data = stripcslashes($_REQUEST['code_text']);
+
+ @file_put_contents($file, $data);
+ chmod($file, 0644);
+
+ $message = 'Шаблон успешнно сохранен';
+ $header = 'Выполнено';
+ $theme = 'accept';
+
+ echo json_encode(
+ array(
+ 'message' => $message,
+ 'header' => $header,
+ 'theme' => $theme)
+ );
+
+ exit;
+ }
+
+ /**
+ * Удаление шаблона поля
+ *
+ */
+ function DeleteFieldTpl($id, $fld, $type, $func)
+ {
+ switch ($type)
+ {
+ case 'adm':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-' . $id . '.tpl';
+ break;
+
+ case 'doc':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-doc-' . $id . '.tpl';
+ break;
+
+ case 'req':
+ $file = BASE_DIR . '/fields/' . $fld . '/tpl/field-req-' . $id . '.tpl';
+ break;
+ }
+
+ @unlink($file);
+
+ header('Location:' . get_referer_link());
+ exit;
+ }
}
-}
-?>
+?>
\ No newline at end of file
diff --git a/class/class.settings.php b/class/class.settings.php
index e1e9f83..07eb18b 100644
--- a/class/class.settings.php
+++ b/class/class.settings.php
@@ -218,6 +218,8 @@ class AVE_Settings
}
else
{
+ $this->clearSettingsCache();
+
$_SESSION['use_editor'] = intval($_REQUEST['use_editor']);
$message = $AVE_Template->get_config_vars('SETTINGS_SAVED');
$header = $AVE_Template->get_config_vars('SETTINGS_SUCCESS');
@@ -317,6 +319,7 @@ class AVE_Settings
$AVE_Template->assign('content', $AVE_Template->fetch('settings/settings_lang.tpl'));
}
+
/**
* Метод Редактирования параметров языков
*
@@ -340,6 +343,7 @@ class AVE_Settings
$AVE_Template->assign('content', $AVE_Template->fetch('settings/settings_lang_edit.tpl'));
}
+
function settingsLanguageEditSave()
{
global $AVE_DB, $AVE_Template;
@@ -589,5 +593,143 @@ class AVE_Settings
return true;
}
+ /**
+ * Функция очищает кеш системных настроек
+ *
+ */
+ function clearSettingsCache()
+ {
+ $cache_dir = BASE_DIR . '/cache/sql/settings/';
+
+ return rrmdir($cache_dir);
+ }
+
+
+ /**
+ * Функция редактирования robots.txt
+ *
+ */
+ function editRobots()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $file_name = 'robots.txt';
+
+ $_REQUEST['sub'] = (! isset($_REQUEST['sub']))
+ ? ''
+ : $_REQUEST['sub'];
+
+ switch ($_REQUEST['sub'])
+ {
+ case 'save':
+ $file = BASE_DIR . '/' . $file_name;
+
+ $template = stripcslashes($_REQUEST['code_text']);
+
+ $result = file_put_contents($file, trim($template));
+
+ if ($result === false)
+ {
+ $message = $AVE_Template->get_config_vars('SETTINGS_SAVED_ERR_FILE');
+ $header = $AVE_Template->get_config_vars('SETTINGS_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('SETTINGS_SAVED_FILE');
+ $header = $AVE_Template->get_config_vars('SETTINGS_SUCCESS');
+ $theme = 'accept';
+ }
+
+ if (isAjax())
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+ else
+ {
+ $AVE_Template->assign('message', $message);
+ header('Location:index.php?do=settings&cp=' . SESSION);
+ }
+ exit;
+
+ default:
+ $file = BASE_DIR . '/' . $file_name;
+
+ $template = file_get_contents($file);
+
+ $formaction = "index.php?do=settings&action=robots&sub=save&cp=" . SESSION;
+
+ $AVE_Template->assign('file_name', $file_name);
+ $AVE_Template->assign('formaction', $formaction);
+ $AVE_Template->assign('template', $template);
+ break;
+ }
+
+ $AVE_Template->assign('content', $AVE_Template->fetch('settings/edit_file.tpl'));
+ }
+
+
+ /**
+ * Функция редактирования func.custom.php
+ *
+ */
+ function editCustom()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ $file_name = 'func.custom.php';
+
+ $_REQUEST['sub'] = (! isset($_REQUEST['sub']))
+ ? ''
+ : $_REQUEST['sub'];
+
+ switch ($_REQUEST['sub'])
+ {
+ case 'save':
+ $file = BASE_DIR . '/functions/' . $file_name;
+
+ $template = stripcslashes($_REQUEST['code_text']);
+
+ $result = file_put_contents($file, trim($template));
+
+ if ($result === false)
+ {
+ $message = $AVE_Template->get_config_vars('SETTINGS_SAVED_ERR_FILE');
+ $header = $AVE_Template->get_config_vars('SETTINGS_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('SETTINGS_SAVED_FILE');
+ $header = $AVE_Template->get_config_vars('SETTINGS_SUCCESS');
+ $theme = 'accept';
+ }
+
+ if (isAjax())
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+ else
+ {
+ $AVE_Template->assign('message', $message);
+ header('Location:index.php?do=settings&cp=' . SESSION);
+ }
+ exit;
+
+ default:
+ $file = BASE_DIR . '/functions/' . $file_name;
+
+ $template = file_get_contents($file);
+
+ $formaction = "index.php?do=settings&action=robots&sub=save&cp=" . SESSION;
+
+ $AVE_Template->assign('file_name', $file_name);
+ $AVE_Template->assign('formaction', $formaction);
+ $AVE_Template->assign('template', $template);
+ break;
+ }
+
+ $AVE_Template->assign('content', $AVE_Template->fetch('settings/edit_file.tpl'));
+ }
}
?>
\ No newline at end of file
diff --git a/class/class.thumbnail.php b/class/class.thumbnail.php
index 3430164..297fbc2 100644
--- a/class/class.thumbnail.php
+++ b/class/class.thumbnail.php
@@ -161,7 +161,8 @@ class Image_Toolbox {
* integer $height imageheight of new image to be created
* string $fillcolor optional fill the new image with this color (hexformat, e.g. '#FF0000')
*/
- function Image_Toolbox() {
+ function __construct()
+ {
$args = func_get_args();
$argc = func_num_args();
diff --git a/class/class.user.php b/class/class.user.php
index f9aec22..f2fd027 100644
--- a/class/class.user.php
+++ b/class/class.user.php
@@ -32,24 +32,25 @@ class AVE_User
* @public array
*/
public $_allowed_admin_permission = array(
- 'alles', // все права
- 'adminpanel', // доступ в админку
- 'group_view', 'group_edit', // группы пользователей
- 'user_view', 'user_edit', 'user_perms', // пользователи
- 'template_view', 'template_edit', 'template_php', // шаблоны
- 'rubric_view', 'rubric_edit', 'rubric_php', 'rubric_perms', 'rubric_code', // рубрики
- 'document_view', 'document_php', 'document_revisions', // документы
- 'remark_view', 'remark_edit', // заметки
- 'request_view', 'request_edit', 'request_php', // запросы
- 'navigation_view', 'navigation_edit', // навигация
- 'blocks_view', 'blocks_edit', // визуальные блоки
- 'sysblocks_view', 'sysblocks_edit', // системные блоки
- 'modules_view', 'modules_admin', 'modules_system', // модули
- 'mediapool_int', 'mediapool_add', 'mediapool_del', 'mediapool_finder', // файловый менеджер
- 'gen_settings', 'gen_settings_more', 'gen_settings_countries', 'gen_settings_languages', // общие настройки
- 'db_actions', // база данных
- 'logs_view', 'logs_clear', // логи
- 'cache_clear', 'cache_thumb' // сессии и кеш
+ 'alles', // все права
+ 'adminpanel', // доступ в админку
+ 'group_view', 'group_edit', // группы пользователей
+ 'user_view', 'user_edit', 'user_perms', // пользователи
+ 'template_view', 'template_edit', 'template_php', // шаблоны
+ 'rubric_view', 'rubric_edit', 'rubric_php', 'rubric_perms', 'rubric_code', // рубрики
+ 'document_view', 'document_php', 'document_revisions', // документы
+ 'remark_view', 'remark_edit', // заметки
+ 'request_view', 'request_edit', 'request_php', // запросы
+ 'navigation_view', 'navigation_edit', // навигация
+ 'blocks_view', 'blocks_edit', // визуальные блоки
+ 'sysblocks_view', 'sysblocks_edit', // системные блоки
+ 'modules_view', 'modules_admin', 'modules_system', // модули
+ 'mediapool_int', 'mediapool_add', 'mediapool_del', 'mediapool_finder', // файловый менеджер
+ 'gen_settings', 'gen_settings_more', 'gen_settings_countries', 'gen_settings_languages', // общие настройки
+ 'gen_settings_robots', 'gen_settings_fcustom',
+ 'db_actions', // база данных
+ 'logs_view', 'logs_clear', // логи
+ 'cache_clear', 'cache_thumb' // сессии и кеш
);
/**
@@ -309,8 +310,10 @@ class AVE_User
SELECT
user_group_name,
user_group_permission
- FROM " . PREFIX . "_user_groups
- WHERE user_group = '" . $user_group_id . "'
+ FROM
+ " . PREFIX . "_user_groups
+ WHERE
+ user_group = '" . $user_group_id . "'
")->FetchRow();
}
@@ -321,9 +324,9 @@ class AVE_User
else
{
$AVE_Template->assign('g_all_permissions', $this->_allowed_admin_permission);
- $AVE_Template->assign('g_group_permissions', explode('|', $row->user_group_permission));
+ $AVE_Template->assign('g_group_permissions', array_diff(explode('|', $row->user_group_permission), array('')));
$AVE_Template->assign('g_name', $row->user_group_name);
- $AVE_Template->assign('modules', $AVE_Module->moduleListGet(1));
+ $AVE_Template->assign('modules', $AVE_Module->_modules);
}
}
diff --git a/fields/checkbox/field.php b/fields/checkbox/field.php
index 9820411..f4e2b3c 100644
--- a/fields/checkbox/field.php
+++ b/fields/checkbox/field.php
@@ -12,7 +12,7 @@
*/
// Чекбокс (Checkbox)
-function get_field_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_empty=0, &$maxlength=null, $document_fields=array(), $rubric_id=0, $default=null)
+function get_field_checkbox($field_value, $action, $field_id = 0, $tpl = '', $tpl_empty = 0, &$maxlength = null, $document_fields = array(), $rubric_id = 0, $default = null)
{
global $AVE_Template;
@@ -20,7 +20,9 @@ function get_field_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_em
$fld_dir = dirname(__FILE__) . '/';
$tpl_dir = $fld_dir . 'tpl/';
- $lang_file = $fld_dir . 'lang/' . (defined('ACP') ? $_SESSION['admin_language'] : $_SESSION['user_language']) . '.txt';
+ $lang_file = $fld_dir . 'lang/' . (defined('ACP')
+ ? $_SESSION['admin_language']
+ : $_SESSION['user_language']) . '.txt';
$AVE_Template->config_load($lang_file, 'lang');
$AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
@@ -36,19 +38,22 @@ function get_field_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_em
$AVE_Template->assign('doc_id', (isset($_REQUEST['Id']) ? (int)$_REQUEST['Id'] : 0));
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin');
- return $AVE_Template->fetch($tpl_file);
+ return $AVE_Template->fetch($tpl_file);
break;
case 'doc':
$field_value = clean_php($field_value);
- $res = ((int)$field_value === 1) ? (int)$field_value : 0;
+ $res = ((int)$field_value === 1)
+ ? (int)$field_value
+ : 0;
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc');
- if($tpl_empty && $tpl_file)
+ if ($tpl_empty && $tpl_file)
{
+ $AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $field_value);
return $AVE_Template->fetch($tpl_file);
}
@@ -59,12 +64,15 @@ function get_field_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_em
case 'req':
$field_value = clean_php($field_value);
- $res = ((int)$field_value === 1) ? (int)$field_value : 0;
+ $res = ((int)$field_value === 1)
+ ? (int)$field_value
+ : 0;
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'req');
- if($tpl_empty && $tpl_file)
+ if ($tpl_empty && $tpl_file)
{
+ $AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $field_value);
return $AVE_Template->fetch($tpl_file);
}
@@ -74,7 +82,9 @@ function get_field_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_em
case 'save':
$field_value = clean_php($field_value);
- $res = ((int)$field_value === 1) ? $field_value : '0';
+ $res = ((int)$field_value === 1)
+ ? $field_value
+ : '0';
break;
case 'name':
diff --git a/fields/image_mega/tpl/field-doc.tpl b/fields/image_mega/tpl/field-doc.tpl
index 40ae5cf..da7baa7 100755
--- a/fields/image_mega/tpl/field-doc.tpl
+++ b/fields/image_mega/tpl/field-doc.tpl
@@ -39,7 +39,7 @@ $image.http Есть ли в ссылке http или https (true/false)
{/if}
{if isset($image.description) && $image.description != ''}
- {$image.description}
+ {$image.description|html_entity_decode}
{/if}
diff --git a/fields/image_multi_new_3inputs/.gitkeep b/fields/image_multi_new_3inputs/.gitkeep
deleted file mode 100755
index e69de29..0000000
diff --git a/fields/image_multi_new_3inputs/css/.gitkeep b/fields/image_multi_new_3inputs/css/.gitkeep
deleted file mode 100755
index e69de29..0000000
diff --git a/fields/image_multi_new_3inputs/css/field.css b/fields/image_multi_new_3inputs/css/field.css
deleted file mode 100755
index 5a56003..0000000
--- a/fields/image_multi_new_3inputs/css/field.css
+++ /dev/null
@@ -1,96 +0,0 @@
-.cascad3 {
- position: relative;
-}
-
-.cascad3_item {
- display: inline-block;
- margin: 3px;
- width: 120px;
- height: 226px;
- background-color: rgba(255, 255, 255, 0.5);
- border: solid 1px #eaeaea;
- border-radius: 5px;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- position: relative;
- text-align: center;
-}
-
-.cascad3_item:hover {
- background-color: rgba(255, 255, 255, 1.0);
- border: solid 1px rgba(234, 234, 234, 0.5);
- -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1);
- -moz-box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1);
- box-shadow: 0 0 5px 2px rgba(0, 0, 0, 0.1);
-}
-
-.cascad3_item:hover > .header {
- background-color: rgba(210, 210, 210, 0.3);
-}
-
-.cascad3_item .header {
- background-color: rgba(210, 210, 210, 0.5);
- height: 26px;
- margin-bottom: 10px;
- cursor: move;
- border-radius: 5px 5px 0 0;
-}
-
-.cascad3_item .image {
- background-color: #fcfcfc;
- border: solid 1px #eaeaea;
- border-radius: 5px;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
-}
-
-.cascad3_item input {
- display: inline-block;
- width: 100px;
- margin-top: 5px;
- border-radius: 0 0 2px 2px;
- border: 1px solid #eaeaea !important;
- resize: none !important;
- box-shadow: none !important;
- -webkit-box-shadow: none !important;
- -moz-box-shadow: none !important;
- padding: 3px !important;
- box-sizing: border-box !important;
- -webkit-box-sizing: border-box !important;
- -moz-box-sizing: border-box !important;
-}
-
-.cascad3_item .view {
- position: absolute;
- top: 3px;
- left: 3px;
- cursor: pointer !important;
-}
-
-.cascad3_item .delete {
- position: absolute;
- top: 3px;
- right: 3px;
- cursor: pointer !important;
-}
-
-.cascad3_item .info {
- position: absolute;
- top: 30px;
- right: 3px;
- cursor: pointer !important;
-}
-
-.cascad3_sortable > .ui-state-highlight {
- display: inline-block;
- margin: 5px;
- width: 120px;
- height: 200px;
- background-color: rgba(255,255,255,0.5); !important;
- border: solid 1px #eaeaea;
- border-radius: 5px;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- position: relative;
- text-align: center;
-}
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/field.php b/fields/image_multi_new_3inputs/field.php
deleted file mode 100755
index 62c41f7..0000000
--- a/fields/image_multi_new_3inputs/field.php
+++ /dev/null
@@ -1,307 +0,0 @@
-config_load($lang_file, 'lang');
- $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
- $AVE_Template->config_load($lang_file, 'admin');
-
- $res = 0;
-
- $iniset_count = ini_get('max_file_uploads');
-
- switch ($action)
- {
- case 'edit':
-
- $items = array();
- $items = unserialize($field_value);
- $image_items = array();
-
- if($items != false){
-
- foreach($items as $k => $v){
- $image_item = explode('|', $v);
-
- $image[$k]['url'] = $image_item[0];
- $image[$k]['thumb'] = ($image_item[0] != '') ? make_thumbnail(array('size' => 'f100x100', 'link' => $image_item[0])) : $img_pixel;
- $image[$k]['desc'] = (isset($image_item[1])) ? htmlspecialchars($image_item[1], ENT_QUOTES) : '';
- $image[$k]['desc2'] = (isset($image_item[2])) ? htmlspecialchars($image_item[2], ENT_QUOTES) : '';
- $image[$k]['desc3'] = (isset($image_item[3])) ? htmlspecialchars($image_item[3], ENT_QUOTES) : '';
- }
-
- if (!empty($image)) {
- $image_items = $image;
- }
- }
-
- $show_upload = true;
-
- if(preg_match("/%id/i", $default))
- {
- if ($_REQUEST['action'] != 'new') {
- $path_upload = trim(@str_replace('%id', $_REQUEST['Id'], $default), '/');
- $show_upload = true;
- } else {
- $path_upload = (!empty($default)) ? trim($default, '/') : '';
- $show_upload = false;
- }
- }
- else
- {
- $path_upload = (!empty($default)) ? $default : '';
- $show_upload = true;
- }
-
- $dir_upload = '/' . UPLOAD_DIR . '/' . ((!empty($path_upload)) ? $path_upload . '/' : '');
-
- $tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin');
-
- $AVE_Template->assign('max_files', $AVE_Template->get_config_vars('max_f_f') . $iniset_count);
- $AVE_Template->assign('dir_upload', $AVE_Template->get_config_vars('upl_dir') . $dir_upload);
- $AVE_Template->assign('show_upload', $show_upload);
-
- $AVE_Template->assign('field_dir', $fld_name);
- $AVE_Template->assign('images', $image_items);
- $AVE_Template->assign('field_id', $field_id);
- $AVE_Template->assign('doc_id', (int)$_REQUEST['Id']);
- return $AVE_Template->fetch($tpl_file);
- break;
-
- case 'doc':
-
- $items = (isset($field_value)) ? unserialize($field_value) : array();
-
- $res = array();
-
- if($items != false){
- foreach($items as $image_item)
- {
- $image_item = clean_php($image_item);
- $field_param = explode('|', $image_item);
- if($image_item){
- if ($tpl_empty)
- {
- $image_item = $field_param;
- }
- else
- {
- $image_item = preg_replace_callback(
- '/\[tag:parametr:(\d+)\]/i',
- function($data) use($field_param)
- {
- return $field_param[(int)$data[1]];
- },
- $tpl
- );
-
- $image_item = preg_replace_callback(
- '/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/',
- create_function(
- '$m',
- 'return watermarks(\'$m[1]\', \'$m[2]\', $m[3]);'
- ),
- $image_item
- );
-
- $image_item = preg_replace_callback('/\[tag:([r|c|f|t|s]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $image_item);
- }
- }
- $res[] = $image_item;
- }
- }
-
- $tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc');
-
- if($tpl_empty && $tpl_file){
-
- $AVE_Template->assign('field_id', $field_id);
- $AVE_Template->assign('field_value', $res);
- $AVE_Template->assign('field_count', count($res));
- $AVE_Template->assign('rubric_id', $rubric_id);
- $AVE_Template->assign('default', $default);
-
- return $AVE_Template->fetch($tpl_file);
- }
- return (!empty($res)) ? implode(PHP_EOL, $res) : $tpl;
- break;
-
- case 'req':
- $items = unserialize($field_value);
-
- $res = '';
-
- if($items != false) {
- foreach($items as $image_item)
- {
- $image_item = clean_php($image_item);
- $field_param = explode('|', $image_item);
- if($image_item){
- if ($tpl_empty)
- {
- $image_item = $field_param;
- }
- else
- {
- $image_item = preg_replace_callback(
- '/\[tag:parametr:(\d+)\]/i',
- function($data) use($field_param)
- {
- return $field_param[(int)$data[1]];
- },
- $tpl
- );
-
- $image_item = preg_replace_callback(
- '/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/',
- create_function(
- '$m',
- 'return watermarks(\'$m[1]\', \'$m[2]\', $m[3]);'
- ),
- $image_item
- );
-
- $image_item = preg_replace_callback('/\[tag:([r|c|f]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $image_item);
- }
- }
- $res[] = $image_item;
- }
- }
-
- $tpl_file = get_field_tpl($tpl_dir, $field_id, 'req');
-
- if($tpl_empty && $tpl_file){
-
- $AVE_Template->assign('field_id', $field_id);
- $AVE_Template->assign('field_value', $res);
- $AVE_Template->assign('field_count', count($res));
- $AVE_Template->assign('rubric_id', $rubric_id);
- $AVE_Template->assign('default', $default);
-
- return $AVE_Template->fetch($tpl_file);
- }
-
- return (!empty($res)) ? implode(PHP_EOL, $res) : $tpl;
- break;
-
- case 'save':
- foreach ($field_value as $v)
- {
- if(!empty($v['url'])){
- $field_value_new[] = $v['url'] . '|' . $v['descr'] . '|' . $v['descr2'] . '|' . $v['descr3'];
- }
- }
- if (isset($field_value_new)) {
- return @serialize($field_value_new);
- } else {
- return $field_value_new = '';
- }
-
- break;
-
- case 'name' :
- return $AVE_Template->get_config_vars('name');
- break;
-
- case 'upload':
- $error = false;
-
- $files_unput = 'cascad3_files'.'_'.$_REQUEST['field_id'].'_'.$_REQUEST['doc_id'];
-
- if(preg_match("/%id/i", $default))
- {
- $path = trim(@str_replace('%id', $_REQUEST['doc_id'], $default), '/');
- }
- else
- {
- $path = (!empty($default)) ? $default : '';
- }
-
- function getExtension($file)
- {
- $file = pathinfo($file);
- return $file['extension'];
- }
-
- $valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
-
- $dir = '/' . UPLOAD_DIR . '/' . ((!empty($path)) ? $path . '/' : '');
- $dir_abs = BASE_DIR . $dir;
-
- if (!is_dir($dir_abs)) @mkdir($dir_abs, 0777, true);
-
- foreach ($_FILES[$files_unput]['name'] as $name => $value) {
-
- $filename = strtolower(stripslashes(prepare_url($_FILES[$files_unput]['name'][$name])));
- //$size = filesize($_FILES[$files_unput]['tmp_name'][$name]);
-
- $ext = getExtension($filename);
- $ext = strtolower($ext);
-
- if(in_array($ext, $valid_formats))
- {
- if (file_exists($dir_abs . $filename))
- {
- $filename = rand(1000, 9999) . '_' . $filename;
- }
-
- if (@move_uploaded_file($_FILES[$files_unput]['tmp_name'][$name], $dir_abs . $filename)) {
- $new_files[] = $filename;
- $error = false;
- } else {
- $error = true;
- }
- }
- else
- {
- $error = true;
- @unlink($_FILES[$files_unput]['tmp_name'][$name]);
- }
- }
- if ($error !== true) {
- echo json_encode(array(
- 'files' => $new_files,
- 'dir' => $dir,
- 'respons' => 'succes',
- 'message' => $AVE_Template->get_config_vars('resp_s_m'),
- 'header' => $AVE_Template->get_config_vars('resp_s_h'),
- 'theme' => 'accept'
- )
- );
- }
- else
- {
- echo json_encode(array(
- 'respons' => 'error',
- 'message' => $AVE_Template->get_config_vars('resp_e_m'),
- 'header' => $AVE_Template->get_config_vars('resp_e_h'),
- 'theme' => 'error'
- )
- );
- }
- exit;
- }
-
- return ($res ? $res : $field_value);
-}
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/js/.gitkeep b/fields/image_multi_new_3inputs/js/.gitkeep
deleted file mode 100755
index e69de29..0000000
diff --git a/fields/image_multi_new_3inputs/js/field.js b/fields/image_multi_new_3inputs/js/field.js
deleted file mode 100755
index 7e9bc6a..0000000
--- a/fields/image_multi_new_3inputs/js/field.js
+++ /dev/null
@@ -1,235 +0,0 @@
-var Cascad3 = {
-
- init: false,
-
- init: function() {
- if (this.initialized) return;
- this.initialized = true;
-
- this.cascad3();
- },
-
- cascad3: function() {
- this.cascad3_sortable();
- this.cascad3_del_item();
- this.cascad3_del_all_item();
- this.cascad3_add_single();
- this.cascad3_add_folder();
- this.cascad3_upload_files();
- this.cascad3_click_upload();
- },
-
- cascad3_update: function() {
- this.cascad3_maxid();
- this.cascad3_del_item();
- AveAdmin.fancy_box();
- AveAdmin.tooltip();
- },
-
- cascad3_maxid: function(id, doc) {
- var maxid = 1;
- $('#cascad3_' + doc + '_' + id).children('.cascad3_sortable').children('.cascad3_item').each(function() {
- maxid = Math.max(maxid, parseInt($(this).attr("data-id")) + 1);
- });
- return maxid;
- },
-
- cascad3_del_item: function() {
- $('.cascad3_item .delete').on('click', function(event) {
- event.preventDefault();
- var id = $(this).attr('data-id');
- jConfirm(
- del_conf,
- del_head,
- function(b) {
- if (b) {
- $('#cascad3_image_' + id).remove();
- }
- }
- );
- });
- },
-
- cascad3_del_all_item: function() {
- $('.cascad3_del_all').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- jConfirm(
- del_all_c,
- del_all_h,
- function(b) {
- if (b) {
- $('#cascad3_' + d_id + '_' + c_id).children('.cascad3_sortable').children('.cascad3_item').each(function() {
- $(this).remove();
- });
- }
- }
- );
- });
- },
-
- cascad3_upload_files: function() {
- $('.cascad3_upload').on('change', function(event) {
-
- var cascad3_input = $(this);
-
- event.preventDefault();
-
- if (cascad3_input.val() == '') {
- return false;
- }
-
- var files_input = this.files.length;
- var max_files = cascad3_input.attr("data-max-files");
-
- if (files_input > max_files) {
- $.jGrowl(max_f_t, {
- header: max_f_h,
- theme: 'error'
- });
-
- cascad3_input.replaceWith(cascad3_input.val('').clone(true));
-
- return false;
- }
-
- var cid = $(this).parent('.cascad3').attr("data-id");
- var did = $(this).parent('.cascad3').attr("data-doc");
- var rid = $(this).parent('.cascad3').attr("data-rubric");
-
- $('#formDoc').ajaxSubmit({
- url: 'index.php?do=fields',
- data: {
- "field_id": cid,
- "rubric_id": rid,
- "doc_id": did,
- "field": 'image_multi_new_3inputs',
- "type": 'upload'
- },
- beforeSend: function() {
- $.alerts._overlay('show');
- },
- dataType: "json",
- success: function(data) {
- if (data['respons'] == 'succes') {
- for (var p = 0, max = data.files.length; p < max; p++) {
- iid = Cascad3.cascad3_maxid(cid, did);
- var field_value = data['dir'] + data.files[p];
- var img_path = '../index.php?thumb=' + field_value + '&mode=f&width=128&height=128';
- $('#cascad3_' + did + '_' + cid + ' > .cascad3_sortable:last').prepend(
- '' +
- '' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
'
- );
- $.alerts._overlay('hide');
- Cascad3.cascad3_update();
- }
- }
- $.jGrowl(data['message'], {
- header: data['header'],
- theme: data['theme']
- });
- cascad3_input.replaceWith(cascad3_input = cascad3_input.clone(true));
- cascad3_input.val();
- }
- });
- return false;
- });
- },
-
- cascad3_click_upload: function() {
- $('.cascad3_upload_local').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- $('.cascad3_upload_field_' + c_id + '_' + d_id).trigger('click');
- });
- },
-
- cascad3_add_single: function() {
- $('.cascad3_add_single').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- var iid = Cascad3.cascad3_maxid(c_id, d_id);
- $('#cascad3_' + d_id + '_' + c_id + ' > .cascad3_sortable:last').prepend(
- ''
- );
- browse_uploads('image__' + c_id + '_' + d_id + '_' + iid + '');
- Cascad3.cascad3_update();
- });
- },
-
- cascad3_sortable: function() {
- $('.cascad3_sortable').sortable({
- handle: ".header",
- placeholder: "ui-state-highlight grey_bg"
- });
- //$(".cascad3").disableSelection();
- },
-
- cascad3_add_folder: function() {
- $('.cascad3_add_folder').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- browse_dirs("cascad3__" + c_id + '_' + d_id);
- });
- }
-};
-
-$(document).ready(function() {
- Cascad3.init();
-
- $.fn.myPlugin = function cascad3_add_items(dir, cid, did) {
-
- $.ajax({
- url: ave_path + 'admin/index.php?do=docs&action=image_import&ajax=run',
- data: {
- "path": dir
- },
- dataType: "json",
- success: function(data) {
- $.alerts._overlay('hide');
- for (var p = 0, max = data.respons.length; p < max; p++) {
- var iid = Cascad3.cascad3_maxid(cid, did);
- var field_value = dir + data.respons[p];
- var img_path = '../index.php?thumb=' + field_value + '&mode=f&width=128&height=128';
- $('#cascad3_' + did + '_' + cid + ' > .cascad3_sortable:last').prepend(
- '' +
- '' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
'
- );
- Cascad3.cascad3_update();
- }
- }
- });
- }
-
-});
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/js/outside.js b/fields/image_multi_new_3inputs/js/outside.js
deleted file mode 100755
index 701c263..0000000
--- a/fields/image_multi_new_3inputs/js/outside.js
+++ /dev/null
@@ -1,231 +0,0 @@
-var Cascad3 = {
-
- init: false,
-
- init: function() {
- if (this.initialized) return;
- this.initialized = true;
-
- this.cascad3();
- },
-
- cascad3: function() {
- this.cascad3_sortable();
- this.cascad3_del_item();
- this.cascad3_del_all_item();
- this.cascad3_add_single();
- this.cascad3_add_folder();
- this.cascad3_upload_files();
- this.cascad3_click_upload();
- },
-
- cascad3_update: function() {
- this.cascad3_maxid();
- this.cascad3_del_item();
- AveAdmin.fancy_box();
- AveAdmin.tooltip();
- },
-
- cascad3_maxid: function(id, doc) {
- var maxid = 1;
- $('#cascad3_' + doc + '_' + id).children('.cascad3_sortable').children('.cascad3_item').each(function() {
- maxid = Math.max(maxid, parseInt($(this).attr("data-id")) + 1);
- });
- return maxid;
- },
-
- cascad3_del_item: function() {
- $('.cascad3_item .delete').on('click', function(event) {
- event.preventDefault();
- var id = $(this).attr('data-id');
- jConfirm(
- del_conf,
- del_head,
- function(b) {
- if (b) {
- $('#cascad3_image_' + id).remove();
- }
- }
- );
- });
- },
-
- cascad3_del_all_item: function() {
- $('.cascad3_del_all').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- jConfirm(
- del_all_c,
- del_all_h,
- function(b) {
- if (b) {
- $('#cascad3_' + d_id + '_' + c_id).children('.cascad3_sortable').children('.cascad3_item').each(function() {
- $(this).remove();
- });
- }
- }
- );
- });
- },
-
- cascad3_upload_files: function() {
- $('.cascad3_upload').on('change', function(event) {
-
- event.preventDefault();
-
- var cascad3_input = $(this);
-
- event.preventDefault();
-
- if (cascad3_input.val() == '') {
- return false;
- }
-
- var files_input = this.files.length;
- var max_files = cascad3_input.attr("data-max-files");
-
- if (files_input > max_files) {
- $.jGrowl(max_f_t, {
- header: max_f_h,
- theme: 'error'
- });
-
- cascad3_input.replaceWith(cascad3_input.val('').clone(true));
-
- return false;
- }
-
- var cid = $(this).parent('.cascad3').attr("data-id");
- var did = $(this).parent('.cascad3').attr("data-doc");
- var rid = $(this).parent('.cascad3').attr("data-rubric");
-
- $('#docmanager_edit').ajaxSubmit({
- url: 'index.php?do=fields',
- data: {
- "field_id": cid,
- "rubric_id": rid,
- "doc_id": did,
- "field": 'image_multi_new_3inputs',
- "type": 'upload'
- },
- beforeSend: function() {
- $.alerts._overlay('show');
- },
- dataType: "json",
- success: function(data) {
- if (data['respons'] == 'succes') {
- for (var p = 0, max = data.files.length; p < max; p++) {
- iid = Cascad3.cascad3_maxid(cid, did);
- var field_value = data['dir'] + data.files[p];
- var img_path = '../index.php?thumb=' + field_value + '&mode=f&width=128&height=128';
- $('#cascad3_' + did + '_' + cid + ' > .cascad3_sortable:last').prepend(
- '' +
- '' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
'
- );
- $.alerts._overlay('hide');
- Cascad3.cascad3_update();
- }
- }
- $.jGrowl(data['message'], {
- header: data['header'],
- theme: data['theme']
- });
- cascad3_input.replaceWith(cascad3_input = cascad3_input.clone(true));
- cascad3_input.val();
- }
- });
- return false;
- });
- },
-
- cascad3_click_upload: function() {
- $('.cascad3_upload_local').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- $('.cascad3_upload_field_' + c_id + '_' + d_id).trigger('click');
- });
- },
-
- cascad3_add_single: function() {
- $('.cascad3_add_single').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- var iid = Cascad3.cascad3_maxid(c_id, d_id);
- $('#cascad3_' + d_id + '_' + c_id + ' > .cascad3_sortable:last').prepend(
- '' +
- '' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
'
- );
- browse_uploads('image__' + c_id + '_' + d_id + '_' + iid + '');
- Cascad3.cascad3_update();
- });
- },
-
- cascad3_sortable: function() {
- $('.cascad3_sortable').sortable({
- handle: ".header",
- placeholder: "ui-state-highlight grey_bg"
- });
- //$(".cascad3").disableSelection();
- },
-
- cascad3_add_folder: function() {
- $('.cascad3_add_folder').on('click', function(event) {
- event.preventDefault();
- var c_id = $(this).parent().parent().parent('.cascad3').attr("data-id");
- var d_id = $(this).parent().parent().parent('.cascad3').attr("data-doc");
- browse_dirs("cascad3__" + c_id + '_' + d_id);
- });
- }
-}
-
-$(document).ready(function() {
- Cascad3.init();
-
- $.fn.myPlugin = function cascad3_add_items(dir, cid, did) {
-
- $.ajax({
- url: ave_path + 'admin/index.php?do=docs&action=image_import&ajax=run',
- data: {
- "path": dir
- },
- dataType: "json",
- success: function(data) {
- $.alerts._overlay('hide');
- for (var p = 0, max = data.respons.length; p < max; p++) {
- var iid = Cascad3.cascad3_maxid(cid, did);
- var field_value = dir + data.respons[p];
- var img_path = '../index.php?thumb=' + field_value + '&mode=f&width=128&height=128';
- $('#cascad3_' + did + '_' + cid + ' > .cascad3_sortable:last').prepend(
- '' +
- '' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
' +
- '
'
- );
- Cascad3.cascad3_update();
- }
- }
- });
- }
-
-});
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/.gitkeep b/fields/image_multi_new_3inputs/lang/.gitkeep
deleted file mode 100755
index e69de29..0000000
diff --git a/fields/image_multi_new_3inputs/lang/bg.txt b/fields/image_multi_new_3inputs/lang/bg.txt
deleted file mode 100644
index e771d4d..0000000
--- a/fields/image_multi_new_3inputs/lang/bg.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-[admin]
-name = "Изображение (Каскада, 3 полета)"
-look = "Преглед"
-link = "Промени пътя"
-select = "Избери изображение"
-delete = "Изтриване на елелемт от элемент каскадата"
-place = "Описание"
-del_conf = "Сигурни ли сте, че желаете да изтриете този елемент? (Изображението няма да бъде изтрито от сървъра)"
-del_head = "Изтриване на елемент от каскадата..."
-add_n_e = "Добави нов елемент:"
-add_f = "Избор на изображение"
-add_d = "Избор на папка"
-add_l = "Качи от компютъра"
-add_upl_e = "Вие може за заредите изображения от локален компютър след създаването на документа. За това натиснете бутона по долу «Добави и продължи редактирането»"
-upl_dir = "Папка: "
-del_all = "Изтриване на всички елементи"
-del_all_c = "Сигурни ли сте, че желаете да изтриете всички елементи? (Изображенията няма да бъдат изтрити от сървъра)"
-del_all_h = "Изтриване на всички елементи на каскадата..."
-resp_s_h = "Изпълнено"
-resp_s_m = "Файловете са успешно заредени"
-resp_e_m = "Възникна грешка при зареждането на файловете. Моля, опитайте отново."
-resp_e_h = "Грешка"
-resp_m_m = "Броя на файловете за зареждане са повече от максималния, зададен в настройките на PHP."
-resp_m_h = "Грешка"
-max_f_f = "Максимален брой файлове за зареждане: "
-max_f_h = "Грешка"
-max_f_t = "Превишен е максималния брой файлове, разрешен за едновременно зареждане"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/cz.txt b/fields/image_multi_new_3inputs/lang/cz.txt
deleted file mode 100644
index 53f8b41..0000000
--- a/fields/image_multi_new_3inputs/lang/cz.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-[admin]
-name = "Zobrazení (Kaskáda, 3 inputy)"
-look = "Zobrazit"
-link = "Změnit cestu"
-select = "Vybrat zobrazení"
-delete = "Smazat prvek kaskády"
-place = "Popis"
-del_conf = "Opravdu chcete odstranit tento prvek? (Zobrazení nebude smazáno ze serveru)"
-del_head = "Smazání prvku kaskády..."
-add_n_e = "Přidat nový element:"
-add_f = "Vybrat zobrazení"
-add_d = "Vybrat složku"
-add_l = "Nahrát z počítače"
-add_upl_e = "Můžete nahrávat obrázky z místního počítače po vytvoření dokumentu. Kliknutím níže na "Přidat a pokračovat v úpravách"
-upl_dir = "Složka: "
-del_all = "Odstranit všechny prvky"
-del_all_c = "Opravdu chcete odstranit všechny prvky? (Zobrazení nebude smazáno ze serveru)"
-del_all_h = "Odstranit všechny prvky kaskádu..."
-resp_s_h = "Hotovo"
-resp_s_m = "Soubory úspěšně nahrány"
-resp_s_h = "Hotovo"
-resp_s_m = "Soubory úspěšně nahrány"
-resp_e_m = "Při stahování souborů došlo k chybě. Zkuste znovu."
-resp_e_h = "Chyba"
-resp_m_m = "Počet souborů, které se mají nahrát překračují hodnotu zadanou v konfiguračním PHP."
-resp_m_h = "Chyba"
-max_f_f = "Maximální počet souborů ke stažení: "
-max_f_h = "Chba"
-max_f_t = Překročen maximální počet souborů, během jednoho nahrávání"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/en.txt b/fields/image_multi_new_3inputs/lang/en.txt
deleted file mode 100755
index 5de64c1..0000000
--- a/fields/image_multi_new_3inputs/lang/en.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-[en]
-name = "Cascad NEW, 3 inputs"
-look = "Lool"
-link = "Change path"
-select = "Select image"
-delete = "Delete item cascade"
-place = "Description"
-del_conf = "are you sure You want to delete this item? (the Image will not be deleted from the server)"
-del_head = "Delete item cascade..."
-add_n_e = "Add new item:"
-add_f = "Select image"
-add_d = "Select folder"
-add_l = "Download to computer"
-add_upl_e = "You can upload pictures from your computer after you create the document. To do this, press the bottom button "Add and continue editing""
-del_all = "Delete any items"
-del_all_c = "are you sure You want to delete all items? (Image will not be deleted from the server)"
-del_all_h = "Delete all items of the cascade..."
-resp_s_h = "Done"
-resp_s_m = "File successfully loaded"
-resp_e_m = "an error Occurred when uploading files. Try again."
-resp_e_h = "Error"
-resp_m_m = "number of uploaded file exceeds the value set in your PHP settings."
-resp_m_h = "Error"
-max_f_f = "Maximum number zagrozenia files:"
-max_f_h = "Error"
-max_f_t = "you have Exceeded the maximum number of files to download"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/pl.txt b/fields/image_multi_new_3inputs/lang/pl.txt
deleted file mode 100644
index 81337e7..0000000
--- a/fields/image_multi_new_3inputs/lang/pl.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-[admin]
-name = "Obrazek (Kaskada, 3 input’y)"
-look = "Popatrz"
-link = "Zmień sposób"
-select = "Wybierz obrazek"
-delete = "Usuń kaskadę"
-place = "Opis"
-del_conf = "Czy na pewno chcesz usunąć ten element? (Obrazek nie będzie usunięty z serwera)"
-del_head = "Usuń element kaskady ..."
-add_n_e = "Dodaj nowy element"
-add_f = "Wybierz obrazek"
-add_d = "Wybierz folder"
-add_l = "Pobierz z komputera"
-add_upl_e = "Możesz pobrać obrazki z komputera lokalnego po utworzeniu dokumentu. Aby to zrobić, kliknij poniżej na “Dodaj i kontynuować edycję”"
-upl_dir = "Folder:"
-del_all = "Usuń wszystkie elementy"
-del_all_c = "Czy na pewno chcesz usunąć wszystkie elementy? (Obrazek nie będzie usunięty z serwera)"
-del_all_h = "Usuń wszystkie pozycje kaskady..."
-resp_s_h = "Gotowe"
-resp_s_m = "Pliki pomyślnie pobrane"
-resp_e_m = "Wystąpił błąd podczas pobierania plików. Spróbuj ponownie."
-resp_e_h = "Błąd"
-resp_m_m = "Liczba plików do przesłania przekracza wartości, określone w PHP konfiguracji."
-resp_m_h = "Błąd"
-max_f_f = "Maksymalna liczba plików do pobrania:"
-max_f_h = "Błąd"
-max_f_t = "Przekroczono maksymalną liczbę plików, na jednoczesne ładowanie"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/ru.txt b/fields/image_multi_new_3inputs/lang/ru.txt
deleted file mode 100755
index 555dc98..0000000
--- a/fields/image_multi_new_3inputs/lang/ru.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-[admin]
-name = "Изображение (Каскад, 3 инпута)"
-look = "Посмотреть"
-link = "Изменить путь"
-select = "Выбрать изображение"
-delete = "Удалить элемент каскада"
-place = "параметр"
-del_conf = "Вы уверены, что хотите удалить данный элемент? (Изображение не будет удалено с сервера)"
-del_head = "Удаление элемента каскада..."
-add_n_e = "Добавить новый элемент:"
-add_f = "Выбрать изображение"
-add_d = "Выбрать папку"
-add_l = "Загрузить с компьютера"
-add_upl_e = "Вы сможете загрузить фотографии с локального компьютера после создания документа. Для этого нажмите внизу кнопку «Добавить и продолжить редактирование»"
-upl_dir = "Папка: "
-del_all = "Удалить все элементы"
-del_all_c = "Вы уверены, что хотите удалить все элементы? (Изображения не будет удалены с сервера)"
-del_all_h = "Удаление всех элемента каскада..."
-resp_s_h = "Выполнено"
-resp_s_m = "Файлы успешно загрузились"
-resp_e_m = "Возникла ошибка при загрузке файлов. Попробуйте еще раз."
-resp_e_h = "Ошибка"
-resp_m_m = "Кол-во загружаемых файлов превышает значение, заданное в настройках PHP."
-resp_m_h = "Ошибка"
-max_f_f = "Макимальное кол-во загружаемых файлов: "
-max_f_h = "Ошибка"
-max_f_t = "Превышено максимальное число файлов, для одновременной загрузки"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/lang/ua.txt b/fields/image_multi_new_3inputs/lang/ua.txt
deleted file mode 100644
index f2afc1f..0000000
--- a/fields/image_multi_new_3inputs/lang/ua.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-[admin]
-name = "Зображення (Каскад, 3 інпута)"
-look = "Подивитися"
-link = "Змінити шлях"
-select = "Обрати зображення"
-delete = "Видалити елемент каскаду"
-place = "Опис"
-del_conf = "Ви впевнені, що бажаєте видалити цей елемент? (Зображення не буде видалено зі сервера)"
-del_head = "Видалення елемента каскаду..."
-add_n_e = "Додати новий елемент:"
-add_f = "Обрати зображення"
-add_d = "Обрати папку"
-add_l = "Завантажити з компьютера"
-add_upl_e = "Ви зможете завантажити зображення з локального компьютера післе створення документа. Для цього натисніть внизу кнопку “Додати та продовжити редагування”"
-upl_dir = "Папка: "
-del_all = "Видалити всі елементи"
-del_all_c = "Ви впевнені, що бажаєте видалити всі елементи? (Зображення не буде видалено зі сервера)"
-del_all_h = "Видалення всіх елементів каскаду..."
-resp_s_h = "Виконано"
-resp_s_m = "Файли успішно завантажилися"
-resp_e_m = "Сталася помилка при завантаженні файлів. Спробуйте ще раз."
-resp_e_h = "Помилка"
-resp_m_m = "Кількість файлів для завантаження перевищує значення, яке вказане у налаштуваннях PHP."
-resp_m_h = "Помилка"
-max_f_f = "Максимальна кількість файлів для завантаження: "
-max_f_h = "Помилка"
-max_f_t = "Перевищено максимальне число файлів, для одночасного завантаження"
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/tpl/.gitkeep b/fields/image_multi_new_3inputs/tpl/.gitkeep
deleted file mode 100755
index e69de29..0000000
diff --git a/fields/image_multi_new_3inputs/tpl/field-doc.tpl b/fields/image_multi_new_3inputs/tpl/field-doc.tpl
deleted file mode 100755
index c52ebed..0000000
--- a/fields/image_multi_new_3inputs/tpl/field-doc.tpl
+++ /dev/null
@@ -1,3 +0,0 @@
-{foreach from=$field_value item=image}
-
-{/foreach}
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/tpl/field-req.tpl b/fields/image_multi_new_3inputs/tpl/field-req.tpl
deleted file mode 100755
index c52ebed..0000000
--- a/fields/image_multi_new_3inputs/tpl/field-req.tpl
+++ /dev/null
@@ -1,3 +0,0 @@
-{foreach from=$field_value item=image}
-
-{/foreach}
\ No newline at end of file
diff --git a/fields/image_multi_new_3inputs/tpl/field.tpl b/fields/image_multi_new_3inputs/tpl/field.tpl
deleted file mode 100755
index 6836d03..0000000
--- a/fields/image_multi_new_3inputs/tpl/field.tpl
+++ /dev/null
@@ -1,65 +0,0 @@
-{if $cascad3_new_3inputs != load}
- {assign var=cascad3_new_3inputs value='' scope="global"}
- {if $smarty.request.outside}
-
- {else}
-
- {/if}
-
-
- {assign var=cascad3_new_3inputs value="load" scope="global"}
-{/if}
-
-
-
- {if $show_upload}
-
- {/if}
-
-
-
- {foreach from=$images key=key item=image}
-
-
-
-
-
-
-
-
-
-
-
-
-
- {/foreach}
-
-
-
\ No newline at end of file
diff --git a/fields/teasers/field.php b/fields/teasers/field.php
index dcb9276..cddd81a 100644
--- a/fields/teasers/field.php
+++ b/fields/teasers/field.php
@@ -1,165 +1,167 @@
config_load($lang_file, 'lang');
- $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
- $AVE_Template->config_load($lang_file, 'admin');
-
- switch ($action)
+ /**
+ * Teasers
+ */
+ function get_field_teasers($field_value, $action, $field_id=0, $tpl='', $tpl_empty=0, &$maxlength = '', $doc_fields=array(), $rubric_id=0, $default='')
{
- case 'edit':
+ global $AVE_DB, $AVE_Template;
- $items = array();
+ $fld_dir = dirname(__FILE__) . '/';
+ $tpl_dir = $fld_dir . 'tpl/';
+ $fld_name = basename($fld_dir);
- $items = unserialize($field_value);
+ $lang_file = $fld_dir . 'lang/' . (defined('ACP') ? $_SESSION['admin_language'] : $_SESSION['user_language']) . '.txt';
- if($items != false){
+ $AVE_Template->config_load($lang_file, 'lang');
+ $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
+ $AVE_Template->config_load($lang_file, 'admin');
- foreach($items as $k => $v){
- $list_item = explode('|', $v);
+ switch ($action)
+ {
+ case 'edit':
- $list[$k]['param'] = (isset($list_item[0])) ? htmlspecialchars($list_item[0], ENT_QUOTES) : '';
- $list[$k]['value'] = (isset($list_item[1])) ? htmlspecialchars($list_item[1], ENT_QUOTES) : '';
+ $items = array();
+
+ $items = unserialize($field_value);
+
+ if($items != false){
+
+ foreach($items as $k => $v){
+ $list_item = explode('|', $v);
+
+ $list[$k]['param'] = (isset($list_item[0])) ? htmlspecialchars($list_item[0], ENT_QUOTES) : '';
+ $list[$k]['value'] = (isset($list_item[1])) ? htmlspecialchars($list_item[1], ENT_QUOTES) : '';
+ }
+
+ $items = $list;
}
- $items = $list;
- }
+ $tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin');
- $tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin');
+ $AVE_Template->assign('doc_id', $_REQUEST['Id']);
+ $AVE_Template->assign('items', $items);
+ $AVE_Template->assign('field_dir', $fld_name);
+ $AVE_Template->assign('field_id', $field_id);
- $AVE_Template->assign('doc_id', $_REQUEST['Id']);
- $AVE_Template->assign('items', $items);
- $AVE_Template->assign('field_dir', $fld_name);
- $AVE_Template->assign('field_id', $field_id);
+ return $AVE_Template->fetch($tpl_file);
- return $AVE_Template->fetch($tpl_file);
-
- case 'save':
- foreach ($field_value as $v)
- {
- if(! empty($v['value']) && ! empty($v['param']))
+ case 'save':
+ foreach ($field_value as $v)
{
- $field_value_new[] = $v['param'] . ($v['value'] ? '|' . $v['value'] : '');
+ if(! empty($v['value']) && ! empty($v['param']))
+ {
+ $field_value_new[] = $v['param'] . ($v['value'] ? '|' . $v['value'] : '');
+ }
}
- }
- if (isset($field_value_new))
- {
- return @serialize($field_value_new);
- }
- else
- {
- return $field_value_new = '';
- }
- break;
-
- case 'doc':
- $items = (isset($field_value)) ? unserialize($field_value) : array();
-
- $res = array();
-
- if ($items != false)
- {
- foreach($items as $item)
+ if (isset($field_value_new))
{
- $item = explode('|', $item);
-
- if ($item[1])
- $res[] = eval2var('?>' . showteaser($item[1]) . '');
+ return @serialize($field_value_new);
}
- }
+ else
+ {
+ return $field_value_new = '';
+ }
+ break;
- return (! empty($res))
- ? implode(PHP_EOL, $res)
- : $tpl;
+ case 'doc':
+ $items = (isset($field_value))
+ ? unserialize($field_value)
+ : array();
- break;
+ $res = array();
- case 'req':
- return get_field_default($field_value, $action, $field_id, $tpl, $tpl_empty);
+ if ($items != false)
+ {
+ foreach($items as $item)
+ {
+ $item = explode('|', $item);
- case 'name' :
- return $AVE_Template->get_config_vars('name');
- break;
+ if ($item[1])
+ $res[] = showteaser($item[1]);
+ }
+ }
- case 'search':
+ return (! empty($res))
+ ? implode(PHP_EOL, $res)
+ : $tpl;
- $field_default = explode(',', $default);
+ break;
- $zap_1 = ($field_default[0]) ? ',' : '';
- $zap_2 = ($field_default[0] && $field_default[1]) ? ',' : '';
+ case 'req':
+ return get_field_default($field_value, $action, $field_id, $tpl, $tpl_empty);
- $sel_1 = ($field_default[0]) ? 'b.field_value as b1' : '';
- $sel_2 = ($field_default[1]) ? 'c.field_value as c1' : '';
+ case 'name' :
+ return $AVE_Template->get_config_vars('name');
+ break;
- $from_1 = ($field_default[0]) ? PREFIX . '_document_fields b' : '';
- $from_2 = ($field_default[1]) ? PREFIX . '_document_fields c' : '';
+ case 'search':
- $search_1 = ($field_default[0]) ? "AND (b.document_id=a.Id AND b.rubric_field_id = " . $field_default[0] . ")" : "";
- $search_2 = ($field_default[1]) ? "AND (c.document_id=a.Id AND c.rubric_field_id = " . $field_default[1] . ")" : "";
+ $field_default = explode(',', $default);
- $or_1 = ($field_default[0]) ? "OR (UPPER(b.field_value) LIKE UPPER('%" . $_REQUEST['q'] . "%'))" : "";
- $or_2 = ($field_default[1]) ? "OR (UPPER(c.field_value) LIKE UPPER('%" . $_REQUEST['q'] . "%'))" : "";
+ $zap_1 = ($field_default[0]) ? ',' : '';
+ $zap_2 = ($field_default[0] && $field_default[1]) ? ',' : '';
- $sql = $AVE_DB->Query("
- SELECT
- a.Id,
- a.document_title
- $zap_1
- $sel_1
- $zap_2
- $sel_2
- FROM
- " . PREFIX . "_documents a
- $zap_1
- " . $from_1 . "
- $zap_2
- " . $from_2 . "
- WHERE
- a.rubric_id = '" . $_REQUEST['rubric_id'] . "'
- AND
- a.document_status = 1
- " . $search_1 . "
- " . $search_2 . "
- AND
- (
- (UPPER(document_title) LIKE UPPER('%" . $_REQUEST['q'] . "%'))
- $or_1
- $or_2
- )
- GROUP BY a.Id
- LIMIT 0,5
- ");
+ $sel_1 = ($field_default[0]) ? 'b.field_value as b1' : '';
+ $sel_2 = ($field_default[1]) ? 'c.field_value as c1' : '';
- $doc_finded = array();
+ $from_1 = ($field_default[0]) ? PREFIX . '_document_fields b' : '';
+ $from_2 = ($field_default[1]) ? PREFIX . '_document_fields c' : '';
- while ($row = $sql->FetchRow())
- {
- $doc_finded[] = array(
- 'doc_id' => $row->Id,
- 'doc_title' => $row->document_title,
- 'doc_name' => (($field_default[0]) ? $row->b1 : $row->document_title),
- 'doc_article' => (($field_default[1]) ? $row->c1 : '')
- );
- }
+ $search_1 = ($field_default[0]) ? "AND (b.document_id=a.Id AND b.rubric_field_id = " . $field_default[0] . ")" : '';
+ $search_2 = ($field_default[1]) ? "AND (c.document_id=a.Id AND c.rubric_field_id = " . $field_default[1] . ")" : '';
- echo json_encode($doc_finded);
- exit;
+ $or_1 = ($field_default[0]) ? "OR (UPPER(b.field_value) LIKE UPPER('%" . $_REQUEST['q'] . "%'))" : '';
+ $or_2 = ($field_default[1]) ? "OR (UPPER(c.field_value) LIKE UPPER('%" . $_REQUEST['q'] . "%'))" : '';
- default:
- return $field_value;
+ $sql = $AVE_DB->Query("
+ SELECT
+ a.Id,
+ a.document_title
+ $zap_1
+ $sel_1
+ $zap_2
+ $sel_2
+ FROM
+ " . PREFIX . "_documents a
+ $zap_1
+ " . $from_1 . "
+ $zap_2
+ " . $from_2 . "
+ WHERE
+ a.rubric_id = '" . $_REQUEST['rubric_id'] . "'
+ AND
+ a.document_status = 1
+ " . $search_1 . "
+ " . $search_2 . "
+ AND
+ (
+ (UPPER(document_title) LIKE UPPER('%" . $_REQUEST['q'] . "%'))
+ $or_1
+ $or_2
+ )
+ GROUP BY a.Id
+ LIMIT 0,5
+ ");
+
+ $doc_finded = array();
+
+ while ($row = $sql->FetchRow())
+ {
+ $doc_finded[] = array(
+ 'doc_id' => $row->Id,
+ 'doc_title' => $row->document_title,
+ 'doc_name' => (($field_default[0]) ? $row->b1 : $row->document_title),
+ 'doc_article' => (($field_default[1]) ? $row->c1 : '')
+ );
+ }
+
+ echo json_encode($doc_finded);
+ exit;
+
+ default:
+ return $field_value;
+ }
+
+ return ($res ? $res : $field_value);
}
-
- return ($res ? $res : $field_value);
-}
?>
\ No newline at end of file
diff --git a/fields/teasers/js/field.js b/fields/teasers/js/field.js
index ddc8e4f..bede30f 100644
--- a/fields/teasers/js/field.js
+++ b/fields/teasers/js/field.js
@@ -1,4 +1,4 @@
-var Analoque = {
+var Teasers = {
init: false,
@@ -57,7 +57,7 @@ var Analoque = {
$('.AddButton').on('click', function() {
c_id = $(this).parent().parent('.analoque_lists').attr("data-id");
d_id = $(this).parent().parent('.analoque_lists').attr("data-docid");
- i_id = Analoque.Analoque_maxid(d_id + '_' + c_id);
+ i_id = Teasers.Analoque_maxid(d_id + '_' + c_id);
$('#analoque_lists_' + d_id + '_' + c_id + ':last').append(
''
);
- Analoque.Analoque_update();
+ Teasers.Analoque_update();
});
},
@@ -81,6 +81,8 @@ var Analoque = {
*/
Analoque_search: function() {
+ var res_search = false;
+
$('.search_analoque').on('input', function(event)
{
event.preventDefault();
@@ -92,28 +94,40 @@ var Analoque = {
var kid = query.attr('data-id');
var field_id_input = $('.field_' + did + '_' + fid + '_' + kid);
- query.autocomplete("index.php?do=fields&field=analoque&type=search&doc_id=" + did + "&field_id=" + fid, {
+ if (res_search)
+ return false;
+
+ res_search = true;
+
+ query.autocomplete("index.php?do=fields&field=teasers&type=search&doc_id=" + did + "&field_id=" + fid, {
width: query.outerWidth(),
- max: 10,
+ max: 5,
dataType: "json",
matchContains: "word",
scroll: true,
scrollHeight: 200,
parse: function(data) {
- return $.map(data, function(row) {
- return {
- data: row,
- value: row.doc_title,
- result: query.val()
- }
- });
+ res_search = false;
+
+ if (typeof data === 'object')
+ {
+ return $.map(data, function(row) {
+ return {
+ data: row,
+ value: row.doc_title,
+ result: query.val()
+ }
+ });
+ }
+
+ return false;
},
formatItem: function(item) {
- return '' + item.doc_article + ' ' + item.doc_name + '
';
+ return '' + item.doc_article + ' ' + item.doc_name + '
';
}
}).result(function(e, item) {
- query.val(item.doc_name);
- field_id_input.val(item.doc_id);
+ query.val(item.doc_name);
+ field_id_input.val(item.doc_id);
});
return false;
@@ -123,7 +137,6 @@ var Analoque = {
}
}
-$(document).ready(function()
-{
- Analoque.init();
+$(document).ready(function() {
+ Teasers.init();
});
diff --git a/fields/teasers/tpl/field.tpl b/fields/teasers/tpl/field.tpl
index 36d0c54..0978bfa 100644
--- a/fields/teasers/tpl/field.tpl
+++ b/fields/teasers/tpl/field.tpl
@@ -1,5 +1,5 @@
{if $analoque != load}
- {assign var=analoque value='' scope="global"}
+ {assign var=teasers value='' scope="global"}
{if $smarty.request.outside}
{else}
@@ -14,7 +14,7 @@
var analoque_del_conf = '{#del_conf#}';
var analoque_del_head = '{#del_head#}';
- {assign var=analoque value="load" scope="global"}
+ {assign var=teasers value="load" scope="global"}
{/if}
diff --git a/fields/youtube/lang/bg.txt b/fields/youtube/lang/bg.txt
index 4e0085c..d6f8fcb 100644
--- a/fields/youtube/lang/bg.txt
+++ b/fields/youtube/lang/bg.txt
@@ -1,3 +1,9 @@
[admin]
-
name = "YouTube"
+f_url = "Линк"
+f_width = "Ширина"
+f_height = "Височина"
+f_fullscreen = "На цял екран"
+f_allow = "Разреши"
+f_forbidden = "Забрани"
+f_metod = "Метод на вмъкване"
diff --git a/fields/youtube/lang/cz.txt b/fields/youtube/lang/cz.txt
index e087e9b..8bc8292 100644
--- a/fields/youtube/lang/cz.txt
+++ b/fields/youtube/lang/cz.txt
@@ -1,2 +1,9 @@
[admin]
name = "YouTube"
+f_url = "Ссылка"
+f_width = "Ширина"
+f_height = "Высота"
+f_fullscreen = "Полноэкранный режим"
+f_allow = "Разрешить"
+f_forbidden = "Запретить"
+f_metod = "Метод вставки"
\ No newline at end of file
diff --git a/fields/youtube/lang/en.txt b/fields/youtube/lang/en.txt
index e087e9b..2b76c11 100644
--- a/fields/youtube/lang/en.txt
+++ b/fields/youtube/lang/en.txt
@@ -1,2 +1,9 @@
[admin]
name = "YouTube"
+f_url = "Url"
+f_width = "Width"
+f_height = "Height"
+f_fullscreen = "Fullscreen"
+f_allow = "Allow"
+f_forbidden = "Forbidden"
+f_metod = "Metod"
\ No newline at end of file
diff --git a/fields/youtube/lang/pl.txt b/fields/youtube/lang/pl.txt
index e087e9b..2b76c11 100644
--- a/fields/youtube/lang/pl.txt
+++ b/fields/youtube/lang/pl.txt
@@ -1,2 +1,9 @@
[admin]
name = "YouTube"
+f_url = "Url"
+f_width = "Width"
+f_height = "Height"
+f_fullscreen = "Fullscreen"
+f_allow = "Allow"
+f_forbidden = "Forbidden"
+f_metod = "Metod"
\ No newline at end of file
diff --git a/fields/youtube/lang/ru.txt b/fields/youtube/lang/ru.txt
index e087e9b..8bc8292 100644
--- a/fields/youtube/lang/ru.txt
+++ b/fields/youtube/lang/ru.txt
@@ -1,2 +1,9 @@
[admin]
name = "YouTube"
+f_url = "Ссылка"
+f_width = "Ширина"
+f_height = "Высота"
+f_fullscreen = "Полноэкранный режим"
+f_allow = "Разрешить"
+f_forbidden = "Запретить"
+f_metod = "Метод вставки"
\ No newline at end of file
diff --git a/fields/youtube/lang/ua.txt b/fields/youtube/lang/ua.txt
index e087e9b..2b76c11 100644
--- a/fields/youtube/lang/ua.txt
+++ b/fields/youtube/lang/ua.txt
@@ -1,2 +1,9 @@
[admin]
name = "YouTube"
+f_url = "Url"
+f_width = "Width"
+f_height = "Height"
+f_fullscreen = "Fullscreen"
+f_allow = "Allow"
+f_forbidden = "Forbidden"
+f_metod = "Metod"
\ No newline at end of file
diff --git a/fields/youtube/tpl/field.tpl b/fields/youtube/tpl/field.tpl
index 7366b60..55f3d3b 100644
--- a/fields/youtube/tpl/field.tpl
+++ b/fields/youtube/tpl/field.tpl
@@ -1,24 +1,24 @@
- Ссылка:
+ {#f_url#}:
- Ширина: px
+ {#f_width#}: px
- Высота: px
+ {#f_height#}: px
- Полноэкранный режим:
+ {#f_fullscreen#}:
- Разрешить
- Запретить
+ {#f_allow#}
+ {#f_forbidden#}
- Метод вставки:
+ {#f_metod#}:
Embed
Iframe
-
+
\ No newline at end of file
diff --git a/functions/func.block.php b/functions/func.block.php
index a7fb44a..44091da 100644
--- a/functions/func.block.php
+++ b/functions/func.block.php
@@ -29,6 +29,10 @@ function parse_block($id)
{
$cache_file = BASE_DIR . '/cache/sql/block/' . $id . '.cache';
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE)
+ $cache_file = null;
+
if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
@@ -48,7 +52,8 @@ function parse_block($id)
LIMIT 1
")->GetCell();
- file_put_contents($cache_file,$return);
+ if ($cache_file)
+ file_put_contents($cache_file, $return);
}
//-- парсим теги
@@ -84,9 +89,9 @@ function parse_block($id)
$gen_time = Debug::endTime('BLOCK_' . $id);
- $GLOBALS['block_generate'][] = array('BLOCK_'. $id => $gen_time);
+ $GLOBALS['block_generate']['BLOCKS'][$id] = $gen_time;
return $return;
}
}
-?>
+?>
\ No newline at end of file
diff --git a/functions/func.breadcrumbs.php b/functions/func.breadcrumbs.php
index 16b6931..103fedd 100644
--- a/functions/func.breadcrumbs.php
+++ b/functions/func.breadcrumbs.php
@@ -62,8 +62,17 @@
$lang_home_alias = $AVE_DB->Query($sql)->FetchRow();
- $search = array('[name]', '[link]', '[count]');
- $replace = array($lang_home_alias->document_breadcrum_title, $bread_show_host ? HOST . '/' . ltrim($lang_home_alias->document_alias, '/') : $lang_home_alias->document_alias, 1);
+ $search = array(
+ '[name]',
+ '[link]',
+ '[count]'
+ );
+
+ $replace = array(
+ $lang_home_alias->document_breadcrum_title,
+ $bread_show_host ? HOST . '/' . ltrim($lang_home_alias->document_alias, '/') : $lang_home_alias->document_alias,
+ 1
+ );
$link = str_replace($search, $replace, $bread_link_template);
@@ -74,7 +83,7 @@
if ($bread_sepparator_use)
$bread_crumb .= $bread_sepparator;
- unset($search, $replace, $link, $sql, $lang_home_alias);
+ unset ($search, $replace, $link, $sql, $lang_home_alias);
}
if ($curent_document == 1 || $curent_document == PAGE_NOT_FOUND_ID)
@@ -195,7 +204,9 @@
}
// Последний элемент
- if (get_settings('bread_link_box_last') == 1 || (isset($AVE_Core->curentdoc->bread_link_box_last) && $AVE_Core->curentdoc->bread_link_box_last == 1))
+ if ((isset($AVE_Core->curentdoc->bread_link_box_last) && $AVE_Core->curentdoc->bread_link_box_last == 0))
+ $bread_crumb .= '';
+ else if (get_settings('bread_link_box_last') == 1 || (isset($AVE_Core->curentdoc->bread_link_box_last) && $AVE_Core->curentdoc->bread_link_box_last == 1))
$bread_crumb .= sprintf($bread_self_box, $current->document_breadcrum_title);
if (! $noprint)
@@ -211,4 +222,4 @@
return $crumbs[$curent_document];
}
-?>
+?>
\ No newline at end of file
diff --git a/functions/func.common.php b/functions/func.common.php
index 1afa549..4f7b2b5 100755
--- a/functions/func.common.php
+++ b/functions/func.common.php
@@ -15,8 +15,8 @@
/**
* Вставляем файл с пользовательскими функциями
*/
- if (file_exists(BASE_DIR."/functions/func.custom.php"))
- include (BASE_DIR."/functions/func.custom.php");
+ if (file_exists(BASE_DIR . '/functions/func.custom.php'))
+ include (BASE_DIR . '/functions/func.custom.php');
/**
@@ -255,9 +255,7 @@
static $settings = null;
if ($settings === null)
- {
- $settings = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_settings", SYSTEM_CACHE_LIFETIME)->FetchAssocArray();
- }
+ $settings = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_settings", SYSTEM_CACHE_LIFETIME, 'settings')->FetchAssocArray();
if ($field == '')
return $settings;
@@ -928,6 +926,37 @@
}
+ /**
+ * Функция поиска ключевых слов
+ *
+ * @param string $string - запрос
+ * @return string
+ */
+ function searchTags()
+ {
+ global $AVE_DB;
+
+ $sql = $AVE_DB->Query("
+ SELECT DISTINCT
+ tag
+ FROM
+ " . PREFIX . "_document_tags
+ ");
+
+ $tags = array();
+
+ $ii = 0;
+
+ while ($row = $sql->GetCell())
+ {
+ $tags[]['value'] = $row;
+ }
+
+ echo json_encode($tags);
+ exit;
+ }
+
+
/**
* Формирование строки из случайных символов
*
@@ -1084,4 +1113,4 @@
-?>
+?>
\ No newline at end of file
diff --git a/functions/func.fields.php b/functions/func.fields.php
index 378b966..fec137a 100644
--- a/functions/func.fields.php
+++ b/functions/func.fields.php
@@ -76,7 +76,7 @@
return ' ';
case 'doc':
case 'req':
- if (!$tpl_empty)
+ if (! $tpl_empty)
{
$field_param = explode('|', $field_value);
$field_value = preg_replace_callback(
@@ -90,7 +90,8 @@
}
return $field_value;
- default: return $field_value;
+ default:
+ return $field_value;
}
}
@@ -171,14 +172,29 @@
*
* @return string
*/
- function get_field_num($rubric_id, $alias){
+ function get_field_num($rubric_id, $alias)
+ {
global $AVE_DB;
- static $alias_field_id=array();
- if(isset($alias_field_id[$rubric_id][$alias])) return $alias_field_id[$rubric_id][$alias];
- $alias_field_id[$rubric_id][$alias] = $AVE_DB->Query("SELECT Id FROM " . PREFIX . "_rubric_fields WHERE (rubric_field_alias='".addslashes($alias)."' OR Id='".intval($alias)."') AND rubric_id=".intval($rubric_id))->GetCell();
+
+ static $alias_field_id = array();
+
+ if (isset($alias_field_id[$rubric_id][$alias]))
+ return $alias_field_id[$rubric_id][$alias];
+
+ $sql = "
+ SELECT Id
+ FROM " . PREFIX . "_rubric_fields
+ WHERE (rubric_field_alias = '".addslashes($alias)."'
+ OR Id = '".intval($alias)."')
+ AND rubric_id = ".intval($rubric_id)
+ ;
+
+ $alias_field_id[$rubric_id][$alias] = $AVE_DB->Query($sql)->GetCell();
+
return $alias_field_id[$rubric_id][$alias];
}
+
/**
* Возвращаем
*
@@ -196,11 +212,18 @@
if(isset($alias_field_id[$id]))
return $alias_field_id[$id];
- $alias_field_id[$id] = $AVE_DB->Query("SELECT rubric_field_default FROM " . PREFIX . "_rubric_fields WHERE Id = ".intval($id))->GetCell();
+ $sql = "
+ SELECT rubric_field_default
+ FROM " . PREFIX . "_rubric_fields
+ WHERE Id = ".intval($id)
+ ;
+
+ $alias_field_id[$id] = $AVE_DB->Query($sql)->GetCell();
return $alias_field_id[$id];
}
+
/**
* Возвращаем шаблон tpl или пусто
*
@@ -210,25 +233,41 @@
*
* @return string
*/
- function get_field_tpl($dir='', $field_id=0, $type='admin'){
-
+ function get_field_tpl($dir='', $field_id=0, $type='admin')
+ {
$alias_field_id = get_field_alias($field_id);
- switch ($type) {
+ switch ($type)
+ {
case '':
case 'admin':
default:
- $tpl = (file_exists($dir.'field-'.$field_id.'.tpl')) ? $dir.'field-'.$field_id.'.tpl' : ((file_exists($dir.'field-'.$alias_field_id.'.tpl')) ? $dir.'field-'.$alias_field_id.'.tpl' : $dir.'field.tpl');
+ $tpl = (file_exists($dir.'field-'.$field_id.'.tpl'))
+ ? $dir.'field-'.$field_id.'.tpl'
+ : ((file_exists($dir.'field-'.$alias_field_id.'.tpl'))
+ ? $dir.'field-'.$alias_field_id.'.tpl'
+ : $dir.'field.tpl');
+
$tpl = (@filesize($tpl)) ? $tpl : '';
break;
case 'doc':
- $tpl = (file_exists($dir.'field-doc-'.$field_id.'.tpl')) ? $dir.'field-doc-'.$field_id.'.tpl' : ((file_exists($dir.'field-doc-'.$alias_field_id.'.tpl')) ? $dir.'field-doc-'.$alias_field_id.'.tpl' : $dir.'field-doc.tpl');
+ $tpl = (file_exists($dir.'field-doc-'.$field_id.'.tpl'))
+ ? $dir.'field-doc-'.$field_id.'.tpl'
+ : ((file_exists($dir.'field-doc-'.$alias_field_id.'.tpl'))
+ ? $dir.'field-doc-'.$alias_field_id.'.tpl'
+ : $dir.'field-doc.tpl');
+
$tpl = (@filesize($tpl)) ? $tpl : '';
break;
case 'req':
- $tpl = (file_exists($dir.'field-req-'.$field_id.'.tpl')) ? $dir.'field-req-'.$field_id.'.tpl' : ((file_exists($dir.'field-req-'.$alias_field_id.'.tpl')) ? $dir.'field-req-'.$alias_field_id.'.tpl' : $dir.'field-req.tpl');
+ $tpl = (file_exists($dir.'field-req-'.$field_id.'.tpl'))
+ ? $dir.'field-req-'.$field_id.'.tpl'
+ : ((file_exists($dir.'field-req-'.$alias_field_id.'.tpl'))
+ ? $dir.'field-req-'.$alias_field_id.'.tpl'
+ : $dir.'field-req.tpl');
+
$tpl = (@filesize($tpl)) ? $tpl : '';
break;
}
@@ -245,7 +284,7 @@
*
* @return string
*/
- function document_get_field($field_id, $document_id=null)
+ function document_get_field($field_id, $document_id = null)
{
global $AVE_Core;
@@ -370,7 +409,7 @@
if (! is_numeric($document_id))
return false;
- if (!isset ($document_fields[$document_id]))
+ if (! isset($document_fields[$document_id]))
{
$document_fields[$document_id] = false;
@@ -446,6 +485,7 @@
$document_fields[$row['document_id']][$row['rubric_field_alias']] = $row['rubric_field_id'];
}
}
+
return $document_fields[$document_id];
}
@@ -650,4 +690,37 @@
return $return;
}
-?>
+
+ /**
+ * Возвращает наименование поля документа по номеру
+ *
+ * @param int $field_id ([tag:fld:X]) - номер поля
+ * @param int $doc_id
+ * @param int $parametr ([tag:parametr:X]) - часть поля
+ *
+ * @return string
+ */
+ function get_field_name($field_id, $doc_id = null)
+ {
+ global $req_item_id;
+
+ //-- Если не передан $doc_id, то проверяем реквест
+ if (! $doc_id && $req_item_id)
+ $doc_id = $req_item_id;
+ //-- Или берём для текущего дока
+ elseif (! $doc_id && $_REQUEST['id'] > 0)
+ $doc_id = $_REQUEST['id'];
+ //-- Возвращаем FALSE, если не число
+ elseif (! is_numeric($doc_id))
+ return false;
+
+ $document_fields = get_document_fields($doc_id);
+
+ if (empty($document_fields[$field_id]))
+ return false;
+
+ $field_name = $document_fields[$field_id]['rubric_field_title'];
+
+ return $field_name;
+ }
+?>
\ No newline at end of file
diff --git a/functions/func.helpers.php b/functions/func.helpers.php
index 9b76983..7ae8068 100644
--- a/functions/func.helpers.php
+++ b/functions/func.helpers.php
@@ -341,29 +341,29 @@ if (!function_exists('cleanSanitize')){
* @param bool $middle Вырезает середину, оставляет начало + разделитель + конец
* @return mixed|string
*/
-if (!function_exists('trancate'))
+if (! function_exists('trancate'))
{
function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length == 0)
return '';
- if (strlen($string) > $length)
+ if (mb_strlen($string) > $length)
{
- $length -= min($length, strlen($etc));
+ $length -= min($length, mb_strlen($etc));
if (! $break_words && ! $middle)
{
- $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
+ $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1));
}
- if (!$middle)
+ if (! $middle)
{
- return substr($string, 0, $length) . $etc;
+ return mb_substr($string, 0, $length) . $etc;
}
else
{
- return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
+ return mb_substr($string, 0, $length / 2) . $etc . mb_substr($string, - $length / 2);
}
}
else
@@ -409,7 +409,9 @@ if (!function_exists('truncate_text'))
if (strlen($out) >= $n)
{
$out = trim($out);
- return (strlen($out) == strlen($str)) ? $out : $out . $end_char;
+ return (strlen($out) == strlen($str))
+ ? $out
+ : $out . $end_char;
}
}
return $str;
diff --git a/functions/func.navigation.php b/functions/func.navigation.php
index 7d89228..7b2b9fa 100644
--- a/functions/func.navigation.php
+++ b/functions/func.navigation.php
@@ -21,25 +21,45 @@
{
global $AVE_DB, $AVE_Core;
- $gen_time = microtime(true);
-
- // извлекаем id из аргумента
+ // Извлекаем id из аргумента
$navi_id = $navi_tag[1];
+ Debug::startTime('NAVIAGTION_' . $navi_id);
+
+ // Достаем для проверки тип меню
+ $sql = "
+ SELECT
+ expand_ext
+ FROM
+ ".PREFIX."_navigation
+ WHERE
+ navigation_id = '" . $navi_id . "'
+ OR
+ alias = '" . $navi_id . "'
+ ";
+
+ $expnad_ext = $AVE_DB->Query($sql, SYSTEM_CACHE_LIFETIME, 'nav_' . $navi_id)->GetCell();
+
// извлекаем level из аргумента
- $navi_print_level = $navi_tag[2];
+ $navi_print_level = (! empty($navi_tag[2]))
+ ? $navi_tag[2]
+ : '';
$navi = '';
$cache_file = BASE_DIR . '/cache/sql/nav/template-' . $navi_id . '.cache';
- if(! file_exists(dirname($cache_file)))
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE || $expnad_ext != 1)
+ $cache_file = null;
+
+ if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
// получаем меню навигации по id,
// и если такой не существует, выводим сообщение
- if(file_exists($cache_file))
+ if (file_exists($cache_file))
{
$navi_menu = unserialize(file_get_contents($cache_file));
}
@@ -47,7 +67,8 @@
{
$navi_menu = get_navigations($navi_id);
- file_put_contents($cache_file, serialize($navi_menu));
+ if ($cache_file)
+ file_put_contents($cache_file, serialize($navi_menu));
}
if (! $navi_menu)
@@ -75,10 +96,14 @@
// после ; id текущего пункта
// id текущего документа. Если не задан, то главная страница
- $doc_active_id = (int)(($_REQUEST['id']) ? $_REQUEST['id'] : 1);
+ $doc_active_id = (int)(($_REQUEST['id'])
+ ? $_REQUEST['id']
+ : 1);
// алиас текущего документа
- $alias = ltrim(isset($AVE_Core->curentdoc->document_alias) ? $AVE_Core->curentdoc->document_alias : '');
+ $alias = ltrim(isset($AVE_Core->curentdoc->document_alias)
+ ? $AVE_Core->curentdoc->document_alias
+ : '');
// запрос для выборки по текущему алиасу
$sql_doc_active_alias = '';
@@ -146,10 +171,10 @@
$sql_navi_level = '';
$sql_navi_active = '';
- if($navi_print_level)
+ if ($navi_print_level)
{
$sql_navi_level = ' AND level IN (' . $navi_print_level . ') ';
- $sql_navi_active = ' AND parent_id IN(' . $navi_active_way_str . ') ';
+ $sql_navi_active = ' AND parent_id IN (' . $navi_active_way_str . ') ';
}
// обычное использование навигации
@@ -157,14 +182,14 @@
{
switch ($navi_menu->expand_ext)
{
- // все уровни
- case 1:
+ // текущий и родительский уровни
+ case 0:
+ $sql_navi_active = ' AND parent_id IN (' . $navi_active_way_str . ') ';
$navi_parent = 0;
break;
- // текущий и родительский уровни
- case 0:
- $sql_navi_active = ' AND parent_id IN(' . $navi_active_way_str . ') ';
+ // все уровни
+ case 1:
$navi_parent = 0;
break;
@@ -176,50 +201,75 @@
}
}
-
$cache_items = BASE_DIR . '/cache/sql/nav/items-' . $navi_id . '.cache';
$navi_items = array();
- //-- Проверяем есть файл кеша, если есть пропускам запрос к БД
- if(! file_exists($cache_items))
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE || $expnad_ext != 1)
+ $cache_items = null;
+
+ if (empty($navi_print_level))
{
- //-- Запрос пунктов меню
- $sql = "
- SELECT *
- FROM
- " . PREFIX . "_navigation_items
- WHERE
- status = '1'
- AND
- navigation_id = '" . $navi_menu->navigation_id . "'" .
- $sql_navi_level .
- $sql_navi_active . "
- ORDER BY
- position ASC
- ";
-
- $sql_navi_items = $AVE_DB->Query($sql);
-
- while ($row_navi_items = $sql_navi_items->FetchAssocArray())
+ //-- Проверяем есть файл кеша, если есть пропускам запрос к БД
+ if (! file_exists($cache_items))
{
- $navi_items[$row_navi_items['parent_id']][] = $row_navi_items;
- }
+ //-- Запрос пунктов меню
+ $sql = "
+ SELECT *
+ FROM
+ " . PREFIX . "_navigation_items
+ WHERE
+ status = '1'
+ AND
+ navigation_id = '" . $navi_menu->navigation_id . "'" .
+ $sql_navi_level .
+ $sql_navi_active . "
+ ORDER BY
+ position ASC
+ ";
- file_put_contents($cache_items, serialize($navi_items));
+ $sql_navi_items = $AVE_DB->Query($sql);
+
+ while ($row_navi_items = $sql_navi_items->FetchAssocArray())
+ $navi_items[$row_navi_items['parent_id']][] = $row_navi_items;
+
+ if ($cache_items)
+ file_put_contents($cache_items, serialize($navi_items));
+ }
+ else
+ {
+ $navi_items = unserialize(file_get_contents($cache_items));
+ }
}
else
{
- $navi_items = unserialize(file_get_contents($cache_items));
- }
+ //-- Запрос пунктов меню
+ $sql = "
+ SELECT *
+ FROM
+ " . PREFIX . "_navigation_items
+ WHERE
+ status = '1'
+ AND
+ navigation_id = '" . $navi_menu->navigation_id . "'" .
+ $sql_navi_level . "
+ ORDER BY
+ position ASC
+ ";
- if($navi_print_level)
- {
- $keys = array_keys($navi_items);
- $navi_parent = ! empty($keys)
- ? $keys[0]
- : 0;
- }
+ $sql_navi_items = $AVE_DB->Query($sql);
+
+ while ($row_navi_items = $sql_navi_items->FetchAssocArray())
+ {
+ $navi_items[$row_navi_items['parent_id']][] = $row_navi_items;
+ }
+
+ $keys = array_keys($navi_items);
+ $navi_parent = ! empty($keys)
+ ? $keys[0]
+ : 0;
+ }
// Парсим теги в шаблонах пунктов
$navi_item_tpl = array(
@@ -248,8 +298,9 @@
$navi = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $navi);
$navi = str_replace(array("\n","\r"),'',$navi);
- $gen_time = microtime(true) - $gen_time;
- $GLOBALS['block_generate'][] = array('NAVIGATION_' . $navi_id => $gen_time);
+ $gen_time = Debug::endTime('NAVIAGTION_' . $navi_id);
+
+ $GLOBALS['block_generate']['NAVIAGTIONS'][$navi_id] = $gen_time;
return $navi;
}
diff --git a/functions/func.parserequest.php b/functions/func.parserequest.php
index 03ee099..3712c4d 100755
--- a/functions/func.parserequest.php
+++ b/functions/func.parserequest.php
@@ -1,386 +1,1050 @@
Query("
- SELECT *
- FROM
- " . PREFIX . "_request_conditions
- WHERE
- request_id = '" . $id . "'
- AND
- condition_status = '1'
- ORDER BY
- condition_position ASC
- ");
-
- // Обрабатываем выпадающие списки
-
- if (! defined('ACP'))
+ function request_get_settings($id)
{
- $doc = 'doc_' . $AVE_Core->curentdoc->Id;
+ global $AVE_DB;
- if (isset($_POST['req_' . $id]))
- $_SESSION[$doc]['req_' . $id] = $_POST['req_' . $id];
- elseif (isset($_SESSION[$doc]['req_' . $id]))
- $_POST['req_' . $id] = $_SESSION[$doc]['req_' . $id];
+ // Получаем информацию о запросе
+ $reqest_settings = $AVE_DB->Query("
+ SELECT
+ *
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ " . (is_numeric($id) ? 'Id' : 'request_alias') . " = '" . $id . "'
+ ", -1, 'request/settings/' . $id)->FetchRow();
+
+ // Выходим, если нет запроса
+ if (! is_object($reqest_settings))
+ return '';
+ else
+ return $reqest_settings;
}
- if (! empty($_POST['req_' . $id]) && is_array($_POST['req_' . $id]))
- {
- $i = 1;
- foreach ($_POST['req_' . $id] as $fid => $val)
+ /**
+ * Обработка условий запроса.
+ * Возвращает строку условий в SQL-формате
+ *
+ * @param int $id идентификатор запроса
+ * @return string
+ */
+ function request_get_condition_sql_string($id, $update_db = false)
+ {
+ global $AVE_DB, $AVE_Core;
+
+ $id = (int)$id;
+ $from = array();
+ $where = array();
+
+ $sql_ak = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX . "_request_conditions
+ WHERE
+ request_id = '" . $id . "'
+ AND
+ condition_status = '1'
+ ORDER BY
+ condition_position ASC
+ ");
+
+ // Обрабатываем выпадающие списки
+
+ if (! defined('ACP'))
{
- if (! ($val != '' && isset($_SESSION['val_' . $fid]) && in_array($val, $_SESSION['val_' . $fid])))
+ $doc = 'doc_' . $AVE_Core->curentdoc->Id;
+
+ if (isset($_POST['req_' . $id]))
+ $_SESSION[$doc]['req_' . $id] = $_POST['req_' . $id];
+ elseif (isset($_SESSION[$doc]['req_' . $id]))
+ $_POST['req_' . $id] = $_SESSION[$doc]['req_' . $id];
+ }
+
+ if (! empty($_POST['req_' . $id]) && is_array($_POST['req_' . $id]))
+ {
+ $i = 1;
+
+ foreach ($_POST['req_' . $id] as $fid => $val)
+ {
+ if (! ($val != '' && isset($_SESSION['val_' . $fid]) && in_array($val, $_SESSION['val_' . $fid])))
+ continue;
+
+ $from_dd[] = "%%PREFIX%%_document_fields AS t0$i, ";
+
+ $where_dd[] = "((t0$i.document_id = a.Id) AND (t0$i.rubric_field_id = $fid AND t0$i.field_value = '$val'))";
+
+ ++$i;
+ }
+ }
+
+ $i = 0;
+
+ while ($row_ak = $sql_ak->FetchRow())
+ {
+ // id поля рубрики
+ $fid = $row_ak->condition_field_id;
+ // значение для условия
+ $val = trim($row_ak->condition_value);
+ // если это поле используется для выпадающего списка или пустое значение для условия, пропускаем
+ if (isset($_POST['req_' . $id]) && isset($_POST['req_' . $id][$fid]) || $val==='')
continue;
+ // И / ИЛИ
+ if (! isset($join) && $row_ak->condition_join)
+ $join = $row_ak->condition_join;
+ // тип сравнения
+ $type = $row_ak->condition_compare;
- $from_dd[] = "%%PREFIX%%_document_fields AS t0$i, ";
+ // выясняем, числовое поле или нет
+ if (! isset($numeric[$fid]))
+ {
+ $numeric[$fid] = (bool)$AVE_DB->Query("
+ SELECT
+ rubric_field_numeric
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ Id = '" . $fid . "'
+ ")->GetCell();
+ }
- $where_dd[] = "((t0$i.document_id = a.Id) AND (t0$i.rubric_field_id = $fid AND t0$i.field_value = '$val'))";
+ $fv = $numeric[$fid] ? "t$fid.field_number_value" : "UPPER(t$fid.field_value)";
- ++$i;
+ // подставляем название таблицы в свободные условия
+ $val = addcslashes(str_ireplace(array('[field]','[numeric_field]'),$fv,$val),"'");
+
+ // формируем выбор таблицы
+ // первый раз евалом проходим значение и запоминаем это в переменной $v[$i]
+ // как только таблица выбрана, фиксируем это в $t[$fid], чтобы не выбирать по несколько раз одни и те же таблицы
+ $from[] = "$val ')); \$t = array(); if (\$v[$i]>'' && !isset(\$t[$fid])) {echo \"%%PREFIX%%_document_fields AS t$fid,\"; \$t[$fid]=1;}?>";
+
+ // обрабатываем условия
+ switch ($type)
+ {
+ case 'N<':case '<': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv < UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+ case 'N>':case '>': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv > UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+ case 'N<=':case '<=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv <= UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+ case 'N>=':case '>=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv >= UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+
+ case '==': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv = UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+ case '!=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv != UPPER('\$v[$i]'))) $join\" : ''?>"; break;
+ case '%%': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('%\$v[$i]%'))) $join\" : ''?>"; break;
+ case '%': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('\$v[$i]%'))) $join\" : ''?>"; break;
+ case '--': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT LIKE UPPER('%\$v[$i]%'))) $join\" : ''?>"; break;
+ case '!-': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT LIKE UPPER('\$v[$i]%'))) $join\" : ''?>"; break;
+
+ case 'SEGMENT': $where[] = "
+ \$v[$i]['seg']=@explode(',',\$v[$i]);
+ \$v[$i]['seg'][0]=(int)trim(\$v[$i]['seg'][0]);
+ \$v[$i]['seg'][1]=(int)trim(\$v[$i]['seg'][1]);
+ echo (\$v[$i]>'' && \$v[$i]{0}!=',' && \$v[$i]['seg'][0] <= \$v[$i]['seg'][1]) ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv >= '\" . \$v[$i]['seg'][0] . \"' AND $fv <= '\" . \$v[$i]['seg'][1] . \"')) $join\" : '');?>"; break;
+ case 'INTERVAL': $where[] = "
+ \$v[$i]['seg']=@explode(',',\$v[$i]);
+ \$v[$i]['seg'][0]=(int)trim(\$v[$i]['seg'][0]);
+ \$v[$i]['seg'][1]=(int)trim(\$v[$i]['seg'][1]);
+ echo (\$v[$i]>'' && \$v[$i]{0}!=',' && \$v[$i]['seg'][0] < \$v[$i]['seg'][1]) ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv > '\" . \$v[$i]['seg'][0] . \"' AND $fv < '\" . \$v[$i]['seg'][1] . \"')) $join\" : '');?>"; break;
+
+ case 'IN=': $where[] = "=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv IN (\$v[$i]))) $join\" : ''?>"; break;
+ case 'NOTIN=': $where[] = "=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT IN (\$v[$i]))) $join\" : ''?>"; break;
+
+ case 'ANY': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv=ANY(\$v[$i]))) $join\" : ''?>"; break;
+ case 'FRE': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND (\$v[$i]))) $join\" : ''?>"; break;
+ }
+
+ $i++;
}
- }
- $i = 0;
+ $retval = array();
- while ($row_ak = $sql_ak->FetchRow())
- {
- // id поля рубрики
- $fid = $row_ak->condition_field_id;
- // значение для условия
- $val = trim($row_ak->condition_value);
- // если это поле используется для выпадающего списка или пустое значение для условия, пропускаем
- if (isset($_POST['req_' . $id]) && isset($_POST['req_' . $id][$fid]) || $val==='')
- continue;
- // И / ИЛИ
- if (! isset($join) && $row_ak->condition_join)
- $join = $row_ak->condition_join;
- // тип сравнения
- $type = $row_ak->condition_compare;
-
- // выясняем, числовое поле или нет
- if (! isset($numeric[$fid]))
+ if (! empty($where) || ! empty($where_dd))
{
- $numeric[$fid] = (bool)$AVE_DB->Query("
- SELECT
- rubric_field_numeric
- FROM
- " . PREFIX . "_rubric_fields
+ if (! empty($where_dd))
+ {
+ $from = (isset($from_dd) ? array_merge($from, $from_dd) : $from);
+ $from = implode(' ', $from);
+ $where_dd = (isset($where_dd) ? ' AND ' : '') . implode(' AND ', $where_dd);
+ $where = implode(' ', $where) . " ";
+ $retval = array('from'=>$from,'where'=> $where.$where_dd);
+ }
+ else
+ {
+ $from = implode(' ', $from);
+ $where = implode(' ', $where) . " ";
+ $retval = array('from'=>$from,'where'=> $where);
+ }
+ }
+
+ // если вызвано из админки или просили обновить, обновляем запрос в бд
+ if (defined('ACP') || $update_db)
+ {
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request
+ SET
+ request_where_cond = '" . ($retval ? addslashes(serialize($retval)) : '') . "'
WHERE
- Id = '" . $fid . "'
- ")->GetCell();
+ Id = '" . $id . "'
+ ");
+
+ $AVE_DB->clear_request($id);
}
- $fv = $numeric[$fid] ? "t$fid.field_number_value" : "UPPER(t$fid.field_value)";
-
- // подставляем название таблицы в свободные условия
- $val = addcslashes(str_ireplace(array('[field]','[numeric_field]'),$fv,$val),"'");
-
- // формируем выбор таблицы
- // первый раз евалом проходим значение и запоминаем это в переменной $v[$i]
- // как только таблица выбрана, фиксируем это в $t[$fid], чтобы не выбирать по несколько раз одни и те же таблицы
- $from[] = "$val ')); \$t = array(); if (\$v[$i]>'' && !isset(\$t[$fid])) {echo \"%%PREFIX%%_document_fields AS t$fid,\"; \$t[$fid]=1;}?>";
-
- // обрабатываем условия
- switch ($type)
- {
- case 'N<':case '<': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv < UPPER('\$v[$i]'))) $join\" : ''?>"; break;
- case 'N>':case '>': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv > UPPER('\$v[$i]'))) $join\" : ''?>"; break;
- case 'N<=':case '<=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv <= UPPER('\$v[$i]'))) $join\" : ''?>"; break;
- case 'N>=':case '>=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv >= UPPER('\$v[$i]'))) $join\" : ''?>"; break;
-
- case '==': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv = UPPER('\$v[$i]'))) $join\" : ''?>"; break;
- case '!=': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv != UPPER('\$v[$i]'))) $join\" : ''?>"; break;
- case '%%': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('%\$v[$i]%'))) $join\" : ''?>"; break;
- case '%': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('\$v[$i]%'))) $join\" : ''?>"; break;
- case '--': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT LIKE UPPER('%\$v[$i]%'))) $join\" : ''?>"; break;
- case '!-': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT LIKE UPPER('\$v[$i]%'))) $join\" : ''?>"; break;
-
- case 'SEGMENT': $where[] = "
- \$v[$i]['seg']=@explode(',',\$v[$i]);
- \$v[$i]['seg'][0]=(int)trim(\$v[$i]['seg'][0]);
- \$v[$i]['seg'][1]=(int)trim(\$v[$i]['seg'][1]);
- echo (\$v[$i]>'' && \$v[$i]{0}!=',' && \$v[$i]['seg'][0] <= \$v[$i]['seg'][1]) ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv >= '\" . \$v[$i]['seg'][0] . \"' AND $fv <= '\" . \$v[$i]['seg'][1] . \"')) $join\" : '');?>"; break;
- case 'INTERVAL': $where[] = "
- \$v[$i]['seg']=@explode(',',\$v[$i]);
- \$v[$i]['seg'][0]=(int)trim(\$v[$i]['seg'][0]);
- \$v[$i]['seg'][1]=(int)trim(\$v[$i]['seg'][1]);
- echo (\$v[$i]>'' && \$v[$i]{0}!=',' && \$v[$i]['seg'][0] < \$v[$i]['seg'][1]) ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv > '\" . \$v[$i]['seg'][0] . \"' AND $fv < '\" . \$v[$i]['seg'][1] . \"')) $join\" : '');?>"; break;
-
- case 'IN=': $where[] = "=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv IN (\$v[$i]))) $join\" : ''?>"; break;
- case 'NOTIN=': $where[] = "=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT IN (\$v[$i]))) $join\" : ''?>"; break;
-
- case 'ANY': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv=ANY(\$v[$i]))) $join\" : ''?>"; break;
- case 'FRE': $where[] = "=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND (\$v[$i]))) $join\" : ''?>"; break;
- }
-
- $i++;
+ return @$retval;
}
- $retval = array();
- if (! empty($where) || ! empty($where_dd))
+ /*
+ * Функция принимает строку, и возвращает
+ * адрес первого изображения, которую найдет
+ */
+
+ function getImgSrc($data)
{
- if (! empty($where_dd))
+ preg_match_all("/( )/u", $data, $images);
+
+ $host = $images[2][0];
+
+ if (preg_match("/(src=)('|\")(.+?)('|\")/u", $host, $matches) == 1)
+ $host = $matches[3];
+
+ preg_match('@/index\.php\?.*thumb=(.*?)\&@i', $host, $matches);
+
+ if (isset($matches[1]))
{
- $from = (isset($from_dd) ? array_merge($from, $from_dd) : $from);
- $from = implode(' ', $from);
- $where_dd = (isset($where_dd) ? ' AND ' : '') . implode(' AND ', $where_dd);
- $where = implode(' ', $where) . " ";
- $retval = array('from'=>$from,'where'=> $where.$where_dd);
+ return $matches[1];
}
else
{
- $from = implode(' ', $from);
- $where = implode(' ', $where) . " ";
- $retval = array('from'=>$from,'where'=> $where);
- }
- }
+ preg_match('/(.+)' . THUMBNAIL_DIR . '\/(.+)-.\d+x\d+(\..+)/u', $host, $matches);
- // если вызвано из админки или просили обновить, обновляем запрос в бд
- if (defined('ACP') || $update_db)
- {
- $AVE_DB->Query("
- UPDATE
- " . PREFIX . "_request
- SET
- request_where_cond = '" . ($retval ? addslashes(serialize($retval)) : '') . "'
- WHERE
- Id = '" . $id . "'
- ");
- }
-
- return @$retval;
-}
-
-
-/*
-* Функция принимает строку, и возвращает
-* адрес первого изображения, которую найдет
-*/
-
-function getImgSrc($data)
-{
- preg_match_all("/( )/u", $data, $images);
-
- $host = $images[2][0];
-
- if (preg_match("/(src=)('|\")(.+?)('|\")/u", $host, $matches) == 1)
- $host = $matches[3];
-
- preg_match('@/index\.php\?.*thumb=(.*?)\&@i', $host, $matches);
-
- if (isset($matches[1]))
- {
- return $matches[1];
- }
- else
- {
- preg_match('/(.+)'.THUMBNAIL_DIR.'\/(.+)-.\d+x\d+(\..+)/u', $host, $matches);
-
- if (isset($matches[1]))
- {
- return $matches[1] . $matches[2] . $matches[3];
- }
- else
+ if (isset($matches[1]))
{
- return $host;
+ return $matches[1] . $matches[2] . $matches[3];
}
- }
-}
-
-/**
- * Функция обработки тэгов полей с использованием шаблонов
- * в соответствии с типом поля
- *
- * @param int $rubric_id идентификатор рубрики
- * @param int $document_id идентификатор документа
- * @param int $maxlength максимальное количество символов обрабатываемого поля
- * @return string
- */
-function request_get_document_field($field_id, $document_id, $maxlength = '', $rubric_id=0)
-{
- if (! is_numeric($document_id) || $document_id < 1)
- return '';
-
- $document_fields = get_document_fields($document_id);
-
- if (! is_array($document_fields[$field_id]))
- $field_id = intval($document_fields[$field_id]);
-
- if (empty($document_fields[$field_id]))
- return '';
-
- $field_value = trim($document_fields[$field_id]['field_value']);
-
- if ($field_value == '' && $document_fields[$field_id]['tpl_req_empty'])
- return '';
-
- $func = 'get_field_' . $document_fields[$field_id]['rubric_field_type'];
-
- if(! is_callable($func))
- $func = 'get_field_default';
-
- $field_value = $func($field_value, 'req', $field_id, $document_fields[$field_id]['rubric_field_template_request'], $document_fields[$field_id]['tpl_req_empty'], $maxlength, $document_fields, $rubric_id, $document_fields[$field_id]['rubric_field_default']);
-
- if ($maxlength != '')
- {
- if ($maxlength == 'more' || $maxlength == 'esc'|| $maxlength == 'img')
- {
- if($maxlength == 'more')
- {
- // ToDo - Вывести в настройки или в настройки самого запроса
- $teaser = explode(' ', $field_value);
- $field_value = $teaser[0];
- }
- elseif($maxlength == 'esc')
- {
- $field_value = addslashes($field_value);
- }
- elseif($maxlength == 'img')
+ else
{
- $field_value = getImgSrc($field_value);
+ return $host;
}
- }
- elseif (is_numeric($maxlength))
+ }
+ }
+
+ /**
+ * Функция обработки тэгов полей с использованием шаблонов
+ * в соответствии с типом поля
+ *
+ * @param int $rubric_id идентификатор рубрики
+ * @param int $document_id идентификатор документа
+ * @param int $maxlength максимальное количество символов обрабатываемого поля
+ * @return string
+ */
+ function request_get_document_field($field_id, $document_id, $maxlength = '', $rubric_id = 0)
+ {
+ if (! is_numeric($document_id) || $document_id < 1)
+ return '';
+
+ $document_fields = get_document_fields($document_id);
+
+ if (! is_array($document_fields[$field_id]))
+ $field_id = intval($document_fields[$field_id]);
+
+ if (empty($document_fields[$field_id]))
+ return '';
+
+ $field_value = trim($document_fields[$field_id]['field_value']);
+
+ if ($field_value == '' && $document_fields[$field_id]['tpl_req_empty'])
+ return '';
+
+ $func = 'get_field_' . $document_fields[$field_id]['rubric_field_type'];
+
+ if (! is_callable($func))
+ $func = 'get_field_default';
+
+ $field_value = $func($field_value, 'req', $field_id, $document_fields[$field_id]['rubric_field_template_request'], $document_fields[$field_id]['tpl_req_empty'], $maxlength, $document_fields, $rubric_id, $document_fields[$field_id]['rubric_field_default']);
+
+ if ($maxlength != '')
+ {
+ if ($maxlength == 'more' || $maxlength == 'esc'|| $maxlength == 'img')
{
- if ($maxlength < 0)
+ if ($maxlength == 'more')
{
- $field_value = str_replace(array("\r\n","\n","\r"), " ", $field_value);
- $field_value = strip_tags($field_value, "");
- $field_value = preg_replace('/ +/', ' ', $field_value);
- $field_value = trim($field_value);
- $maxlength = abs($maxlength);
+ // ToDo - Вывести в настройки или в настройки самого запроса
+ $teaser = explode(' ', $field_value);
+ $field_value = $teaser[0];
}
- // ToDo - сделать настройки окончаний
- if ($maxlength != 0)
+ elseif ($maxlength == 'esc')
+ {
+ $field_value = addslashes($field_value);
+ }
+ elseif ($maxlength == 'img')
+ {
+ $field_value = getImgSrc($field_value);
+ }
+ }
+ elseif (is_numeric($maxlength))
{
- $field_value = mb_substr($field_value, 0, $maxlength) . ((strlen($field_value) > $maxlength) ? '... ' : '');
+ if ($maxlength < 0)
+ {
+ $field_value = str_replace(array("\r\n","\n","\r"), " ", $field_value);
+ $field_value = strip_tags($field_value, REQUEST_STRIP_TAGS);
+ $field_value = preg_replace('/ +/', ' ', $field_value);
+ $field_value = trim($field_value);
+
+ $maxlength = abs($maxlength);
+ }
+ // ToDo - сделать настройки окончаний
+ if ($maxlength != 0)
+ {
+ $field_value = truncate($field_value, $maxlength, REQUEST_ETC, REQUEST_BREAK_WORDS);
+ }
+
}
+ else
+ return false;
+ }
+
+ return $field_value;
+ }
+
+ function showteaser($id, $tparams = '')
+ {
+ $item = showrequestelement($id, '', $tparams);
+ $item = str_replace('[tag:path]', ABS_PATH, $item);
+ $item = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $item);
+
+ return $item;
+ }
+
+ // Функция получения уникальных параметров для каждого тизера
+ function f_params_of_teaser($id_param_array,$num)
+ {
+ global $params_of_teaser;
+ return $params_of_teaser[$id_param_array][$num];
+ }
+
+ // Функция получения элемента запроса
+ function showrequestelement($mixed, $template = '', $tparams = '')
+ {
+ global $AVE_DB, $req_item_num, $params_of_teaser, $use_cache;
+
+ if (is_array($mixed))
+ $mixed = $mixed[1];
+
+ $row = (is_object($mixed) ? $mixed : $AVE_DB->Query("
+ SELECT
+ a.*
+ FROM
+ " . PREFIX . "_documents AS a
+ WHERE
+ a.Id = '" . intval($mixed) . "'
+ GROUP BY
+ a.Id
+ LIMIT 1
+ ")->FetchRow());
+
+ if (! $row)
+ return '';
+
+ $tparams_id = '';
+
+ if ($tparams != '')
+ {
+ $tparams_id = $row->Id.md5($tparams); // Создаем уникальный id для каждого набора параметров
+ $params_of_teaser[$tparams_id] = array(); // Для отмены лишних ворнингов
+ $tparams = trim($tparams,'[]:'); // Удаляем: слева ':[', справа ']'
+ $params_of_teaser[$tparams_id] = explode('|',$tparams); // Заносим параметры в массив уникального id
+ }
+
+ $template = ($template > '' ? $template : $AVE_DB->Query(
+ "SELECT rubric_teaser_template FROM " . PREFIX . "_rubrics WHERE Id='" . intval($row->rubric_id) . "'"
+ )->GetCell());
+
+ $cachefile_docid = BASE_DIR . '/cache/sql/request/' . $row->Id . '/request-' . md5($template) . '.cache';
+
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE)
+ $cachefile_docid = null;
+
+ if (! file_exists($cachefile_docid))
+ {
+ $template = preg_replace("/\[tag:if_notempty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(request_get_document_field(\'$1\', '.$row->Id.', \'$2\', '.(int)$row->rubric_id.'), ENT_QUOTES)) != \'\') { '.'?'.'>', $template);
+ $template = preg_replace("/\[tag:if_empty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(request_get_document_field(\'$1\', '.$row->Id.', \'$2\', '.(int)$row->rubric_id.'), ENT_QUOTES)) == \'\') { '.'?'.'>', $template);
+ $template = str_replace('[tag:if:else]', '', $template);
+ $template = str_replace('[tag:/if]', '', $template);
+
+ // Парсим теги визуальных блоков
+ $item = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $template);
+
+ // Парсим теги системных блоков
+ $item = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $item);
+
+ $item = preg_replace_callback(
+ '/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/',
+ create_function(
+ '$m',
+ 'return request_get_document_field($m[1], ' . $row->Id . ', $m[2], ' . (int)$row->rubric_id . ');'
+ ),
+ $item
+ );
+
+ // Возвращаем поле из БД документа
+ $item = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
+ function ($match) use ($row)
+ {
+ return isset($row->{$match[1]})
+ ? $row->{$match[1]}
+ : null;
+ },
+ $item
+ );
+
+ // Если пришел вызов на активацию языковых файлов
+ $item = preg_replace_callback(
+ '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
+ {
+ global $AVE_Template;
+
+ return $AVE_Template->get_config_vars($match[1]);
+ },
+ $item
+ );
+
+ $item = str_replace('[tag:path]', ABS_PATH, $item);
+ $item = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false)
+ ? DEFAULT_THEME_FOLDER
+ : THEME_FOLDER)
+ . '/', $item);
+
+ // Watermarks
+ $item = preg_replace_callback(
+ '/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/',
+ create_function(
+ '$m',
+ 'watermarks($m[1], $m[2], $m[3]);'
+ ),
+ $item
+ );
+
+ // Удаляем ошибочные теги полей документа в шаблоне рубрики
+ $item = preg_replace('/\[tag:doc:\d*\]/', '', $item);
+ $item = preg_replace('/\[tag:langfile:\d*\]/', '', $item);
+
+ $item = preg_replace_callback('/\[tag:([r|c|f|t|s]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $item);
+
+ if ($tparams != '')
+ {
+ // Заменяем tparam в тизере
+ // $item = preg_replace('/\[tparam:([0-9]+)\]/', '<'.'?php echo $params_of_teaser["'.$tparams_id.'"][$1]'.'?'.'>', $item); // косячная версия, пока оставил
+ $item = preg_replace_callback(
+ '/\[tparam:([0-9]+)\]/',
+ create_function(
+ '$m',
+ 'return f_params_of_teaser('.$tparams_id.', $m[1]);'
+ ),
+ $item
+ );
}
else
- return false;
+ {
+ // Если чистый запрос тизера, просто вытираем tparam
+ $item = preg_replace('/\[tparam:([0-9]+)\]/', '', $item);
+ }
+
+ // Блок для проверки передачи параметров тизеру
+ /*
+ if (count($params_of_teaser[$tparams_id]))
+ {
+ Debug::_echo($params_of_teaser);
+ Debug::_echo($row_Id_mas);
+ Debug::_echo($item, true);
+ }
+ */
+
+ $item = str_replace('[tag:domain]', getSiteUrl(), $item);
+
+ $link = rewrite_link('index.php?id=' . $row->Id . '&doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
+ $item = str_replace('[tag:link]', $link, $item);
+ $item = str_replace('[tag:docid]', $row->Id, $item);
+ $item = str_replace('[tag:docitemnum]', $req_item_num, $item);
+ $item = str_replace('[tag:adminlink]', 'index.php?do=docs&action=edit&rubric_id=' . $row->rubric_id . '&Id=' . $row->Id . '&cp=' . session_id() . '', $item);
+ $item = str_replace('[tag:doctitle]', stripslashes(htmlspecialchars_decode($row->document_title)), $item);
+ $item = str_replace('[tag:docparent]', $row->document_parent, $item);
+ $item = str_replace('[tag:doclang]', $row->document_lang, $item);
+ $item = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $row->document_published)), $item);
+ $item = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $row->document_published)), $item);
+ $item = str_replace('[tag:humandate]', human_date($row->document_published), $item);
+ $item = preg_replace_callback(
+ '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
+ create_function('$m','return translate_date(date($m[1], '.$row->document_published.'));
+ '),
+ $item
+ );
+
+ if (preg_match('/\[tag:docauthor]/u', $item))
+ {
+ $item = str_replace('[tag:docauthor]', get_username_by_id($row->document_author_id), $item);
+ }
+
+ $item = str_replace('[tag:docauthorid]', $row->document_author_id, $item);
+
+ $item = preg_replace_callback(
+ '/\[tag:docauthoravatar:(\d+)\]/',
+ create_function(
+ '$m',
+ 'return getAvatar('.intval($row->document_author_id).', $m[1]);'
+ ),
+ $item
+ );
+
+ if (isset($use_cache) && $use_cache == 1)
+ {
+ // Кеширование элементов запроса
+ if(! file_exists(dirname($cachefile_docid)))
+ @mkdir(dirname($cachefile_docid), 0777, true);
+
+ file_put_contents($cachefile_docid, $item);
+ }
+ }
+ else
+ {
+ $item = file_get_contents($cachefile_docid);
+ }
+
+ $item = str_replace('[tag:docviews]', $row->document_count_view, $item);
+ $item = str_replace('[tag:doccomments]', isset($row->nums) ? $row->nums : '', $item);
+
+ unset($row);
+
+ return $item;
}
- return $field_value;
-}
-
-function showteaser($id, $tparams = '')
-{
- $item = showrequestelement($id, '', $tparams);
- $item = str_replace('[tag:path]', ABS_PATH, $item);
- $item = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $item);
-
- return $item;
-}
-
-// Функция получения уникальных параметров для каждого тизера
-function f_params_of_teaser($id_param_array,$num)
-{
- global $params_of_teaser;
- return $params_of_teaser[$id_param_array][$num];
-}
-
-// Функция получения элемента запроса
-function showrequestelement($mixed, $template = '', $tparams = '')
-{
- global $AVE_DB, $req_item_num, $params_of_teaser, $use_cache;
-
- if (is_array($mixed))
- $mixed = $mixed[1];
-
- $row = (is_object($mixed) ? $mixed : $AVE_DB->Query("
- SELECT
- a.*
- FROM
- " . PREFIX . "_documents AS a
- WHERE
- a.Id = '" . intval($mixed) . "'
- GROUP BY
- a.Id
- LIMIT 1
- ")->FetchRow());
-
- if(! $row)
- return '';
-
- $tparams_id = '';
-
- if ($tparams != '')
+ /**
+ * Обработка тега запроса.
+ * Возвращает список документов удовлетворяющих параметрам запроса
+ * оформленный с использованием шаблона
+ *
+ * @param int $id идентификатор запроса
+ * @return string
+ */
+ function request_parse($id, $params = array())
{
- $tparams_id = $row->Id.md5($tparams); // Создаем уникальный id для каждого набора параметров
- $params_of_teaser[$tparams_id] = array(); // Для отмены лишних ворнингов
- $tparams = trim($tparams,'[]:'); // Удаляем: слева ':[', справа ']'
- $params_of_teaser[$tparams_id] = explode('|',$tparams); // Заносим параметры в массив уникального id
- }
+ global $AVE_Core, $AVE_DB, $request_documents;
- $template = ($template > '' ? $template : $AVE_DB->Query(
- "SELECT rubric_teaser_template FROM " . PREFIX . "_rubrics WHERE Id='" . intval($row->rubric_id) . "'"
- )->GetCell());
+ // Если id пришёл из тега, берём нужную часть массива
+ if (is_array($id))
+ $id = $id[1];
- $cachefile_docid = BASE_DIR . '/cache/sql/request/' . $row->Id . '/request-' . md5($template) . '.cache';
+ $t = array();
+ $a = array();
+ $v = array();
- if(! file_exists($cachefile_docid))
- {
- $template = preg_replace("/\[tag:if_notempty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(request_get_document_field(\'$1\', '.$row->Id.', \'$2\', '.(int)$row->rubric_id.'), ENT_QUOTES)) != \'\') { '.'?'.'>', $template);
- $template = preg_replace("/\[tag:if_empty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(request_get_document_field(\'$1\', '.$row->Id.', \'$2\', '.(int)$row->rubric_id.'), ENT_QUOTES)) == \'\') { '.'?'.'>', $template);
- $template = str_replace('[tag:if:else]', '', $template);
- $template = str_replace('[tag:/if]', '', $template);
+ // Получаем информацию о запросе
+ $request = request_get_settings($id);
- // Парсим теги визуальных блоков
- $item = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $template);
+ // Фиксируем время начала генерации запроса
+ Debug::startTime('request_' . $id);
- // Парсим теги системных блоков
- $item = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $item);
+ // Массив для полей SELECT
+ $request_select = array();
+ // Массив для присоединения таблиц JOIN
+ $request_join = array();
+ // Массив для добавления условий WHERE
+ $request_where = array();
+ // Массив для сортировки результатов ORDER BY
+ $request_order = array();
+ // Массив для сортировки результатов ORDER BY
+ $request_order_fields = array();
- $item = preg_replace_callback(
- '/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|[0-9-]+)]/',
- create_function(
- '$m',
- 'return request_get_document_field($m[1], ' . $row->Id . ', $m[2], ' . (int)$row->rubric_id . ');'
- ),
- $item
+ $request_order_str = '';
+ $request_select_str = '';
+
+ // Сортировка по полям из переданных параметров
+ if (empty($params['SORT']) && ! empty($_REQUEST['requestsort_' . $id]) && ! is_array($_REQUEST['requestsort_' . $id]))
+ {
+ // Разрешаем перебор полей для сортировки через ";"
+ $sort = explode(';', $_REQUEST['requestsort_' . $id]);
+
+ foreach($sort as $v)
+ {
+ $v1 = explode('=', $v);
+
+ // Если хотим сортировку DESC то пишем alias = 0
+ $params['SORT'][$v1[0]] = (isset($v1[1]) && $v1[1] == 0
+ ? 'DESC'
+ : 'ASC');
+ }
+ }
+
+ // Сортировка по полям
+ // Если пришел параметр SORT
+ if (! empty($params['SORT']) && is_array($params['SORT']))
+ {
+ foreach($params['SORT'] as $fid => $sort)
+ {
+ if (is_numeric($fid))
+ $fid = (int)get_field_num($request->rubric_id, $fid);
+
+ // Если значение больше 0
+ if ((int)$fid > 0)
+ {
+ $sort = strtolower($sort);
+
+ // Добавляем условие в SQL
+ $request_join[$fid] = " if (preg_match('t[]'))?>=(! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
+
+ // Если в сортировке указано ASC иначе DESC
+ $asc_desc = strpos(strtolower($sort),'asc') !== false
+ ? 'ASC'
+ : 'DESC';
+
+ $request_order['field-'.$fid] = "t$fid.field_value " . $asc_desc;
+
+ $request_order_fields[] = $fid;
+ }
+ else
+ {
+ // Если в сортировке указано ASC иначе DESC
+ $asc_desc = strpos(strtolower($sort),'asc') !== false
+ ? 'ASC'
+ : 'DESC';
+
+ $request_order[$param] = "$fid " . $asc_desc;
+ }
+ }
+ }
+ // Сортировка по полю из настроек (только если не передана другая в параметрах)
+ elseif ($request->request_order_by_nat)
+ {
+ $fid = (int)$request->request_order_by_nat;
+
+ // Добавляем с учётом переменной $t из условий, чтобы не выбирать те же таблиы заново - это оптимизирует время
+ $request_join[$fid] = "= (! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
+
+ $request_order['field-' . $fid] = "t$fid.field_value " . $request->request_asc_desc;
+ $request_order_fields[] = $fid;
+ }
+
+ // Вторичная сортировка по параметру документа - добавляем в конец сортировок
+ if (! empty($params['RANDOM']))
+ {
+ $request_order['sort'] = ($params['RANDOM'] == 1)
+ ? 'RAND()'
+ : '';
+ }
+ elseif ($request->request_order_by)
+ {
+ $request_order['sort'] = ($request->request_order_by == 'RAND()')
+ ? 'RAND()'
+ : 'a.' . $request->request_order_by . ' ' . $request->request_asc_desc;
+ }
+
+ // Заменяем field_value на field_number_value во всех полях для сортировки, если поле числовое
+ if (! empty($request_order_fields))
+ {
+ $sql_numeric = $AVE_DB->Query("
+ SELECT
+ Id
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ Id IN (" . implode(',', $request_order_fields) . ")
+ AND
+ rubric_field_numeric = '1'
+ ");
+
+ if ($sql_numeric->_result->num_rows > 0)
+ {
+ while ($fid = (int)$sql_numeric->FetchRow()->Id)
+ $request_order['field-' . $fid] = str_replace('field_value','field_number_value', $request_order['field-' . $fid]);
+ }
+ }
+
+ // Статус: если в параметрах, то его ставим. Иначе выводим только активные доки
+ $request_where[] = "a.document_status = '" . ((isset($params['STATUS']))
+ ? (int)$params['STATUS']
+ : '1') . "'";
+
+ // Не выводить текущий документ
+ if ($request->request_hide_current)
+ $request_where[] = "a.Id != '" . get_current_document_id() . "'";
+
+ // Язык
+ if ($request->request_lang)
+ $request_where[] = "a.document_lang = '" . $_SESSION['user_language'] . "'";
+
+ // Дата публикации документов
+ if (get_settings('use_doctime'))
+ $request_where[] = "a.document_published <= UNIX_TIMESTAMP() AND (a.document_expire = 0 OR a.document_expire >= UNIX_TIMESTAMP())";
+
+ // Условия запроса
+ // если используется выпадающий список, получаем строку без сохранения
+ if (! empty($_POST['req_' . $id]) || ! empty($_SESSION['doc_' . $AVE_Core->curentdoc->Id]['req_' . $id]))
+ $where_cond = request_get_condition_sql_string($request->Id, false);
+ // если условия пустые, получаем строку с сохранением её в бд
+ elseif (! $request->request_where_cond)
+ $where_cond = request_get_condition_sql_string($request->Id, true);
+ // иначе, берём из запроса
+ else
+ $where_cond = unserialize($request->request_where_cond);
+
+ $where_cond['from'] = (isset($where_cond['from']))
+ ? str_replace('%%PREFIX%%', PREFIX, $where_cond['from'])
+ : '';
+
+ if (isset($where_cond['where']))
+ $request_where[] = $where_cond['where'];
+
+ // Родительский документ
+ if (isset($params['PARENT']) && (int)$params['PARENT'] > 0)
+ $request_where[] = "a.document_parent = '" . (int)$params['PARENT'] . "'";
+
+ // Автор
+ // Если задано в параметрах
+ if (isset($params['USER_ID']))
+ $user_id = (int)$params['USER_ID'];
+ // Если стоит галка, показывать только СВОИ документы в настройках
+ // Аноним не увидит ничего, так как 0 юзера нет
+ elseif ($request->request_only_owner == '1')
+ $user_id = (int)$_SESSION['user_id'];
+
+ // Если что-то добавили, пишем
+ if (isset($user_id))
+ $request_where[] = "a.document_author_id = '" . $user_id . "'";
+
+ // Произвольные условия WHERE
+ if (isset($params['USER_WHERE']) && $params['USER_WHERE'] > '')
+ {
+ if (is_array($params['USER_WHERE']))
+ $request_where = array_merge($request_where,$params['USER_WHERE']);
+ else
+ $request_where[] = $params['USER_WHERE'];
+ }
+
+ // Готовим строку с условиями
+ array_unshift($request_where,"
+ a.Id != '1' AND a.Id != '" . PAGE_NOT_FOUND_ID . "' AND
+ a.rubric_id = '" . $request->rubric_id . "' AND
+ a.document_deleted != '1'");
+
+ $request_where_str = '(' . implode(') AND (',$request_where) . ')';
+
+ // Количество выводимых доков
+ $params['LIMIT'] = (! empty($params['LIMIT'])
+ ? $params['LIMIT']
+ : (! empty($_REQUEST['requestlimiter_'.$id])
+ ? $_REQUEST['requestlimiter_'.$id]
+ : (int)$request->request_items_per_page));
+
+ $limit = (isset($params['LIMIT']) && is_numeric($params['LIMIT']) && $params['LIMIT'] > '')
+ ? (int)$params['LIMIT']
+ : (int)$request->request_items_per_page;
+
+ $start = (isset($params['START']))
+ ? (int)$params['START']
+ : (($request->request_show_pagination == 1)
+ ? get_current_page('apage') * $limit - $limit
+ : 0);
+
+ $limit_str = ($limit > 0)
+ ? "LIMIT " . $start . "," . $limit
+ : '';
+
+ // Готовим строку с сортировкой
+ if ($request_order)
+ $request_order_str = "ORDER BY " . implode(', ',$request_order);
+
+ // Готовим строку с полями
+ if ($request_select)
+ $request_select_str = ',' . implode(",\r\n",$request_select);
+
+ unset($a, $t, $v);
+
+ // Составляем запрос к БД
+ $sql = " ?>
+ SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS
+ a.*
+ " . $request_select_str . "
+ FROM
+ " . $where_cond['from'] . "
+ " . (isset($params['USER_FROM']) ? $params['USER_FROM'] : '') . "
+ " . PREFIX . "_documents AS a
+ " . implode(' ', $request_join) . "
+ " . (isset($params['USER_JOIN']) ? $params['USER_FROM'] : '') . "
+ WHERE
+ " . $request_where_str . "
+ GROUP BY a.Id
+ " . $request_order_str . "
+ " . $limit_str . "
+ ";
+
+ $sql_request = eval2var($sql);
+
+ unset($sql);
+
+ // Убираем дубли в выборе полей
+ foreach(array_keys($request_join) AS $key)
+ {
+ $search = PREFIX . '_document_fields AS t' . $key . ',';
+
+ if (preg_match('/' . $search . '/', $sql_request) > 0)
+ {
+ $sql_request = str_replace($search, '', $sql_request);
+ }
+ }
+
+ // Если просили просто показать сформированный запрос
+ if ((isset($params['DEBUG']) && $params['DEBUG'] == 1) || $request->request_show_sql == 1)
+ {
+ $return = Debug::_print($sql_request);
+
+ return $return;
+ }
+
+ // Выполняем запрос к бд
+ $sql = $AVE_DB->Query($sql_request, (int)$request->request_cache_lifetime, 'rub_' . $request->rubric_id);
+
+ // Если просили просто вернуть запрос, возвращаем результат
+ if (isset($params['RETURN_SQL']) && $params['RETURN_SQL'] == 1)
+ return $AVE_DB->GetFoundRows();
+
+ // Если есть вывод пагинации, то выполняем запрос на получение кол-ва элементов
+ if ($request->request_show_pagination == 1 || (isset($params['SHOW']) && $params['SHOW'] == 1))
+ $num_items = $AVE_DB->NumAllRows($sql_request, (int)$request->request_cache_lifetime, 'rub_' . $request->rubric_id);
+ else
+ $num_items = $AVE_DB->GetFoundRows();
+
+ // Если просили просто вернуть кол-во, возвращаем результат
+ if (isset($params['RETURN_COUNT']) && $params['RETURN_COUNT'] == 1)
+ return $num_items;
+
+ unset($sql_request);
+
+ // Приступаем к обработке шаблона
+ $main_template = $request->request_template_main;
+
+ //-- Если кол-во элементов больше 0
+ if ($num_items > 0)
+ {
+ $main_template = preg_replace('/\[tag:if_empty](.*?)\[\/tag:if_empty]/si', '', $main_template);
+ $main_template = str_replace (array('[tag:if_notempty]','[/tag:if_notempty]'), '', $main_template);
+ }
+ else
+ {
+ $main_template = preg_replace('/\[tag:if_notempty](.*?)\[\/tag:if_notempty]/si', '', $main_template);
+ $main_template = str_replace (array('[tag:if_empty]','[/tag:if_empty]'), '', $main_template);
+ }
+
+ $pagination = '';
+
+ // Кол-во страниц
+ $num_pages = ($limit > 0)
+ ? ceil($num_items / $limit)
+ : 0;
+
+ // Собираем пагинацию, еслиесть указание ее выводить
+ if ($request->request_show_pagination == 1 || (isset($params['SHOW']) && $params['SHOW'] == 1))
+ {
+ // Если в запросе пришел номер страницы и он больше, чем кол-во страниц
+ // Делаем перенаправление
+ if (isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage']) && $_REQUEST['apage'] > $num_pages)
+ {
+ $redirect_link = rewrite_link('index.php?id=' . $AVE_Core->curentdoc->Id
+ . '&doc=' . (empty($AVE_Core->curentdoc->document_alias)
+ ? prepare_url($AVE_Core->curentdoc->document_title)
+ : $AVE_Core->curentdoc->document_alias)
+ . ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']))
+ ? '&artpage=' . $_REQUEST['artpage']
+ : '')
+ . ((isset($_REQUEST['page']) && is_numeric($_REQUEST['page']))
+ ? '&page=' . $_REQUEST['page']
+ : ''));
+
+ header('Location:' . $redirect_link);
+ exit;
+ }
+
+ // Запоминаем глобально
+ @$GLOBALS['page_id'][$_REQUEST['id']]['apage'] = (@$GLOBALS['page_id'][$_REQUEST['id']]['apage'] > $num_pages
+ ? @$GLOBALS['page_id'][$_REQUEST['id']]['apage']
+ : $num_pages);
+
+ $pagination = '';
+
+ if ($num_pages > 1)
+ {
+ $queries = '';
+
+ // Добавляем GET-запрос в пагинацию если пришло ADD_GET
+ // или указанов настройках запроса
+ if ($request->request_use_query == 1 || (isset($params['ADD_GET']) && $params['ADD_GET'] == 1))
+ $queries = ($_SERVER['QUERY_STRING'])
+ ? '?' . $_SERVER['QUERY_STRING']
+ : '';
+
+ $pagination = 'index.php?id='
+ . $AVE_Core->curentdoc->Id
+
+ . '&doc=' . (empty($AVE_Core->curentdoc->document_alias)
+ ? prepare_url($AVE_Core->curentdoc->document_title)
+ : $AVE_Core->curentdoc->document_alias)
+
+ . '&apage={s}'
+
+ . ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']))
+ ? '&artpage=' . $_REQUEST['artpage']
+ : '')
+
+ . ((isset($_REQUEST['page']) && is_numeric($_REQUEST['page']))
+ ? '&page=' . $_REQUEST['page']
+ : '')
+
+ // Добавляем GET-запрос в пагинацию
+ . clean_php($queries)
+ ;
+
+ // ID пагинации
+ $pagination_id = (isset($params['PAGINATION']) && $params['PAGINATION'] > 0)
+ ? $params['PAGINATION']
+ : $request->request_pagination;
+
+ // Собираем пагинацию
+ $pagination = AVE_Paginations::getPagination($num_pages, 'apage', $pagination, $pagination_id);
+
+ // Костыли для Главной страницы
+ $pagination = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($pagination)));
+ $pagination = str_ireplace('"//' . URL_SUFF . '"', '"/"', $pagination);
+ }
+ }
+
+ // Элементы запроса
+ $rows = array();
+
+ // id найденных документов
+ $request_documents = array();
+
+ while ($row = $sql->FetchRow())
+ {
+ // Собираем Id документов
+ array_push($request_documents, $row->Id);
+ // Собираем оставшуюся информацию
+ array_push($rows, $row);
+ }
+
+ //-- Обрабатываем шаблоны элементов
+ $items = '';
+ //-- Счетчик
+ $x = 0;
+ //-- Общее число элементов
+ $items_count = count($rows);
+
+ global $req_item_num, $use_cache;
+
+ $use_cache = $request->request_cache_elements;
+
+ $item = '';
+
+ foreach ($rows as $row)
+ {
+ $x++;
+ $last_item = ($x == $items_count ? true : false);
+ $item_num = $x;
+ $req_item_num = $item_num;
+ $item = showrequestelement($row, $request->request_template_item);
+ $item = '<'.'?php $item_num='.var_export($item_num,1).'; $last_item='.var_export($last_item,1).'?'.'>'.$item;
+ $item = 'Id . ';?>' . $item;
+ $item = str_replace('[tag:if_first]', '<'.'?php if(isset($item_num) && $item_num===1) { ?'.'>', $item);
+ $item = str_replace('[tag:if_not_first]', '<'.'?php if(isset($item_num) && $item_num!==1) { ?'.'>', $item);
+ $item = str_replace('[tag:if_last]', '<'.'?php if(isset($last_item) && $last_item) { ?'.'>', $item);
+ $item = str_replace('[tag:if_not_last]', '<'.'?php if(isset($item_num) && !$last_item) { ?'.'>', $item);
+ $item = preg_replace('/\[tag:if_every:([0-9-]+)\]/u', '<'.'?php if(isset($item_num) && !($item_num % $1)){ '.'?'.'>', $item);
+ $item = preg_replace('/\[tag:if_not_every:([0-9-]+)\]/u', '<'.'?php if(isset($item_num) && ($item_num % $1)){ '.'?'.'>', $item);
+ $item = str_replace('[tag:/if]', '<'.'?php } ?>', $item);
+ $item = str_replace('[tag:if_else]', '<'.'?php }else{ ?>', $item);
+ $items .= $item;
+ }
+
+ //== Обрабатываем теги запроса
+
+ //-- Парсим теги визуальных блоков
+ $main_template = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $main_template);
+
+ //-- Парсим теги системных блоков
+ $main_template = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $main_template);
+
+ //-- Заменяем тег пагинации на пагинацию
+ $main_template = str_replace('[tag:pages]', $pagination, $main_template);
+
+ //-- Дата
+ $main_template = preg_replace_callback(
+ '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
+ create_function('$m','return translate_date(date($m[1], '.$AVE_Core->curentdoc->document_published.'));
+ '),
+ $main_template
);
- // Возвращаем поле из БД документа
- $item = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
- function ($match) use ($row)
+ //-- ID Документа
+ $main_template = str_replace('[tag:docid]', $AVE_Core->curentdoc->Id, $main_template);
+ //-- ID Автора
+ $main_template = str_replace('[tag:docauthorid]', $AVE_Core->curentdoc->document_author_id, $main_template);
+
+ //-- Имя автора
+ if (preg_match('[tag:docauthor]', $main_content))
+ $main_content = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_content);
+
+ //-- Время - 1 день назад
+ $main_template = str_replace('[tag:humandate]', human_date($AVE_Core->curentdoc->document_published), $main_template);
+
+ //-- Дата создания
+ $main_template = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
+
+ //-- Время создания
+ $main_template = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
+
+ //-- Домен
+ $main_template = str_replace('[tag:domain]', getSiteUrl(), $main_template);
+
+ //-- Общее число элементов запроса
+ $main_template = str_replace('[tag:doctotal]', $num_items, $main_template);
+ //-- Показано элементов запроса на странице
+ $main_template = str_replace('[tag:doconpage]', $x, $main_template);
+
+ //-- Номер страницы пагинации
+ $main_template = str_replace('[tag:pages:curent]', get_current_page('apage'), $main_template);
+
+ //-- Общее кол-во страниц пагинации
+ $main_template = str_replace('[tag:pages:total]', $num_pages, $main_template);
+
+ //-- Title
+ $main_template = str_replace('[tag:pagetitle]', stripslashes(htmlspecialchars_decode($AVE_Core->curentdoc->document_title)), $main_template);
+
+ //-- Alias
+ $main_template = str_replace('[tag:alias]', (isset($AVE_Core->curentdoc->document_alias) ? $AVE_Core->curentdoc->document_alias : ''), $main_template);
+
+ //-- Возвращаем параметр документа из БД
+ $main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
+ function ($match)
{
return isset($row->{$match[1]})
? $row->{$match[1]}
: null;
},
- $item
+ $main_template
);
- // Если пришел вызов на активацию языковых файлов
- $item = preg_replace_callback(
+ //-- Если пришел вызов на активацию языковых файлов
+ $main_template = preg_replace_callback(
'/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
function ($match)
{
@@ -388,707 +1052,83 @@ function showrequestelement($mixed, $template = '', $tparams = '')
return $AVE_Template->get_config_vars($match[1]);
},
- $item
+ $main_template
);
- $item = str_replace('[tag:path]', ABS_PATH, $item);
- $item = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false)
- ? DEFAULT_THEME_FOLDER
- : THEME_FOLDER)
- . '/', $item);
+ //-- Вставляем элементы запроса
+ $return = str_replace('[tag:content]', $items, $main_template);
- // Watermarks
- $item = preg_replace_callback(
- '/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/',
- create_function(
- '$m',
- 'watermarks($m[1], $m[2], $m[3]);'
- ),
- $item
- );
+ //-- Парсим тег [hide]
+ $return = parse_hide($return);
- // Удаляем ошибочные теги полей документа в шаблоне рубрики
- $item = preg_replace('/\[tag:doc:\d*\]/', '', $item);
- $item = preg_replace('/\[tag:langfile:\d*\]/', '', $item);
+ //-- Абсолютный путь
+ $return = str_replace('[tag:path]', ABS_PATH, $return);
- $item = preg_replace_callback('/\[tag:([r|c|f|t|s]\d+x\d+r*):(.+?)]/', 'callback_make_thumbnail', $item);
+ //-- Путь до папки шаблона
+ $return = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $return);
- if ($tparams != '')
- {
- // Заменяем tparam в тизере
- // $item = preg_replace('/\[tparam:([0-9]+)\]/', '<'.'?php echo $params_of_teaser["'.$tparams_id.'"][$1]'.'?'.'>', $item); // косячная версия, пока оставил
- $item = preg_replace_callback(
- '/\[tparam:([0-9]+)\]/',
- create_function(
- '$m',
- 'return f_params_of_teaser('.$tparams_id.', $m[1]);'
- ),
- $item
- );
- }
- else
- {
- // Если чистый запрос тизера, просто вытираем tparam
- $item = preg_replace('/\[tparam:([0-9]+)\]/', '', $item);
- }
+ //-- Парсим модули
+ $return = $AVE_Core->coreModuleTagParse($return);
- // Блок для проверки передачи параметров тизеру
- /*
- if (count($params_of_teaser[$tparams_id]))
- {
- Debug::echo($params_of_teaser);
- Debug::echo($row_Id_mas);
- Debug::echo($item, true);
- }
- */
+ //-- Фиксируем время генерации запроса
+ $GLOBALS['block_generate']['REQUESTS'][$id][] = Debug::endTime('request_' . $id);
- $item = str_replace('[tag:domain]', getSiteUrl(), $item);
-
- $link = rewrite_link('index.php?id=' . $row->Id . '&doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
- $item = str_replace('[tag:link]', $link, $item);
- $item = str_replace('[tag:docid]', $row->Id, $item);
- $item = str_replace('[tag:docitemnum]', $req_item_num, $item);
- $item = str_replace('[tag:adminlink]', 'index.php?do=docs&action=edit&rubric_id=' . $row->rubric_id . '&Id=' . $row->Id . '&cp=' . session_id() . '', $item);
- $item = str_replace('[tag:doctitle]', stripslashes(htmlspecialchars_decode($row->document_title)), $item);
- $item = str_replace('[tag:docparent]', $row->document_parent, $item);
- $item = str_replace('[tag:doclang]', $row->document_lang, $item);
- $item = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $row->document_published)), $item);
- $item = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $row->document_published)), $item);
- $item = str_replace('[tag:humandate]', human_date($row->document_published), $item);
- $item = preg_replace_callback(
- '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
- create_function('$m','return translate_date(date($m[1], '.$row->document_published.'));
- '),
- $item
- );
-
- if (preg_match('/\[tag:docauthor]/u', $item))
- {
- $item = str_replace('[tag:docauthor]', get_username_by_id($row->document_author_id), $item);
- }
-
- $item = str_replace('[tag:docauthorid]', $row->document_author_id, $item);
-
- $item = preg_replace_callback(
- '/\[tag:docauthoravatar:(\d+)\]/',
- create_function(
- '$m',
- 'return getAvatar('.intval($row->document_author_id).', $m[1]);'
- ),
- $item
- );
-
- if (isset($use_cache) && $use_cache == 1)
- {
- // Кеширование элементов запроса
- if(! file_exists(dirname($cachefile_docid)))
- @mkdir(dirname($cachefile_docid), 0777, true);
-
- file_put_contents($cachefile_docid, $item);
- }
- }
- else
- {
- $item = file_get_contents($cachefile_docid);
- }
-
- $item = str_replace('[tag:docviews]', $row->document_count_view, $item);
- $item = str_replace('[tag:doccomments]', isset($row->nums) ? $row->nums : '', $item);
-
- unset($row);
-
- return $item;
-}
-
-/**
- * Обработка тега запроса.
- * Возвращает список документов удовлетворяющих параметрам запроса
- * оформленный с использованием шаблона
- *
- * @param int $id идентификатор запроса
- * @return string
- */
-function request_parse($id, $params = array())
-{
- global $AVE_Core, $AVE_DB, $request_documents;
-
- // Если id пришёл из тега, берём нужную часть массива
- if (is_array($id))
- $id = $id[1];
-
- $t = array();
- $a = array();
- $v = array();
-
- // Получаем информацию о запросе
- $request = $AVE_DB->Query("
- SELECT
- *
- FROM
- " . PREFIX . "_request
- WHERE
- " . (is_numeric($id) ? 'Id' : 'request_alias') . " = '" . $id . "'
- ")->FetchRow();
-
- // Выходим, если нет запроса
- if (! is_object($request))
- return '';
-
- // Фиксируем время начала генерации запроса
- Debug::startTime('request_' . $id);
-
- // Массив для полей SELECT
- $request_select = array();
- // Массив для присоединения таблиц JOIN
- $request_join = array();
- // Массив для добавления условий WHERE
- $request_where = array();
- // Массив для сортировки результатов ORDER BY
- $request_order = array();
- // Массив для сортировки результатов ORDER BY
- $request_order_fields = array();
-
- $request_order_str = '';
- $request_select_str = '';
-
- // Сортировка по полям из переданных параметров
- if (empty($params['SORT']) && ! empty($_REQUEST['requestsort_' . $id]) && ! is_array($_REQUEST['requestsort_' . $id]))
- {
- // Разрешаем перебор полей для сортировки через ";"
- $sort = explode(';', $_REQUEST['requestsort_'.$id]);
-
- foreach($sort as $v)
- {
- $v1 = explode('=', $v);
- // Если хотим сортировку DESC то пишем alias = 0
- $params['SORT'][$v1[0]] = (isset($v1[1]) && $v1[1] == 0
- ? 'DESC'
- : 'ASC');
- }
- }
-
- // Сортировка по полям
- if (! empty($params['SORT']) && is_array($params['SORT']))
- {
- foreach($params['SORT'] as $fid => $sort)
- {
- if (is_numeric($fid))
- $fid = (int)get_field_num($request->rubric_id, $fid);
-
- if ((int)$fid > 0)
- {
- $sort = strtolower($sort);
-
- $request_join[$fid] = " if (preg_match('t[]'))?>=(! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
-
- $asc_desc = strpos(strtolower($sort),'asc') !== false ? 'ASC' : 'DESC';
-
- $request_order['field-'.$fid] = "t$fid.field_value " . $asc_desc;
-
- $request_order_fields[] = $fid;
- }
- else
- {
- $asc_desc = strpos(strtolower($sort),'asc') !== false ? 'ASC' : 'DESC';
- $request_order[$param] = "$fid " . $asc_desc;
- }
- }
- }
- // Сортировка по полю из настроек (только если не передана другая в параметрах)
- elseif ($request->request_order_by_nat)
- {
- $fid = (int)$request->request_order_by_nat;
-
- // Добавляем с учётом переменной $t из условий, чтобы не выбирать те же таблиы заново - это оптимизирует время
- $request_join[$fid] = "= (! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
-
- $request_order['field-' . $fid] = "t$fid.field_value " . $request->request_asc_desc;
- $request_order_fields[] = $fid;
- }
-
- // Вторичная сортировка по параметру документа - добавляем в конец сортировок
- if (! empty($params['RANDOM']))
- {
- $request_order['sort'] = ($params['RANDOM'] == 1)
- ? 'RAND()'
- : '';
- }
- elseif ($request->request_order_by)
- {
- $request_order['sort'] = ($request->request_order_by == 'RAND()')
- ? 'RAND()'
- : 'a.' . $request->request_order_by . ' ' . $request->request_asc_desc;
- }
-
- // Заменяем field_value на field_number_value во всех полях для сортировки, если поле числовое
- if (! empty($request_order_fields))
- {
- $sql_numeric = $AVE_DB->Query("
- SELECT
- Id
- FROM
- " . PREFIX . "_rubric_fields
- WHERE
- Id IN (" . implode(',', $request_order_fields) . ")
- AND
- rubric_field_numeric = '1'
- ");
-
- if ($sql_numeric->_result->num_rows > 0)
- {
- while ($fid = (int)$sql_numeric->FetchRow()->Id)
- $request_order['field-' . $fid] = str_replace('field_value','field_number_value', $request_order['field-' . $fid]);
- }
- }
-
- // Статус: если в параметрах, то его ставим. иначе выводим только активные доки
- $request_where[] = "a.document_status = '" . ((isset($params['STATUS']))
- ? (int)$params['STATUS']
- : '1') . "'";
-
- // Не выводить текущий документ
- if ($request->request_hide_current)
- $request_where[] = "a.Id != '" . get_current_document_id() . "'";
-
- // Язык
- if ($request->request_lang)
- $request_where[] = "a.document_lang = '" . $_SESSION['user_language'] . "'";
-
- // Дата публикации документов
- if (get_settings('use_doctime'))
- $request_where[] = "a.document_published <= UNIX_TIMESTAMP() AND (a.document_expire = 0 OR a.document_expire >= UNIX_TIMESTAMP())";
-
- // Условия запроса
- // если используется выпадающий список, получаем строку без сохранения
- if (! empty($_POST['req_' . $id]) || !empty($_SESSION['doc_' . $AVE_Core->curentdoc->Id]['req_' . $id]))
- $where_cond = request_get_condition_sql_string($request->Id, false);
- // если условия пустые, получаем строку с сохранением её в бд
- elseif (! $request->request_where_cond)
- $where_cond = request_get_condition_sql_string($request->Id, true);
- // иначе, берём из запроса
- else $where_cond = unserialize($request->request_where_cond);
-
- $where_cond['from'] = (isset($where_cond['from']))
- ? str_replace('%%PREFIX%%', PREFIX, $where_cond['from'])
- : '';
-
- if (isset($where_cond['where'])) $request_where[] = $where_cond['where'];
-
- // Родительский документ
- if (isset($params['PARENT']) && (int)$params['PARENT'] > 0)
- $request_where[] = "a.document_parent = '" . (int)$params['PARENT'] . "'";
-
- // Автор
- // Если задано в параметрах
- if (isset($params['USER_ID']))
- $user_id = (int)$params['USER_ID'];
- // Если стоит галка, показывать только СВОИ документы в настройках
- // Аноним не увидит ничего, так как 0 юзера нет
- elseif ($request->request_only_owner == '1')
- $user_id = (int)$_SESSION['user_id'];
-
- // Если что-то добавили, пишем
- if (isset($user_id))
- $request_where[] = "a.document_author_id = '" . $user_id . "'";
-
- // Произвольные условия WHERE
- if (isset($params['USER_WHERE']) && $params['USER_WHERE'] > '')
- {
- if (is_array($params['USER_WHERE']))
- $request_where = array_merge($request_where,$params['USER_WHERE']);
- else
- $request_where[] = $params['USER_WHERE'];
- }
-
- // Готовим строку с условиями
- array_unshift($request_where,"
- a.Id != '1' AND a.Id != '" . PAGE_NOT_FOUND_ID . "' AND
- a.rubric_id = '" . $request->rubric_id . "' AND
- a.document_deleted != '1'");
-
- $request_where_str = '(' . implode(') AND (',$request_where) . ')';
-
- // Количество выводимых доков
- $params['LIMIT']=(! empty($params['LIMIT'])
- ? $params['LIMIT']
- : (!empty($_REQUEST['requestlimiter_'.$id])
- ? $_REQUEST['requestlimiter_'.$id]
- : (int)$request->request_items_per_page));
-
- $limit = (isset($params['LIMIT']) && is_numeric($params['LIMIT']) && $params['LIMIT'] > '')
- ? (int)$params['LIMIT']
- : (int)$request->request_items_per_page;
-
- $start = (isset($params['START']))
- ? (int)$params['START']
- : (($request->request_show_pagination == 1)
- ? get_current_page('apage') * $limit - $limit
- : 0);
-
- $limit_str = ($limit > 0)
- ? "LIMIT " . $start . "," . $limit
- : '';
-
- // Готовим строку с сортировкой
- if ($request_order)
- $request_order_str = "ORDER BY " . implode(', ',$request_order);
-
- // Готовим строку с полями
- if ($request_select)
- $request_select_str = ',' . implode(",\r\n",$request_select);
-
- unset($a, $t, $v);
-
- // Составляем запрос к БД
- $sql = " ?>
- SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS
- a.Id,
- a.rubric_id,
- a.document_title,
- a.document_parent,
- a.document_alias,
- a.document_published,
- a.document_expire,
- a.document_changed,
- a.document_author_id,
- a.document_in_search,
- a.document_status,
- a.document_count_print,
- a.document_count_view,
- a.document_linked_navi_id,
- a.document_lang
- " . $request_select_str . "
- FROM
- " . $where_cond['from'] . "
- " . (isset($params['USER_FROM']) ? $params['USER_FROM'] : '') . "
- " . PREFIX . "_documents AS a
- " . implode(' ', $request_join) . "
- " . (isset($params['USER_JOIN']) ? $params['USER_FROM'] : '') . "
- WHERE
- " . $request_where_str . "
- GROUP BY a.Id
- " . $request_order_str . "
- " . $limit_str . "
- ";
-
- $sql_request = eval2var($sql);
-
- unset($sql);
-
- // Убираем дубли в выборе полей
- foreach(array_keys($request_join) AS $key)
- {
- $search = PREFIX . '_document_fields AS t' . $key . ',';
-
- if (preg_match('/' . $search . '/', $sql_request) > 0)
- {
- $sql_request = str_replace($search, '', $sql_request);
- }
- }
-
- // Если просили просто показать сформированный запрос
- if ((isset($params['DEBUG']) && $params['DEBUG'] == 1) || $request->request_show_sql == 1)
- {
- $return = Debug::_print($sql_request);
+ // Статистика
+ if ($request->request_show_statistic)
+ $return .= " Найдено: $num_items Показано: $items_count Время генерации: " . Debug::endTime('request_' . $id) . " сек Пиковое значение: ".number_format(memory_get_peak_usage()/1024, 0, ',', ' ') . ' Kb
';
return $return;
}
- // Выполняем запрос к бд
- $sql = $AVE_DB->Query($sql_request, (int)$request->request_cache_lifetime, 'rub_' . $request->rubric_id);
-
- // Если просили просто вернуть запрос, возвращаем результат
- if (isset($params['RETURN_SQL']) && $params['RETURN_SQL'] == 1)
- return $sql;
-
- // Если есть вывод пагинации, то выполняем запрос на получение кол-ва элементов
- if ($request->request_show_pagination == 1 || (isset($params['SHOW']) && $params['SHOW'] == 1))
+ /**
+ * Функция получения содержимого поля для обработки в шаблоне запроса
+ *
+ * Пример использования в шаблоне:
+ *
+ *
+ *
+ *
+ *
+ * @param int $rubric_id идентификатор поля, для [tag:rfld:12][150] $rubric_id = 12
+ * @param int $document_id идентификатор документа к которому принадлежит поле.
+ * @param int $maxlength необязательный параметр, количество возвращаемых символов.
+ * Если данный параметр указать со знаком минус
+ * содержимое поля будет очищено от HTML-тегов.
+ * @return string
+ */
+ function request_get_document_field_value($rubric_id, $document_id, $maxlength = 0)
{
- $num_items = $AVE_DB->NumAllRows($sql_request, (int)$request->request_cache_lifetime, 'rub_' . $request->rubric_id);
- }
- else
+
+ if (! is_numeric($rubric_id) || $rubric_id < 1 || ! is_numeric($document_id) || $document_id < 1) return '';
+
+ $document_fields = get_document_fields($document_id);
+
+ $field_value = isset($document_fields[$rubric_id])
+ ? $document_fields[$rubric_id]['field_value']
+ : '';
+
+ if (! empty($field_value))
{
- $num_items = $AVE_DB->GetFoundRows();
+ $field_value = strip_tags($field_value, '');
+ $field_value = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $field_value);
}
- unset($sql_request);
-
- // Приступаем к обработке шаблона
- $main_template = $request->request_template_main;
-
- //-- Если кол-во элементов больше 0
- if ($num_items > 0)
- {
- $main_template = preg_replace('/\[tag:if_empty](.*?)\[\/tag:if_empty]/si', '', $main_template);
- $main_template = str_replace (array('[tag:if_notempty]','[/tag:if_notempty]'), '', $main_template);
- }
- else
+ if (is_numeric($maxlength) && $maxlength != 0)
{
- $main_template = preg_replace('/\[tag:if_notempty](.*?)\[\/tag:if_notempty]/si', '', $main_template);
- $main_template = str_replace (array('[tag:if_empty]','[/tag:if_empty]'), '', $main_template);
+ if ($maxlength < 0)
+ {
+ $field_value = str_replace(array("\r\n", "\n", "\r"), ' ', $field_value);
+ $field_value = strip_tags($field_value, "");
+ $field_value = preg_replace('/ +/', ' ', $field_value);
+ $maxlength = abs($maxlength);
+ }
+
+ $field_value = mb_substr($field_value, 0, $maxlength) . (strlen($field_value) > $maxlength ? '... ' : '');
}
- $pagination = '';
-
- // Кол-во страниц
- $num_pages = ($limit > 0)
- ? ceil($num_items / $limit)
- : 0;
-
- // Собираем пагинацию, еслиесть указание ее выводить
- if ($request->request_show_pagination == 1 || (isset($params['SHOW']) && $params['SHOW'] == 1))
- {
- // Если в запросе пришел номер страницы и он больше, чем кол-во страниц
- // Делаем перенаправление
- if (isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage']) && $_REQUEST['apage'] > $num_pages)
- {
- $redirect_link = rewrite_link('index.php?id=' . $AVE_Core->curentdoc->Id
- . '&doc=' . (empty($AVE_Core->curentdoc->document_alias)
- ? prepare_url($AVE_Core->curentdoc->document_title)
- : $AVE_Core->curentdoc->document_alias)
- . ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']))
- ? '&artpage=' . $_REQUEST['artpage']
- : '')
- . ((isset($_REQUEST['page']) && is_numeric($_REQUEST['page']))
- ? '&page=' . $_REQUEST['page']
- : ''));
-
- header('Location:' . $redirect_link);
- exit;
- }
-
- // Запоминаем глобально
- @$GLOBALS['page_id'][$_REQUEST['id']]['apage'] = (@$GLOBALS['page_id'][$_REQUEST['id']]['apage'] > $num_pages
- ? @$GLOBALS['page_id'][$_REQUEST['id']]['apage']
- : $num_pages);
-
- $pagination = '';
-
- if ($num_pages > 1)
- {
- $queries = '';
-
- // Добавляем GET-запрос в пагинацию если пришло ADD_GET
- // или указанов настройках запроса
- if ($request->request_use_query == 1 || (isset($params['ADD_GET']) && $params['ADD_GET'] == 1))
- $queries = ($_SERVER['QUERY_STRING'])
- ? '?' . $_SERVER['QUERY_STRING']
- : '';
-
- $pagination = 'index.php?id='
- . $AVE_Core->curentdoc->Id
-
- . '&doc=' . (empty($AVE_Core->curentdoc->document_alias)
- ? prepare_url($AVE_Core->curentdoc->document_title)
- : $AVE_Core->curentdoc->document_alias)
-
- . '&apage={s}'
-
- . ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage']))
- ? '&artpage=' . $_REQUEST['artpage']
- : '')
-
- . ((isset($_REQUEST['page']) && is_numeric($_REQUEST['page']))
- ? '&page=' . $_REQUEST['page']
- : '')
-
- // Добавляем GET-запрос в пагинацию
- . clean_php($queries)
- ;
-
- // ID пагинации
- $pagination_id = (isset($params['PAGINATION']) && $params['PAGINATION'] > 0)
- ? $params['PAGINATION']
- : $request->request_pagination;
-
- // Собираем пагинацию
- $pagination = AVE_Paginations::getPagination($num_pages, 'apage', $pagination, $pagination_id);
-
- // Костыли для Главной страницы
- $pagination = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($pagination)));
- $pagination = str_ireplace('"//' . URL_SUFF . '"', '"/"', $pagination);
- }
+ return $field_value;
}
-
- // Элементы запроса
- $rows = array();
-
- // id найденных документов
- $request_documents = array();
-
- while ($row = $sql->FetchRow())
- {
- // Собираем Id документов
- array_push($request_documents, $row->Id);
- // Собираем оставшуюся информацию
- array_push($rows, $row);
- }
-
- // Обрабатываем шаблоны элементов
- $items = '';
- $x = 0;
- $items_count = count($rows);
-
- global $req_item_num, $use_cache;
-
- $use_cache = $request->request_cache_elements;
-
- $item = '';
-
- foreach ($rows as $row)
- {
- $x++;
- $last_item = ($x == $items_count ? true : false);
- $item_num = $x;
- $req_item_num = $item_num;
- $item = showrequestelement($row, $request->request_template_item);
- $item = '<'.'?php $item_num='.var_export($item_num,1).'; $last_item='.var_export($last_item,1).'?'.'>'.$item;
- $item = 'Id . ';?>' . $item;
- $item = str_replace('[tag:if_first]', '<'.'?php if(isset($item_num) && $item_num===1) { ?'.'>', $item);
- $item = str_replace('[tag:if_not_first]', '<'.'?php if(isset($item_num) && $item_num!==1) { ?'.'>', $item);
- $item = str_replace('[tag:if_last]', '<'.'?php if(isset($last_item) && $last_item) { ?'.'>', $item);
- $item = str_replace('[tag:if_not_last]', '<'.'?php if(isset($item_num) && !$last_item) { ?'.'>', $item);
- $item = preg_replace('/\[tag:if_every:([0-9-]+)\]/u', '<'.'?php if(isset($item_num) && !($item_num % $1)){ '.'?'.'>', $item);
- $item = preg_replace('/\[tag:if_not_every:([0-9-]+)\]/u', '<'.'?php if(isset($item_num) && ($item_num % $1)){ '.'?'.'>', $item);
- $item = str_replace('[tag:/if]', '<'.'?php } ?>', $item);
- $item = str_replace('[tag:if_else]', '<'.'?php }else{ ?>', $item);
- $items .= $item;
- }
-
- // Обрабатываем теги запроса
-
- // Парсим теги визуальных блоков
- $main_template = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $main_template);
-
- // Парсим теги системных блоков
- $main_template = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $main_template);
-
- //-- Заменяем тег пагинации на пагинацию
- $main_template = str_replace('[tag:pages]', $pagination, $main_template);
-
- $main_template = preg_replace_callback(
- '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
- create_function('$m','return translate_date(date($m[1], '.$AVE_Core->curentdoc->document_published.'));
- '),
- $main_template
- );
-
- $main_template = str_replace('[tag:humandate]', human_date($AVE_Core->curentdoc->document_published), $main_template);
- $main_template = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
- $main_template = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), $main_template);
-
- $main_template = str_replace('[tag:domain]', getSiteUrl(), $main_template);
-
- if (preg_match('/\[tag:docauthor]/u', $item))
- {
- $main_template = str_replace('[tag:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_template);
- }
-
- //-- Общее число элементов запроса
- $main_template = str_replace('[tag:doctotal]', $num_items, $main_template);
- //-- Показано элементов запроса на странице
- $main_template = str_replace('[tag:doconpage]', $x, $main_template);
-
- //-- Номер страницы пагинации
- $main_template = str_replace('[tag:pages:curent]', get_current_page('apage'), $main_template);
- //-- Общее кол-во страниц пагинации
- $main_template = str_replace('[tag:pages:total]', $num_pages, $main_template);
-
- $main_template = str_replace('[tag:pagetitle]', stripslashes(htmlspecialchars_decode($AVE_Core->curentdoc->document_title)), $main_template);
- $main_template = str_replace('[tag:alias]', (isset($AVE_Core->curentdoc->document_alias) ? $AVE_Core->curentdoc->document_alias : ''), $main_template);
-
- // Возвращаем параметр документа из БД
- $main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- return isset($row->{$match[1]})
- ? $row->{$match[1]}
- : null;
- },
- $main_template
- );
-
- // Если пришел вызов на активацию языковых файлов
- $main_template = preg_replace_callback(
- '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
- function ($match)
- {
- global $AVE_Template;
-
- return $AVE_Template->get_config_vars($match[1]);
- },
- $main_template
- );
-
- // Вставляем элементы запроса
- $return = str_replace('[tag:content]', $items, $main_template);
-
- // Парсим тег [hide]
- $return = parse_hide($return);
-
- $return = str_replace('[tag:path]', ABS_PATH, $return);
- $return = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $return);
-
- // Парсим модули
- $return = $AVE_Core->coreModuleTagParse($return);
-
- // Фиксируем время генерации запроса
- $GLOBALS['block_generate'][] = array('REQUEST_' . $id => Debug::endTime('request_' . $id));
-
- // Статистика
- if ($request->request_show_statistic)
- $return .= " Найдено: $num_items Показано: $items_count Время генерации: " . Debug::endTime('request_' . $id) . " сек Пиковое значение: ".number_format(memory_get_peak_usage()/1024, 0, ',', ' ') . ' Kb
';
-
- return $return;
-}
-
-/**
- * Функция получения содержимого поля для обработки в шаблоне запроса
- *
- * Пример использования в шаблоне:
- *
- *
- *
- *
- *
- * @param int $rubric_id идентификатор поля, для [tag:rfld:12][150] $rubric_id = 12
- * @param int $document_id идентификатор документа к которому принадлежит поле.
- * @param int $maxlength необязательный параметр, количество возвращаемых символов.
- * Если данный параметр указать со знаком минус
- * содержимое поля будет очищено от HTML-тегов.
- * @return string
- */
-function request_get_document_field_value($rubric_id, $document_id, $maxlength = 0)
-{
-
- if (!is_numeric($rubric_id) || $rubric_id < 1 || !is_numeric($document_id) || $document_id < 1) return '';
-
- $document_fields = get_document_fields($document_id);
-
- $field_value = isset($document_fields[$rubric_id]) ? $document_fields[$rubric_id]['field_value'] : '';
-
- if (!empty($field_value))
- {
- $field_value = strip_tags($field_value, '');
- $field_value = str_replace('[tag:mediapath]', ABS_PATH . 'templates/' . ((defined('THEME_FOLDER') === false) ? DEFAULT_THEME_FOLDER : THEME_FOLDER) . '/', $field_value);
- }
-
- if (is_numeric($maxlength) && $maxlength != 0)
- {
- if ($maxlength < 0)
- {
- $field_value = str_replace(array("\r\n", "\n", "\r"), ' ', $field_value);
- $field_value = strip_tags($field_value, "");
- $field_value = preg_replace('/ +/', ' ', $field_value);
- $maxlength = abs($maxlength);
- }
-
- $field_value = mb_substr($field_value, 0, $maxlength) . (strlen($field_value) > $maxlength ? '... ' : '');
- }
-
- return $field_value;
-}
-?>
+?>
\ No newline at end of file
diff --git a/functions/func.sysblock.php b/functions/func.sysblock.php
index 4ac3495..511d579 100644
--- a/functions/func.sysblock.php
+++ b/functions/func.sysblock.php
@@ -33,6 +33,10 @@ function parse_sysblock($id)
$cache_file = BASE_DIR . '/cache/sql/sysblock/' . $id . '.cache';
+ // Если включен DEV MODE, то отключаем кеширование запросов
+ if (defined('DEV_MODE') AND DEV_MODE)
+ $cache_file = null;
+
if (! file_exists(dirname($cache_file)))
mkdir(dirname($cache_file), 0766, true);
@@ -52,7 +56,8 @@ function parse_sysblock($id)
LIMIT 1
")->GetCell();
- file_put_contents($cache_file,$return);
+ if ($cache_file)
+ file_put_contents($cache_file, $return);
}
//-- парсим теги
@@ -88,7 +93,7 @@ function parse_sysblock($id)
$gen_time = Debug::endTime('SYSBLOCK_' . $id);
- $GLOBALS['block_generate'][] = array('SYSBLOCK_'. $id => $gen_time);
+ $GLOBALS['block_generate']['SYSBLOCK'][$id] = $gen_time;
return $return;
}
diff --git a/inc/config.php b/inc/config.php
index 1f17502..92e301c 100755
--- a/inc/config.php
+++ b/inc/config.php
@@ -11,9 +11,9 @@
* @license GPL v.2
*/
- @define('APP_NAME', 'AVE.CMS');
- @define('APP_VERSION', '3.22');
- @define('APP_INFO', ' Ave-Cms.Ru '.'© 2007-' . date('Y'));
+ @define('APP_NAME', 'AVE.cms');
+ @define('APP_VERSION', '3.24');
+ @define('APP_INFO', 'Ave-Cms.Ru '.'© 2007-' . date('Y'));
$GLOBALS['CMS_CONFIG']['USER_IP'] = array('DESCR' =>'Использовать IP для автологина на сайте','default'=>false,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['REWRITE_MODE'] = array('DESCR' =>'Использовать ЧПУ Адреса вида index.php будут преобразованы в /home/','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
@@ -24,10 +24,8 @@
$themes = array();
foreach (glob(dirname(dirname(__FILE__)) . '/templates/*') as $filename)
- {
if (is_dir($filename))
- $themes[]=basename($filename);
- }
+ $themes[] = basename($filename);
$GLOBALS['CMS_CONFIG']['DEFAULT_THEME_FOLDER'] = array('DESCR' =>'Тема публичной части','default'=>$themes[0],'TYPE'=>'dropdown','VARIANT'=>$themes);
@@ -35,7 +33,7 @@
$GLOBALS['CMS_CONFIG']['CODEMIRROR_THEME'] = array(
'DESCR' => 'Цветовая схема Codemirror',
- 'default' => 'default',
+ 'default' => 'dracula',
'TYPE' => 'dropdown',
'VARIANT' => array(
'default',
@@ -90,6 +88,7 @@
);
$GLOBALS['CMS_CONFIG']['ADMIN_MENU'] = array('DESCR' => 'Использовать плавующее боковое меню','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
+ $GLOBALS['CMS_CONFIG']['ADMIN_MENU_QUICK_ADD'] = array('DESCR' => 'Показывать меню в шапке с действиями','default'=>false,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['ADMIN_CAPTCHA'] = array('DESCR' => 'Использовать капчу при входе в админку','default'=>false,'TYPE'=>'bool','VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['ADMIN_EDITMENU'] = array('DESCR' => 'Использовать всплывающие "Действия" в системе','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
@@ -145,12 +144,16 @@
$GLOBALS['CMS_CONFIG']['OUTPUT_EXPIRE_OFFSET'] = array('DESCR' => 'Время жизни кеширования страницы (60*60 - 1 час)','default'=>60*60, 'TYPE'=>'integer', 'VARIANT'=>'');
$GLOBALS['CMS_CONFIG']['CHECK_VERSION'] = array('DESCR' => 'Проверка наличия новых версий','default'=>true,'TYPE'=>'bool','VARIANT'=>'');
+ // 3.23
+ $GLOBALS['CMS_CONFIG']['REQUEST_ETC'] = array('DESCR' => 'Окончание в полях запроса', 'default'=>'...', 'TYPE'=>'string', 'VARIANT'=>'');
+ $GLOBALS['CMS_CONFIG']['REQUEST_BREAK_WORDS'] = array('DESCR' => 'Разбивать слова при выводе полей в запросе', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>'');
+ $GLOBALS['CMS_CONFIG']['REQUEST_STRIP_TAGS'] = array('DESCR' => 'При - у поля, оставляем теги в результате', 'default'=>'', 'TYPE'=>'string', 'VARIANT'=>'');
+
+ $GLOBALS['CMS_CONFIG']['DEV_MODE'] = array('DESCR' => 'Режим разработчика (Отключено кеширование SQL)', 'default'=>false, 'TYPE'=>'bool', 'VARIANT'=>'');
include_once(dirname(dirname(__FILE__)) . '/inc/config.inc.php');
foreach($GLOBALS['CMS_CONFIG'] as $k => $v)
- {
if(! defined($k))
define($k, $v['default']);
- }
-?>
+?>
\ No newline at end of file
diff --git a/inc/init.php b/inc/init.php
index 888e028..a21121d 100644
--- a/inc/init.php
+++ b/inc/init.php
@@ -359,7 +359,7 @@
lang_status = '1'
ORDER BY
lang_default ASC
- ", SYSTEM_CACHE_LIFETIME);
+ ", SYSTEM_CACHE_LIFETIME, 'langs');
while ($row = $sql->FetchRow())
{
@@ -394,6 +394,14 @@
// Язык системы
set_locale();
+ // Debug
+ require (BASE_DIR . '/class/class.debug.php');
+ $Debug = new Debug;
+
+ // Hooks
+ require (BASE_DIR . '/class/class.hooks.php');
+ $Hooks = new Hooks;
+
// Класс Шаблонов SMARTY
require (BASE_DIR . '/class/class.template.php');
@@ -403,12 +411,4 @@
// Класс Модулей
require (BASE_DIR . '/class/class.modules.php');
$AVE_Module = new AVE_Module;
-
- // Debug
- require (BASE_DIR . '/class/class.debug.php');
- $Debug = new Debug;
-
- // Hooks
- require (BASE_DIR . '/class/class.hooks.php');
- $Hooks = new Hooks;
-?>
+?>
\ No newline at end of file
diff --git a/install/data_base.sql b/install/data_base.sql
index be84a0c..a17a672 100755
--- a/install/data_base.sql
+++ b/install/data_base.sql
@@ -262,7 +262,7 @@ INSERT INTO `%%PRFX%%_rubric_permissions` VALUES
(5, 1, 5, 'docread');#inst#
INSERT INTO `%%PRFX%%_rubrics` VALUES
- (1, 'Основные страницы', '', '0', '[tag:fld:header] [tag:fld:text]', 1, 1, 0, 1, '', '', '', '', '', '', '0', '', '0', '');#inst#
+ (1, 'Основные страницы', '', '0', '[tag:fld:header] [tag:fld:text]', 1, 1, 0, 1, '', '', '', '', '', '', '', '0', '', '0', '');#inst#
INSERT INTO `%%PRFX%%_settings` VALUES
(
diff --git a/install/structure_base.sql b/install/structure_base.sql
index fad24c5..5403617 100755
--- a/install/structure_base.sql
+++ b/install/structure_base.sql
@@ -1,13 +1,14 @@
CREATE TABLE `%%PRFX%%_blocks` (
- `id` mediumint(5) unsigned NOT NULL AUTO_INCREMENT,
- `block_name` varchar(255) NOT NULL,
- `block_description` tinytext NOT NULL,
- `block_alias` varchar(20) NOT NULL,
- `block_text` longtext NOT NULL,
- `block_active` enum('0','1') NOT NULL DEFAULT '1',
- `block_author_id` int(10) unsigned NOT NULL DEFAULT '1',
- `block_created` int(10) unsigned NOT NULL DEFAULT '0',
- PRIMARY KEY (`id`)
+ `id` mediumint(5) unsigned NOT NULL AUTO_INCREMENT,
+ `block_name` varchar(255) NOT NULL,
+ `block_description` tinytext NOT NULL,
+ `block_alias` varchar(20) NOT NULL,
+ `block_text` longtext NOT NULL,
+ `block_active` enum('0','1') NOT NULL DEFAULT '1',
+ `block_author_id` int(10) unsigned NOT NULL DEFAULT '1',
+ `block_created` int(10) unsigned NOT NULL DEFAULT '0',
+ PRIMARY KEY (`id`),
+ KEY `block_alias` (`block_alias`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;#inst#
CREATE TABLE `%%PRFX%%_countries` (
@@ -20,22 +21,22 @@ CREATE TABLE `%%PRFX%%_countries` (
) ENGINE=MyISAM DEFAULT CHARSET=utf8;#inst#
CREATE TABLE `%%PRFX%%_document_fields` (
- `Id` int(10) unsigned NOT NULL auto_increment,
- `rubric_field_id` mediumint(5) unsigned NOT NULL default '0',
- `document_id` int(10) unsigned NOT NULL default '0',
- `field_number_value` decimal(18,4) NOT NULL default '0.0000',
+ `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
+ `rubric_field_id` mediumint(5) unsigned NOT NULL DEFAULT '0',
+ `document_id` int(10) unsigned NOT NULL DEFAULT '0',
+ `field_number_value` decimal(18,4) NOT NULL DEFAULT '0.0000',
`field_value` varchar(500) NOT NULL,
- `document_in_search` enum('1','0') NOT NULL default '1',
- PRIMARY KEY (`Id`),
+ `document_in_search` enum('1','0') NOT NULL DEFAULT '1',
+ PRIMARY KEY (`Id`),
KEY `document_id` (`document_id`),
- KEY `rubric_field_id` (`rubric_field_id`,`document_in_search`),
- KEY `field_value` (`field_value`(333))
+ KEY `field_value` (`field_value`),
+ KEY `rubric_field_id` (`rubric_field_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_document_fields_text` (
- `Id` int(10) unsigned NOT NULL auto_increment,
+ `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`rubric_field_id` mediumint(5) unsigned NOT NULL DEFAULT '0',
- `document_id` int(10) unsigned NOT NULL default '0',
+ `document_id` int(10) unsigned NOT NULL DEFAULT '0',
`field_value` longtext NOT NULL,
PRIMARY KEY (`Id`),
KEY `document_id` (`document_id`),
@@ -61,7 +62,8 @@ CREATE TABLE `%%PRFX%%_document_remarks` (
`remark_published` int(10) unsigned NOT NULL default '0',
`remark_status` enum('1','0') NOT NULL default '1',
`remark_author_email` varchar(255) NOT NULL,
- PRIMARY KEY (`Id`)
+ PRIMARY KEY (`Id`),
+ KEY `document_id` (`document_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_document_rev` (
@@ -70,7 +72,8 @@ CREATE TABLE `%%PRFX%%_document_rev` (
`doc_revision` int(10) unsigned NOT NULL DEFAULT '0',
`doc_data` longtext NOT NULL,
`user_id` int(11) NOT NULL DEFAULT '0',
- PRIMARY KEY (`Id`)
+ PRIMARY KEY (`Id`),
+ KEY `doc_id` (`doc_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_documents` (
@@ -101,7 +104,7 @@ CREATE TABLE `%%PRFX%%_documents` (
`document_tags` text NOT NULL,
`document_lang` varchar(5) NOT NULL,
`document_lang_group` int(10) NOT NULL DEFAULT '0',
- `document_property` text NOT NULL,
+ `document_property` text,
PRIMARY KEY (`Id`),
UNIQUE KEY `document_alias` (`document_alias`),
KEY `rubric_id` (`rubric_id`),
@@ -117,7 +120,8 @@ CREATE TABLE `%%PRFX%%_document_alias_history` (
`document_alias_author` mediumint(5) unsigned NOT NULL DEFAULT '1',
`document_alias_changed` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
- UNIQUE KEY `document_alias` (`document_alias`)
+ UNIQUE KEY `document_alias` (`document_alias`),
+ KEY `document_id` (`document_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_document_tags` (
@@ -179,7 +183,8 @@ CREATE TABLE `%%PRFX%%_navigation` (
`end` text NOT NULL,
`user_group` text NOT NULL,
`expand_ext` enum('0','1','2') DEFAULT '1',
- PRIMARY KEY (`navigation_id`)
+ PRIMARY KEY (`navigation_id`),
+ KEY `alias` (`alias`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_navigation_items` (
@@ -249,6 +254,7 @@ CREATE TABLE `%%PRFX%%_request` (
`request_ajax` enum('0','1') NOT NULL DEFAULT '0',
`request_show_sql` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
+ KEY `rubric_id` (`rubric_id`),
KEY `request_alias` (`request_alias`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
@@ -261,7 +267,8 @@ CREATE TABLE `%%PRFX%%_request_conditions` (
`condition_join` enum('OR','AND') NOT NULL DEFAULT 'AND',
`condition_position` smallint(3) unsigned NOT NULL DEFAULT '1',
`condition_status` enum('0','1') NOT NULL DEFAULT '1',
- PRIMARY KEY (`Id`)
+ PRIMARY KEY (`Id`),
+ KEY `request_id` (`request_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_rubric_fields` (
@@ -271,16 +278,17 @@ CREATE TABLE `%%PRFX%%_rubric_fields` (
`rubric_field_alias` varchar(20) NOT NULL,
`rubric_field_title` varchar(255) NOT NULL,
`rubric_field_type` varchar(75) NOT NULL,
- `rubric_field_numeric` enum('0','1') default '0' NOT NULL,
+ `rubric_field_numeric` enum('0','1') NOT NULL DEFAULT '0',
`rubric_field_position` smallint(3) unsigned NOT NULL DEFAULT '1',
`rubric_field_default` text NOT NULL,
- `rubric_field_search` enum('0','1') default '1' NOT NULL,
+ `rubric_field_search` enum('0','1') NOT NULL DEFAULT '1',
`rubric_field_template` text NOT NULL,
`rubric_field_template_request` text NOT NULL,
`rubric_field_description` text NOT NULL,
PRIMARY KEY (`Id`),
KEY `rubric_id` (`rubric_id`),
- KEY `rubric_field_type` (`rubric_field_type`)
+ KEY `rubric_field_type` (`rubric_field_type`),
+ KEY `rubric_field_alias` (`rubric_field_alias`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_rubric_fields_group` (
@@ -332,6 +340,7 @@ CREATE TABLE `%%PRFX%%_rubrics` (
`rubric_teaser_template` text NOT NULL,
`rubric_admin_teaser_template` text NOT NULL,
`rubric_header_template` text NOT NULL,
+ `rubric_footer_template` text NOT NULL,
`rubric_linked_rubric` varchar(255) NOT NULL DEFAULT '0',
`rubric_description` text NOT NULL,
`rubric_meta_gen` enum('0','1') default '0' NOT NULL,
@@ -420,6 +429,15 @@ CREATE TABLE `%%PRFX%%_settings_lang` (
UNIQUE KEY `lang_key` (`lang_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;#inst#
+CREATE TABLE `%%PRFX%%_settings_menu` (
+ `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
+ `name` varchar(255) DEFAULT NULL,
+ `link` varchar(255) DEFAULT NULL,
+ `position` int(3) DEFAULT NULL,
+ `status` enum('0','1') DEFAULT '1',
+ PRIMARY KEY (`id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;#inst#
+
CREATE TABLE `%%PRFX%%_sysblocks` (
`id` mediumint(5) unsigned NOT NULL AUTO_INCREMENT,
`sysblock_name` varchar(255) NOT NULL,
@@ -499,7 +517,8 @@ CREATE TABLE `%%PRFX%%_users_session` (
`ip` int(32) unsigned NOT NULL,
`agent` varchar(255) NOT NULL,
`last_activ` int(11) NOT NULL DEFAULT '0',
- PRIMARY KEY (`id`)
+ PRIMARY KEY (`id`),
+ KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
CREATE TABLE `%%PRFX%%_view_count` (
@@ -508,4 +527,4 @@ CREATE TABLE `%%PRFX%%_view_count` (
`day_id` int(11) NOT NULL,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`)
-) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
+) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;#inst#
\ No newline at end of file