');
+ $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/inc/query_variants/query_manifest.php b/inc/query_variants/query_manifest.php
new file mode 100644
index 0000000..8df8f17
--- /dev/null
+++ b/inc/query_variants/query_manifest.php
@@ -0,0 +1,33 @@
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/request.php b/inc/query_variants/safe_files/admin/request.php
new file mode 100644
index 0000000..6abf11d
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/request.php
@@ -0,0 +1,102 @@
+rubricPermissionFetch();
+
+$AVE_Template->config_load(BASE_DIR . "/admin/lang/" . $_SESSION['admin_language'] . "/request.txt", 'request');
+
+switch ($_REQUEST['action'])
+{
+ case '':
+ if(check_permission_acp('request'))
+ {
+ $AVE_Request->requestListShow();
+ }
+ break;
+
+ case 'edit':
+ if(check_permission_acp('request_edit'))
+ {
+ $AVE_Rubric->rubricTemplateShow(0, 1);
+ $AVE_Request->requestEdit((int)$_REQUEST['Id']);
+ }
+ break;
+
+ case 'copy':
+ if(check_permission_acp('request'))
+ {
+ $AVE_Request->requestCopy((int)$_REQUEST['Id']);
+ }
+ break;
+
+ case 'new':
+ if(check_permission_acp('request_new'))
+ {
+ $AVE_Rubric->rubricTemplateShow(0, 1);
+ $AVE_Request->requestNew();
+ }
+ break;
+
+ case 'delete_query':
+ if(check_permission_acp('request_del'))
+ {
+ $AVE_Request->requestDelete((int)$_REQUEST['Id']);
+ }
+ break;
+
+ case 'conditions':
+ if(check_permission_acp('request_edit'))
+ {
+ $AVE_Rubric->rubricTemplateShow(0, 1);
+ $AVE_Request->requestConditionEdit((int)$_REQUEST['Id']);
+ }
+ break;
+
+ case 'change':
+ if(check_permission_acp('request_edit'))
+ {
+ switch($_REQUEST['sub'])
+ {
+ case '':
+ $AVE_Rubric->rubricTemplateShow(0, 1);
+ $AVE_Request->conditionFieldChange((int)$_REQUEST['field_id'], (int)$_REQUEST['cond_id']);
+ break;
+
+ case 'save':
+ $AVE_Rubric->rubricTemplateShow(0, 1);
+ $AVE_Request->conditionFieldChangeSave((int)$_REQUEST['field_id'], (int)$_REQUEST['cond_id']);
+ break;
+ }
+ }
+ break;
+
+ case 'alias':
+ if (check_permission_acp('request_edit'))
+ {
+ echo $AVE_Request->requestValidate($_REQUEST['alias'], (int)$_REQUEST['id']);
+ }
+ exit;
+}
+
+?>
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/templates/request/change.tpl b/inc/query_variants/safe_files/admin/templates/request/change.tpl
new file mode 100644
index 0000000..1671bbe
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/change.tpl
@@ -0,0 +1,39 @@
+{if $smarty.request.sub == ''}
+
+
+ {foreach from=$fields_list item=field_group}
+
+ {if $groups_count > 1}
+
+ {/if}
+
+ {foreach from=$field_group.fields item=field}
+ {$field.rubric_field_title|escape} (ID: {$field.Id|escape})
+ {/foreach}
+
+ {if $groups_count > 1}
+
+ {/if}
+
+ {/foreach}
+
+
+
+
+
+{else}
+ {foreach from=$fields_list item=field_group}
+
+ {foreach from=$field_group.fields item=field}
+ {if $field_id == $field.Id}
+
+ {/if}
+ {/foreach}
+
+ {/foreach}
+{/if}
diff --git a/inc/query_variants/safe_files/admin/templates/request/cond_list.tpl b/inc/query_variants/safe_files/admin/templates/request/cond_list.tpl
new file mode 100644
index 0000000..f7ff5c3
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/cond_list.tpl
@@ -0,0 +1,112 @@
+
+
+
+ {if $conditions}
+
+ {/if}
+
+
+ {if $conditions}
+
+ {/if}
diff --git a/inc/query_variants/safe_files/admin/templates/request/conditions.tpl b/inc/query_variants/safe_files/admin/templates/request/conditions.tpl
new file mode 100644
index 0000000..cab902b
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/conditions.tpl
@@ -0,0 +1,391 @@
+
+
+
+
{#REQUEST_CONDITIONS#}
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/templates/request/form.tpl b/inc/query_variants/safe_files/admin/templates/request/form.tpl
new file mode 100644
index 0000000..8ad869c
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/form.tpl
@@ -0,0 +1,779 @@
+
+
+{if $smarty.request.action=='edit'}
+
+
+{else}
+
+
{#REQUEST_NEW#}
+
+
+{/if}
+
+
+
+
+ {#MAIN_PAGE#}
+ {#REQUEST_ALL#}
+ {if $smarty.request.action=='edit'}
+ {#REQUEST_EDIT2#}
+ {else}
+ {#REQUEST_NEW#}
+ {/if}
+ {$smarty.request.request_title_new|stripslashes|default:$row->request_title|escape}
+
+
+
+
+{if $errors}
+
+ {foreach from=$errors item=e}
+
+ {assign var=message value=$e}
+ • {$message}
+
+ {/foreach}
+
+{/if}
+
+{if !check_permission('request_php')}
+
+
+ {#REQUEST_REPORT_ERR_PHP#}
+
+
+{/if}
+
+{if $smarty.request.Id == ''}
+ {assign var=iframe value='no'}
+{/if}
+
+{if $smarty.request.action == 'new' && $smarty.request.rubric_id == ''}
+ {assign var=dis value='disabled'}
+{/if}
+
+{if $smarty.request.action=='new' && $smarty.request.rubric_id==''}
+
+
+ {#REQUEST_PLEASE_SELECT#}
+
+
+{/if}
+
+
+
+
+{include file="$codemirror_connect"}
+{include file="$codemirror_editor" conn_id="" textarea_id='request_template_main' ctrls='$("#RequestTpl").ajaxSubmit(sett_options);' height=480}
+{include file="$codemirror_editor" conn_id="2" textarea_id='request_template_item' ctrls='$("#RequestTpl").ajaxSubmit(sett_options);' height=440}
+
+
+{literal}
+
+{/literal}
+
+{if $smarty.request.action !='new' && $smarty.request.rubric_id !=''}
+
+{/if}
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/templates/request/list.tpl b/inc/query_variants/safe_files/admin/templates/request/list.tpl
new file mode 100644
index 0000000..3a614f1
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/list.tpl
@@ -0,0 +1 @@
+for original
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/templates/request/nav.tpl b/inc/query_variants/safe_files/admin/templates/request/nav.tpl
new file mode 100644
index 0000000..7754227
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/nav.tpl
@@ -0,0 +1 @@
+{#MAIN_QUERIES#}
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/admin/templates/request/request.tpl b/inc/query_variants/safe_files/admin/templates/request/request.tpl
new file mode 100644
index 0000000..e3ef687
--- /dev/null
+++ b/inc/query_variants/safe_files/admin/templates/request/request.tpl
@@ -0,0 +1,297 @@
+
+
+
{#REQUEST_TITLE#}
+
+
+
+
+
+
+{literal}
+
+{/literal} {if $page_nav}
+
+{/if}
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/class/class.request.php b/inc/query_variants/safe_files/class/class.request.php
new file mode 100644
index 0000000..2446a4a
--- /dev/null
+++ b/inc/query_variants/safe_files/class/class.request.php
@@ -0,0 +1,962 @@
+_limit;
+ $start = get_current_page() * $limit - $limit;
+
+ // Получаем общее количество запросов
+ $num = $AVE_DB->Query("SELECT COUNT(*) FROM " . PREFIX . "_request")->GetCell();
+
+ // Если количество больше, чем установленный лимит, тогда формируем постраничную навигацию
+ if ($num > $limit)
+ {
+ $page_nav = " {t} ";
+ $page_nav = get_pagination(ceil($num / $limit), 'page', $page_nav);
+ $AVE_Template->assign('page_nav', $page_nav);
+ }
+
+ $limit = $pagination ? "LIMIT " . $start . "," . $limit : '';
+ }
+
+ // Выполняем запрос к БД на получение списка запросов с учетом лимита вывода на страницу (если необходимо)
+ $items = array();
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM " . PREFIX . "_request
+ ORDER BY Id ASC
+ " . $limit . "
+ ");
+
+ // Формируем массив из полученных данных
+ while ($row = $sql->FetchRow())
+ {
+ $row->request_author = get_username_by_id($row->request_author_id);
+ array_push($items, $row);
+ }
+
+ // Возвращаем массив
+ return $items;
+ }
+
+ /**
+ * Получить наименование и описание Запроса по идентификатору
+ *
+ * @param int $request_id идентификатор Запроса
+ * @return object наименование Запроса
+ */
+ function get_request_by_id($request_id = 0)
+ {
+ global $AVE_DB;
+
+ static $requests = array();
+
+ if (! isset($requests[$request_id]))
+ {
+ $requests[$request_id] = $AVE_DB->Query("
+ SELECT
+ rubric_id,
+ request_title,
+ request_description
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ Id = '" . $request_id . "'
+ LIMIT 1
+ ")->FetchRow();
+ }
+
+ return $requests[$request_id];
+ }
+
+ /**
+ * Проверка алиаса тега на валидность и уникальность
+ *
+ * @param string $alias
+ * @param int $id
+ *
+ * @return bool|string
+ */
+ function requestValidate ($alias = '', $id = 0)
+ {
+ global $AVE_DB;
+
+ //-- Соответствие требованиям
+ if (empty ($alias) || preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $alias) !== 1 || is_numeric($alias))
+ return 'syn';
+
+ //-- Уникальность
+ return !(bool)$AVE_DB->Query("
+ SELECT 1
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ request_alias = '" . $alias . "'
+ AND
+ Id != '" . $id . "'
+ ")->GetCell();
+ }
+
+
+/**
+ * Внешние методы класса
+ */
+
+ /**
+ * Метод, предназначенный для формирования списка Запросов
+ *
+ */
+ function requestListFetch()
+ {
+ global $AVE_Template;
+
+ $AVE_Template->assign('conditions', $this->_requestListGet(false));
+ }
+
+ /**
+ * Метод, предназначенный для отображения списка Запросов
+ *
+ */
+ function requestListShow()
+ {
+ global $AVE_Template;
+
+ // Получаем список запросов
+ $AVE_Template->assign('items', $this->_requestListGet());
+
+ // Передаем в шаблон и отображаем страницу со списком
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/request.tpl'));
+ }
+
+ /**
+ * Метод, предназначенный для создания нового Запроса
+ *
+ */
+ function requestNew()
+ {
+ global $AVE_DB, $AVE_Template;
+
+ // Определяем действие пользователя
+ switch ($_REQUEST['sub'])
+ {
+ // Действие не определено
+ case '':
+ $AVE_Template->assign('rid', 0);
+ // Отображаем пустую форму для создания нового запроса
+ $AVE_Template->assign('formaction', 'index.php?do=request&action=new&sub=save&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/form.tpl'));
+ break;
+
+ // Нажата кнопка Сохранить запрос
+ case 'save':
+ $save = true;
+ $errors = array();
+
+ $row = new stdClass();
+
+ $row->request_template_item = stripslashes(pretty_chars($_REQUEST['request_template_item']));
+ $row->request_template_main = stripslashes(pretty_chars($_REQUEST['request_template_main']));
+ $row->request_title = stripslashes($_REQUEST['request_title']);
+ $row->rubric_id = stripslashes($_REQUEST['rubric_id']);
+ $row->request_items_per_page = stripslashes($_REQUEST['request_items_per_page']);
+ $row->request_order_by = stripslashes($_REQUEST['request_order_by']);
+ $row->request_order_by_nat = stripslashes($_REQUEST['request_order_by_nat']);
+ $row->request_asc_desc = stripslashes($_REQUEST['request_asc_desc']);
+ $row->request_description = stripslashes($_REQUEST['request_description']);
+ $row->request_show_pagination = (isset($_REQUEST['request_show_pagination']) ? (int)($_REQUEST['request_show_pagination']) : 0);
+ $row->request_pagination = (isset($_REQUEST['request_pagination']) ? (int)($_REQUEST['request_pagination']) : 1);
+ $row->request_external = (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0);
+ $row->request_ajax = (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0);
+ $row->request_only_owner = (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0);
+ $row->request_hide_current = (isset($_REQUEST['request_hide_current']) ? (int)($_REQUEST['request_hide_current']) : 0);
+ $row->request_use_query = (isset($_REQUEST['request_use_query']) ? $_REQUEST['request_use_query'] : 0);
+ $row->request_count_items = (isset($_REQUEST['request_count_items']) ? $_REQUEST['request_count_items'] : 0);
+ $row->request_lang = (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0);
+ $row->request_show_statistic = (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0);
+ $row->request_show_sql = (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0);
+ $row->request_cache_elements = (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0);
+ $row->request_cache_lifetime = (int)($_REQUEST['request_cache_lifetime']);
+
+
+
+ if (empty($_REQUEST['rubric_id']))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_RUBRIC');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_RUBRIC');
+ }
+
+ if (empty($_REQUEST['request_title']))
+ {
+ $save = false;
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TITLE');
+ }
+
+ if (empty($_REQUEST['request_template_main']))
+ {
+ $save = false;
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TEXT');
+ }
+
+ $check_code_template_item = strtolower($_REQUEST['request_template_item']);
+ $check_code_template_main = strtolower($_REQUEST['request_template_main']);
+
+ if ((is_php_code($check_code_template_item) || is_php_code($check_code_template_main)) && !check_permission('request_php'))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP');
+ reportLog($AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP_N') . ' (' . stripslashes(htmlspecialchars($_REQUEST['request_title'], ENT_QUOTES)) . ')');
+ }
+
+ if ($save === false)
+ {
+ $AVE_Template->assign('row', $row);
+ $AVE_Template->assign('errors', $errors);
+ $AVE_Template->assign('formaction', 'index.php?do=request&action=new&sub=save&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/form.tpl'));
+ }
+ else
+ {
+ $sql = "
+ INSERT " . PREFIX . "_request
+ SET
+ rubric_id = '" . (int)$_REQUEST['rubric_id'] . "',
+ request_alias = '" . (isset($_REQUEST['request_alias']) ? stripslashes($_REQUEST['request_alias']) : '') . "',
+ request_title = '" . (isset($_REQUEST['request_title']) ? stripslashes($_REQUEST['request_title']) : '') . "',
+ request_items_per_page = '" . (isset($_REQUEST['request_items_per_page']) ? stripslashes($_REQUEST['request_items_per_page']) : 0) . "',
+ request_template_item = '" . (isset($_REQUEST['request_template_item']) ? stripslashes(pretty_chars($_REQUEST['request_template_item'])) : '') . "',
+ request_template_main = '" . (isset($_REQUEST['request_template_main']) ? stripslashes(pretty_chars($_REQUEST['request_template_main'])) : '') . "',
+ request_order_by = '" . (isset($_REQUEST['request_order_by']) ? stripslashes($_REQUEST['request_order_by']) : '') . "',
+ request_order_by_nat = '" . (isset($_REQUEST['request_order_by_nat']) ? (int)trim($_REQUEST['request_order_by_nat']) : 0) . "',
+ request_description = '" . (isset($_REQUEST['request_description']) ? stripslashes($_REQUEST['request_description']) : '') . "',
+ request_author_id = '" . (int)$_SESSION['user_id'] . "',
+ request_created = '" . time() . "',
+ request_asc_desc = '" . (isset($_REQUEST['request_asc_desc']) ? stripslashes($_REQUEST['request_asc_desc']) : 'DESC') . "',
+ request_show_pagination = '" . (isset($_REQUEST['request_show_pagination']) ? (int)$_REQUEST['request_show_pagination'] : 0) . "',
+ request_pagination = '" . (isset($_REQUEST['request_pagination']) ? (int)$_REQUEST['request_pagination'] : 1) . "',
+ request_external = '" . (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0). "',
+ request_ajax = '" . (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0). "',
+ request_hide_current = '" . (isset($_REQUEST['request_hide_current']) ? (int)($_REQUEST['request_hide_current']) : 0) . "',
+ request_only_owner = '" . (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0) . "',
+ request_use_query = '" . (isset($_REQUEST['request_use_query']) ? (int)$_REQUEST['request_use_query'] : 0) . "',
+ request_count_items = '" . (isset($_REQUEST['request_count_items']) ? (int)$_REQUEST['request_count_items'] : 0) . "',
+ request_lang = '" . (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0). "',
+ request_show_statistic = '" . (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0). "',
+ request_show_sql = '" . (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0). "',
+ request_cache_elements = '" . (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0). "',
+ request_cache_lifetime = '" . (isset($_REQUEST['request_cache_lifetime']) ? (int)($_REQUEST['request_cache_lifetime']) : 0) . "',
+ request_changed = '" . time() . "',
+ request_changed_elements = '" . time() . "'
+ ";
+
+ // Выполняем запрос к БД и сохраняем введенную пользователем информацию
+ $AVE_DB->Query($sql);
+
+ // Получаем id последней записи
+ $iid = $AVE_DB->InsertId();
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('REQUEST_ADD_NEW_SUC') . ' (' . stripslashes(htmlspecialchars($_REQUEST['request_title'], ENT_QUOTES)) . ') (' . $iid . ')');
+
+ // Если в запросе пришел параметр на продолжение редактирования запроса
+ if ($_REQUEST['reedit'] == 1)
+ {
+ // Выполняем переход на страницу с редактированием запроса
+ header('Location:index.php?do=request&action=edit&Id=' . $iid . '&rubric_id=' . $_REQUEST['rubric_id'] . '&cp=' . SESSION);
+ }
+ else
+ {
+ // В противном случае выполняем переход к списку запросов
+ if (!$_REQUEST['next_edit'])
+ header('Location:index.php?do=request&cp=' . SESSION);
+ else
+ header('Location:index.php?do=request&action=edit&Id=' . $iid . '&rubric_id='.$_REQUEST['rubric_id'].'&cp=' . SESSION);
+ }
+
+ exit;
+ }
+ }
+ }
+
+ /**
+ * Метод, предназначенный для редактирования Запроса
+ *
+ * @param int $request_id идентификатор запроса
+ */
+ function requestEdit($request_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ // Определяем действие пользователя
+ switch ($_REQUEST['sub'])
+ {
+ // Если действие не определено
+ case '':
+ // Выполняем запрос к БД и получаем всю информацию о запросе
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ Id = '" . $request_id . "'
+ OR
+ request_alias = '" . $request_id . "'
+ ");
+
+ if ($sql->_result->num_rows == 0)
+ {
+ header('Location:index.php?do=request&cp=' . SESSION);
+ exit;
+ }
+
+ $row = $sql->FetchRow();
+
+ // Получаем постраничную навигацию
+ $sql = $AVE_DB->Query("
+ SELECT
+ id,
+ pagination_name
+ FROM
+ " . PREFIX . "_paginations
+ ");
+
+ $paginations = array();
+
+ while ($pages = $sql->FetchRow())
+ array_push($paginations, $pages);
+
+ // Передаем данные в шаблон и отображаем страницу с редактированием запроса
+ if (! isset($_REQUEST['rubric_id']))
+ $_REQUEST['rubric_id'] = $row->rubric_id;
+
+ $AVE_Template->assign('row', $row);
+ $AVE_Template->assign('rid', $row->Id);
+ $AVE_Template->assign('paginations', $paginations);
+ $AVE_Template->assign('formaction', 'index.php?do=request&action=edit&sub=save&Id=' . $row->Id . '&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/form.tpl'));
+
+ break;
+
+ // Пользователь нажал кнопку Сохранить изменения
+ case 'save':
+
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ Id = '" . $request_id . "'
+ ");
+
+ if ($sql->_result->num_rows == 0)
+ {
+ header('Location:index.php?do=request&cp=' . SESSION);
+ exit;
+ }
+
+ $save = true;
+ $errors = array();
+ $row = new stdClass();
+ $row->request_template_item = (isset($_REQUEST['request_template_item']) ? stripslashes(pretty_chars($_REQUEST['request_template_item'])) : '');
+ $row->request_template_main = (isset($_REQUEST['request_template_main']) ? stripslashes(pretty_chars($_REQUEST['request_template_main'])) : '');
+ $row->request_title = (isset($_REQUEST['request_title']) ? stripslashes($_REQUEST['request_title']) : '');
+ $row->rubric_id = (isset($_REQUEST['rubric_id']) ? stripslashes($_REQUEST['rubric_id']) : 0);
+ $row->request_items_per_page = (isset($_REQUEST['request_items_per_page']) ? stripslashes($_REQUEST['request_items_per_page']) : 0);
+ $row->request_order_by = (isset($_REQUEST['request_order_by']) ? stripslashes($_REQUEST['request_order_by']) : '');
+ $row->request_order_by_nat = (isset($_REQUEST['request_order_by_nat']) ? (int)trim($_REQUEST['request_order_by_nat']) : 0);
+ $row->request_asc_desc = (isset($_REQUEST['request_asc_desc']) ? stripslashes($_REQUEST['request_asc_desc']) : 'DESC');
+ $row->request_description = (isset($_REQUEST['request_description']) ? stripslashes($_REQUEST['request_description']) : '');
+ $row->request_show_pagination = (isset($_REQUEST['request_show_pagination']) ? $_REQUEST['request_show_pagination'] : 0);
+ $row->request_pagination = (isset($_REQUEST['request_pagination']) ? (int)($_REQUEST['request_pagination']) : 1);
+ $row->request_external = (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0);
+ $row->request_ajax = (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0);
+ $row->request_only_owner = (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0);
+ $row->request_hide_current = (isset($_REQUEST['request_hide_current']) ? (int)($_REQUEST['request_hide_current']) : 0);
+ $row->request_use_query = (isset($_REQUEST['request_use_query']) ? $_REQUEST['request_use_query'] : 0);
+ $row->request_count_items = (isset($_REQUEST['request_count_items']) ? $_REQUEST['request_count_items'] : 0);
+ $row->request_lang = (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0);
+ $row->request_show_statistic = (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0);
+ $row->request_show_sql = (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0);
+ $row->request_cache_elements = (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0);
+ $row->request_cache_lifetime = (int)($_REQUEST['request_cache_lifetime']);
+
+ $message = '';
+
+ if (empty($_REQUEST['rubric_id']))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_RUBRIC');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_RUBRIC');
+ }
+
+ if (empty($_REQUEST['request_title']))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TITLE');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TITLE');
+ }
+
+ if (empty($_REQUEST['request_template_main']))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TEXT');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_TEXT');
+ }
+
+ $check_code_template_item = strtolower($_REQUEST['request_template_item']);
+ $check_code_template_main = strtolower($_REQUEST['request_template_main']);
+
+ if ((is_php_code($check_code_template_item) || is_php_code($check_code_template_main)) && !check_permission('request_php'))
+ {
+ $save = false;
+ $message = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP');
+ $errors[] = $AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP');
+ reportLog($AVE_Template->get_config_vars('REQUEST_REPORT_ERR_PHP_E') . ' (' . stripslashes(htmlspecialchars($_REQUEST['request_title'], ENT_QUOTES)) . ') (Id:' . $request_id . ')');
+ }
+
+ if ($save === false)
+ {
+ if (isAjax())
+ {
+ $header = $AVE_Template->get_config_vars('REQUEST_ERROR');
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => 'error'));
+ exit;
+ }
+
+ $AVE_Template->assign('row', $row);
+ $AVE_Template->assign('errors', $errors);
+ $AVE_Template->assign('formaction', 'index.php?do=request&action=edit&sub=save&Id=' . $request_id . '&cp=' . SESSION);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/form.tpl'));
+ }
+ else
+ {
+ // Выполняем запрос к БД и обновляем имеющиеся данные
+ $sql = "
+ UPDATE " . PREFIX . "_request
+ SET
+ rubric_id = '" . (int)$_REQUEST['rubric_id'] . "',
+ request_alias = '" . (isset($_REQUEST['request_alias']) ? $_REQUEST['request_alias'] : '') . "',
+ request_title = '" . (isset($_REQUEST['request_title']) ? $_REQUEST['request_title'] : '') . "',
+ request_items_per_page = '" . (isset($_REQUEST['request_items_per_page']) ? $_REQUEST['request_items_per_page'] : 0) . "',
+ request_template_item = '" . (isset($_REQUEST['request_template_item']) ? $_REQUEST['request_template_item'] : '') . "',
+ request_template_main = '" . (isset($_REQUEST['request_template_main']) ? $_REQUEST['request_template_main'] : '') . "',
+ request_order_by = '" . (isset($_REQUEST['request_order_by']) ? $_REQUEST['request_order_by'] : '') . "',
+ request_order_by_nat = '" . (isset($_REQUEST['request_order_by_nat']) ? (int)trim($_REQUEST['request_order_by_nat']) : 0) . "',
+ request_description = '" . (isset($_REQUEST['request_description']) ? $_REQUEST['request_description'] : '') . "',
+ request_asc_desc = '" . (isset($_REQUEST['request_asc_desc']) ? $_REQUEST['request_asc_desc'] : 'DESC') . "',
+ request_show_pagination = '" . (isset($_REQUEST['request_show_pagination']) ? (int)$_REQUEST['request_show_pagination'] : 0) . "',
+ request_pagination = '" . (isset($_REQUEST['request_pagination']) ? (int)$_REQUEST['request_pagination'] : 1) . "',
+ request_external = '" . (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0). "',
+ request_ajax = '" . (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0). "',
+ request_hide_current = '" . (isset($_REQUEST['request_hide_current']) ? (int)($_REQUEST['request_hide_current']) : 0) . "',
+ request_only_owner = '" . (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0) . "',
+ request_use_query = '" . (isset($_REQUEST['request_use_query']) ? (int)$_REQUEST['request_use_query'] : 0) . "',
+ request_count_items = '" . (isset($_REQUEST['request_count_items']) ? (int)$_REQUEST['request_count_items'] : 0) . "',
+ request_lang = '" . (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0). "',
+ request_show_statistic = '" . (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0). "',
+ request_show_sql = '" . (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0). "',
+ request_cache_elements = '" . (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0). "',
+ request_cache_lifetime = '" . (isset($_REQUEST['request_cache_lifetime']) ? (int)($_REQUEST['request_cache_lifetime']) : 0) . "',
+ request_changed = '" . time() . "',
+ request_changed_elements = '" . time() . "'
+
+ WHERE
+ Id = '" . $request_id . "'
+ ";
+
+ $AVE_DB->Query($sql);
+
+ $AVE_DB->clearRequest($request_id);
+
+ // ToDO Сделать проверку на сохранение
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($AVE_Template->get_config_vars('REQUEST_SAVE_CHA_SUC') . ' (' . stripslashes(htmlspecialchars($_REQUEST['request_title'], ENT_QUOTES)) . ') (Id:' . $request_id . ')');
+
+ // В противном случае выполняем переход к списку запросов
+ if (! isAjax())
+ {
+ header('Location:index.php?do=request&cp=' . SESSION);
+ exit;
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_TEMPLATE_SAVED');
+ $header = $AVE_Template->get_config_vars('REQUEST_SUCCESS');
+ $theme = 'accept';
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+ }
+ break;
+ }
+ }
+
+ /**
+ * Метод, предназначенный для создания копии Запроса
+ *
+ * @param int $request_id идентификатор запроса
+ */
+ function requestCopy($request_id)
+ {
+ global $AVE_DB;
+
+ // Выполняем запрос к БД на получение информации о копиреумом запросе
+ $row = $AVE_DB->Query("
+ SELECT *
+ FROM " . PREFIX . "_request
+ WHERE Id = '" . $request_id . "'
+ ")->FetchRow();
+
+ // Выполняем запрос к БД на добавление нового запроса на основании полученных ранее данных
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_request
+ SET
+ rubric_id = '" . $row->rubric_id . "',
+ request_items_per_page = '" . $row->request_items_per_page . "',
+ request_title = '" . substr($_REQUEST['cname'], 0, 25) . "',
+ request_template_item = '" . addslashes($row->request_template_item) . "',
+ request_template_main = '" . addslashes($row->request_template_main) . "',
+ request_order_by = '" . addslashes($row->request_order_by) . "',
+ request_order_by_nat = '" . addslashes($row->request_order_by_nat) . "',
+ request_author_id = '" . (int)$_SESSION['user_id'] . "',
+ request_created = '" . time() . "',
+ request_description = '" . addslashes($row->request_description) . "',
+ request_asc_desc = '" . $row->request_asc_desc . "',
+ request_show_pagination = '" . $row->request_show_pagination . "',
+ request_pagination = '" . $row->request_pagination . "',
+ request_hide_current = '" . $row->request_hide_current . "',
+ request_only_owner = '" . $row->request_only_owner . "',
+ request_use_query = '" . $row->request_use_query . "',
+ request_count_items = '" . $row->request_count_items . "',
+ request_lang = '" . $row->request_lang . "',
+ request_show_statistic = '" . $row->request_show_statistic . "',
+ request_show_sql = '" . $row->request_show_sql . "',
+ request_cache_elements = '" . (isset($row->request_cache_elements) ? $row->request_cache_elements : 0) . "'
+ ");
+
+ // Получаем id добавленной записи
+ $iid = $AVE_DB->InsertId();
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($_SESSION['user_name'] . ' - создал копию запроса (' . $request_id . ')', 2, 2);
+
+ // Выполняем запрос к БД и получаем все условия запроса для копируемого запроса
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM " . PREFIX . "_request_conditions
+ WHERE request_id = '" . $request_id . "'
+ ");
+
+ // Обрабатываем полученные данные и
+ while ($row_ak = $sql->FetchRow())
+ {
+ // Выполняем запрос к БД на добавление условий для нового, скопированного запроса
+ $AVE_DB->Query("
+ INSERT " . PREFIX . "_request_conditions
+ SET
+ request_id = '" . $iid . "',
+ condition_compare = '" . $row_ak->condition_compare . "',
+ condition_field_id = '" . $row_ak->condition_field_id . "',
+ condition_value = '" . $row_ak->condition_value . "',
+ condition_join = '" . $row_ak->condition_join . "'
+ ");
+ }
+
+ // Выполянем переход к списку запросов
+ header('Location:index.php?do=request&cp=' . SESSION);
+ exit;
+ }
+
+ /**
+ * Метод, предназначенный для удаления запроса
+ *
+ * @param int $request_id идентификатор запроса
+ */
+ function requestDelete($request_id)
+ {
+ global $AVE_DB;
+
+ // Выполняем запрос к БД на удаление общей информации о запросе
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_request
+ WHERE Id = '" . $request_id . "'
+ ");
+
+ // Выполняем запрос к БД на удаление условий запроса
+ $AVE_DB->Query("
+ DELETE
+ FROM " . PREFIX . "_request_conditions
+ WHERE request_id = '" . $request_id . "'
+ ");
+
+ // Сохраняем системное сообщение в журнал
+ reportLog($_SESSION['user_name'] . ' - удалил запрос (' . $request_id . ')', 2, 2);
+
+ // Выполянем переход к списку запросов
+ header('Location:index.php?do=request&cp=' . SESSION);
+ exit;
+ }
+
+ /**
+ * Метод, предназначенный для редактирования условий Запроса
+ *
+ * @param int $request_id идентификатор запроса
+ */
+ function requestConditionEdit($request_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ // Определяем действие пользователя
+ switch ($_REQUEST['sub'])
+ {
+ // Если действие не определено
+ case '':
+ $fields = array();
+
+ // Выполняем запрос к БД и получаем список полей у той рубрики, к которой относится данный запрос
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX . "_rubric_fields
+ WHERE
+ rubric_id = '" . $_REQUEST['rubric_id'] . "'
+ ORDER BY rubric_field_position ASC
+ ");
+
+ // Обрабатываем полученные данные и формируем массив
+ while ($row = $sql->FetchRow())
+ array_push($fields, $row);
+
+ $conditions = array();
+
+ // Выполняем запрос к БД и получаем условия запроса
+ $sql = $AVE_DB->Query("
+ SELECT *
+ FROM
+ " . PREFIX . "_request_conditions
+ WHERE
+ request_id = '" . $request_id . "'
+ ORDER BY condition_position ASC
+ ");
+
+ // Обрабатываем полученные данные и формируем массив
+ while ($row = $sql->FetchRow())
+ array_push($conditions, $row);
+
+ // Передаем данные в шаблон и отображаем страницу с редактированием условий
+ $AVE_Template->assign('request_title', $this->get_request_by_id($request_id)->request_title);
+ $AVE_Template->assign('fields', $fields);
+ $AVE_Template->assign('conditions', $conditions);
+
+ if (isAjax() && (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 1))
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/cond_list.tpl'));
+ else
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/conditions.tpl'));
+
+ break;
+
+ case 'sort':
+
+ foreach ($_REQUEST['sort'] as $position => $cond_id)
+ {
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request_conditions
+ SET
+ condition_position = '" . (int)$position . "'
+ WHERE
+ Id = '" . (int)$cond_id . "'
+ ");
+ }
+
+ if (isAjax())
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_SORTED');
+ $header = $AVE_Template->get_config_vars('REQUEST_SUCCESS');
+ $theme = 'accept';
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ }
+
+ exit;
+
+ // Если пользователь нажал кнопку Сохранить изменения
+ case 'save':
+ // Если существует хотя бы одно условие, тогда
+
+ if (isset($_REQUEST['conditions']) && is_array($_POST['conditions']))
+ {
+ $condition_edited = false;
+
+ // Обрабатываем данные полей
+ foreach ($_REQUEST['conditions'] as $condition_id => $val)
+ {
+ // Выполняем запрос к БД на обновление информации об условиях
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request_conditions
+ SET
+ request_id = '" . $request_id . "',
+ condition_compare = '" . $val['condition_compare'] . "',
+ condition_field_id = '" . $val['condition_field_id'] . "',
+ condition_value = '" . (! empty($val['condition_value']) ? $val['condition_value'] : '') . "',
+ condition_join = '" . $val['condition_join'] . "',
+ condition_status = '" . ((! empty($val['condition_value'])) ? (($val['condition_status'] == '1') ? '1' : '0') : ''). "'
+ WHERE
+ Id = '" . $condition_id . "'
+ ");
+
+ $condition_edited = true;
+ }
+
+ // Если изменения были, сохраняем системное сообщение в журнал
+ if ($condition_edited)
+ {
+ reportLog('' . $AVE_Template->get_config_vars('REQUEST_COND_CHA_SUC') . ' (' . stripslashes(htmlspecialchars($this->get_request_by_id($request_id)->request_title, ENT_QUOTES)) . ') - ( Id: '.$request_id.' )');
+
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_POST_OK');
+ $header = $AVE_Template->get_config_vars('REQUEST_SUCCESS');
+ $theme = 'accept';
+ }
+ else
+ {
+
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_POST_ERR');
+ $header = $AVE_Template->get_config_vars('REQUEST_ERROR');
+ $theme = 'error';
+ }
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_NO_POST');
+ $header = $AVE_Template->get_config_vars('REQUEST_ERROR');
+ $theme = 'error';
+ }
+
+ // Если некоторые из условий были помечены на удаление
+ if (isset($_POST['del']) && is_array($_POST['del']))
+ {
+ // Обрабатываем все поля помеченные на удаление
+ foreach ($_POST['del'] as $condition_id => $val)
+ {
+ // Выполняем запрос к БД на удаление условий
+ $AVE_DB->Query("
+ DELETE FROM
+ " . PREFIX . "_request_conditions
+ WHERE
+ Id = '" . $condition_id . "'
+ ");
+ }
+
+ // Сохраняем системное сообщение в журнал
+ reportLog('' . $AVE_Template->get_config_vars('REQUEST_COND_DEL_SUC') . ' (' . stripslashes(htmlspecialchars($this->get_request_by_id($request_id)->request_title, ENT_QUOTES)) . ') - ( Id: '.$request_id.' )');
+ }
+
+ // Нет смысла каждый раз формировать SQL-запрос с условиями Запроса
+ // поэтому формируем SQL-запрос только при изменении условий
+ // require(BASE_DIR . '/functions/func.parserequest.php');
+ request_get_condition_sql_string($request_id, true);
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request
+ SET
+ request_changed = '" . time() . "'
+ WHERE
+ Id = '" . $request_id . "'
+ ");
+
+ $AVE_DB->clearRequest($request_id);
+
+ if (! isAjax())
+ {
+ // Выполняем обновление страницы
+ header('Location:index.php?do=request&action=conditions&rubric_id=' . $_REQUEST['rubric_id'] . '&Id=' . $request_id . '&cp=' . SESSION . ($_REQUEST['pop'] ? '&pop=1' : ''));
+ exit;
+ }
+ else
+ {
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+
+ break;
+
+ // Если пользователь добавил новое условие
+ case 'new':
+ if ($_POST['new_value'] !== '')
+ {
+ // Выполняем запрос к БД на добавление нового условия
+ $sql = $AVE_DB->Query("
+ INSERT
+ " . PREFIX . "_request_conditions
+ SET
+ request_id = '" . $request_id . "',
+ condition_compare = '" . $_POST['new_operator'] . "',
+ condition_field_id = '" . $_POST['field_new'] . "',
+ condition_value = '" . $_POST['new_value'] . "',
+ condition_join = '" . $_POST['oper_new'] . "'
+ ");
+
+ if ($sql->_result === false)
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_NEW_ERR');
+ $header = $AVE_Template->get_config_vars('REQUEST_ERROR');
+ $theme = 'error';
+ }
+ else
+ {
+ // Сохраняем системное сообщение в журнал
+ reportLog('' . $AVE_Template->get_config_vars('REQUEST_COND_ADD_SUC') . ' (' . stripslashes(htmlspecialchars($this->get_request_by_id($request_id)->request_title, ENT_QUOTES)) . ') - ( Id: '.$request_id.' )');
+ }
+
+ }
+ else
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_VALUE_ERR');
+ $header = $AVE_Template->get_config_vars('REQUEST_ERROR');
+ $theme = 'error';
+ }
+
+ // Нет смысла каждый раз формировать SQL-запрос с условиями Запроса
+ // поэтому формируем SQL-запрос только при изменении условий
+ // require(BASE_DIR . '/functions/func.parserequest.php');
+ request_get_condition_sql_string($request_id, true);
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request
+ SET
+ request_changed = '" . time() . "'
+ WHERE
+ Id = '" . $request_id . "'
+ ");
+
+ $AVE_DB->clearRequest($request_id);
+
+ if (! isAjax())
+ {
+ header('Location:index.php?do=request&action=conditions&rubric_id=' . $_REQUEST['rubric_id'] . '&Id=' . $request_id . '&cp=' . SESSION);
+ exit;
+ }
+ else
+ {
+ if (! $message)
+ {
+ $message = $AVE_Template->get_config_vars('REQUEST_COND_NEW_SUC');
+ $header = $AVE_Template->get_config_vars('REQUEST_SUCCESS');
+ $theme = 'accept';
+ }
+
+ echo json_encode(array('message' => $message, 'header' => $header, 'theme' => $theme));
+ exit;
+ }
+ break;
+ }
+ }
+
+ /**
+ * @param $field_id
+ * @param $cond_id
+ */
+ function conditionFieldChange($field_id, $cond_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ // Передаем данные в шаблон и отображаем страницу с редактированием условий
+ $AVE_Template->assign('field_id', $field_id);
+ $AVE_Template->assign('cond_id', $cond_id);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/change.tpl'));
+ }
+
+
+ /**
+ * @param $field_id
+ * @param $cond_id
+ */
+ function conditionFieldChangeSave($field_id, $cond_id)
+ {
+ global $AVE_DB, $AVE_Template;
+
+ // ToDo
+ $sql = $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request_conditions
+ SET
+ condition_field_id = '" . $field_id . "'
+ WHERE
+ Id = '" . $cond_id . "'
+ ");
+
+ request_get_condition_sql_string((int)$_REQUEST['req_id'], true);
+
+ $request_id = $AVE_DB->Query("
+ SELECT
+ request_id
+ FROM
+ " . PREFIX . "_request_conditions
+ WHERE
+ Id = '" . $cond_id . "'
+ ")->GetCell();
+
+ $AVE_DB->Query("
+ UPDATE
+ " . PREFIX . "_request
+ SET
+ request_changed = '" . time() . "'
+ WHERE
+ Id = '" . $request_id . "'
+ ");
+
+ $AVE_DB->clearRequest($request_id);
+
+ // Передаем данные в шаблон и отображаем страницу с редактированием условий
+ $AVE_Template->assign('field_id', $field_id);
+ $AVE_Template->assign('cond_id', $cond_id);
+ $AVE_Template->assign('content', $AVE_Template->fetch('request/change.tpl'));
+ }
+
+}
+
+?>
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/functions/func.parserequest.php b/inc/query_variants/safe_files/functions/func.parserequest.php
new file mode 100644
index 0000000..096deea
--- /dev/null
+++ b/inc/query_variants/safe_files/functions/func.parserequest.php
@@ -0,0 +1,939 @@
+item_num = $item_num;
+ $this->is_last = $is_last;
+ $this->row = $row;
+ $this->rubric_id = $rubric_id;
+ $this->items_count = $items_count;
+ }
+
+ /**
+ * Основной метод для обработки всех условных тегов в строке.
+ *
+ * @param string $content Строка с тегами, например, '[tag:if_first]...[/tag:if]'
+ * @return string Обработанная строка
+ */
+ public function process(string $content): string
+ {
+ // Сначала обрабатываем теги if_notempty и if_empty
+ $processed_content = preg_replace_callback(
+ '/\\[tag:(if_notempty|if_empty):rfld:([a-zA-Z0-9-_]+)]\\[(more|esc|img|strip|[0-9-]+)](.*?)\\[tag:\\/if]/s',
+ function ($matches) {
+ $tag_type = $matches[1];
+ $field_name = $matches[2];
+ $format = $matches[3];
+ $inner_content = $matches[4];
+
+ $parts = explode('[tag:if_else]', $inner_content);
+ $true_content = $parts[0];
+ $false_content = $parts[1] ?? '';
+
+ $field_value = '';
+ if (defined('USE_GET_FIELDS') && USE_GET_FIELDS) {
+ $field_value = htmlspecialchars(get_field($field_name, (int)$this->row->Id), ENT_QUOTES);
+ } else {
+ $field_value = htmlspecialchars(request_get_document_field($field_name, (int)$this->row->Id, $format, $this->rubric_id), ENT_QUOTES);
+ }
+
+ $condition = ($tag_type === 'if_notempty' && $field_value !== '') || ($tag_type === 'if_empty' && $field_value === '');
+
+ return $condition ? $true_content : $false_content;
+ },
+ $content
+ );
+
+ // Затем обрабатываем остальные условные теги
+ $processed_content = preg_replace_callback(
+ '/\\[tag:(if_first|if_not_first|if_last|if_not_last|if_every:([0-9-]+)|if_not_every:([0-9-]+))](.*?)\\[tag:\\/if]/s',
+ function ($matches) {
+ $tag = $matches[1];
+ $inner_content = $matches[4];
+
+ $parts = explode('[tag:if_else]', $inner_content);
+ $true_content = $parts[0];
+ $false_content = $parts[1] ?? '';
+
+ $condition = false;
+
+ if ($tag === 'if_first') {
+ $condition = ($this->item_num === 1);
+ } elseif ($tag === 'if_not_first') {
+ $condition = ($this->item_num !== 1);
+ } elseif ($tag === 'if_last') {
+ $condition = $this->is_last;
+ } elseif (strpos($tag, 'if_not_last') === 0) {
+ $condition = !$this->is_last;
+ } elseif (strpos($tag, 'if_every') === 0) {
+ $mod = (int)($matches[2] ?? 0);
+ $condition = ($this->item_num > 0 && $mod > 0 && ($this->item_num % $mod) === 0);
+ } elseif (strpos($tag, 'if_not_every') === 0) {
+ $mod = (int)($matches[3] ?? 0);
+ $condition = ($this->item_num > 0 && $mod > 0 && ($this->item_num % $mod) !== 0);
+ }
+
+ return $condition ? $true_content : $false_content;
+ },
+ $processed_content
+ );
+
+ return $processed_content;
+ }
+}
+
+/**
+ * Функция для обработки тегов с использованием TagProcessor.
+ *
+ * @param string $items Строка с тегами.
+ * @param int $item_num Текущий номер элемента.
+ * @param bool $is_last Флаг, указывающий, является ли элемент последним.
+ * @param object $row Объект с данными документа.
+ * @param int $items_count Общее количество элементов на текущей странице.
+ * @return string Обработанная строка.
+ */
+function request_process_tags($items, $item_num, $is_last, $row, $items_count)
+{
+ // Создаем экземпляр обработчика, передавая общее количество
+ $processor = new TagProcessor($item_num, $is_last, $row, (int)$row->rubric_id, $items_count);
+
+ // Обрабатываем содержимое и возвращаем результат
+ return $processor->process($items);
+}
+
+/**
+ * Достаем настройки запроса
+ *
+ * @param string|int $id Идентификатор или псевдоним запроса
+ * @return object|string Объект с настройками запроса или пустая строка в случае ошибки
+ */
+function request_get_settings ($id)
+{
+ global $AVE_DB;
+
+ // Получаем информацию о запросе
+ $sql = "
+ SELECT
+ #REQUEST SETTINGS = " . $id . "
+ *
+ FROM
+ " . PREFIX . "_request
+ WHERE
+ " . (is_numeric($id) ? 'Id' : 'request_alias') . " = '" . $id . "'
+ ";
+
+ // Выполняем запрос с учетом кеширования
+ $reqest_settings = $AVE_DB->Query($sql, -1, 'rqs_' . $id, true, '.settings')->FetchRow();
+
+ // Выходим, если нет запроса
+ if (! is_object($reqest_settings))
+ return '';
+ else
+ return $reqest_settings;
+}
+
+/**
+ * Обработка условий запроса.
+ * Возвращает строку условий в SQL-формате.
+ *
+ * @param int|string $id ID или алиас запроса.
+ *
+ * @return string Возвращает строку SQL-условия.
+ */
+function request_get_condition_sql_string($id)
+{
+ global $AVE_DB, $AVE_Core;
+
+ // Используем request_get_settings() для получения ID и настроек запроса.
+ $request_settings = request_get_settings($id);
+
+ // Выходим, если запрос не найден.
+ if (!is_object($request_settings)) {
+ return '';
+ }
+
+ $from = [];
+ $where = [];
+ $retval = '';
+ $i = 0;
+
+ if (!defined('ACP'))
+ {
+ $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];
+ }
+ }
+
+ // Теперь мы можем безопасно запросить условия, используя гарантированный ID.
+ $sql_ak = $AVE_DB->Query(
+ "
+ SELECT
+ condition_field_id,
+ condition_value,
+ condition_compare,
+ condition_join
+ FROM " . PREFIX . "_request_conditions
+ WHERE
+ request_id = '" . $request_settings->Id . "'
+ AND condition_status = '1'
+ ORDER BY
+ condition_position ASC;
+ ",
+ -1,
+ 'rqc_' . $request_settings->Id,
+ true,
+ '.conditions'
+ );
+
+ if (!empty($_POST['req_' . $id]) && is_array($_POST['req_' . $id]))
+ {
+ foreach ($_POST['req_' . $id] as $fid => $val)
+ {
+ if (!($val != '' && isset($_SESSION['val_' . $fid]) && in_array($val, $_SESSION['val_' . $fid]))) continue;
+
+ if ($i) $from[] = "JOIN " . PREFIX . "_document_fields AS t$i ON t$i.document_id = t0.document_id";
+
+ $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value = '" . $AVE_DB->Escape($val) . "'";
+
+ ++$i;
+ }
+ }
+
+ while ($row_ak = $sql_ak->FetchRow())
+ {
+ $fid = $row_ak->condition_field_id;
+
+ if (isset($_POST['req_' . $id]) && isset($_POST['req_' . $id][$fid])) continue;
+
+ if ($i) $from[] = "JOIN " . PREFIX . "_document_fields AS t$i ON t$i.document_id = t0.document_id";
+
+ $val = $row_ak->condition_value;
+
+ switch ($row_ak->condition_compare)
+ {
+ case ' <': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value < '" . $AVE_DB->Escape($val) . "'"; break;
+ case ' >': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value > '" . $AVE_DB->Escape($val) . "'"; break;
+ case '<=': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value <= '" . $AVE_DB->Escape($val) . "'"; break;
+ case '>=': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value >= '" . $AVE_DB->Escape($val) . "'"; break;
+ case '==': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value = '" . $AVE_DB->Escape($val) . "'"; break;
+ case '!=': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value != '" . $AVE_DB->Escape($val) . "'"; break;
+ case '%%': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value LIKE '%" . $AVE_DB->Escape($val) . "%'"; break;
+ case '%': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value LIKE '" . $AVE_DB->Escape($val) . "%'"; break;
+ case '--': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value NOT LIKE '%" . $AVE_DB->Escape($val) . "%'"; break;
+ case '!-': $where[] = "t$i.rubric_field_id = " . $fid . " AND t$i.field_value NOT LIKE '" . $AVE_DB->Escape($val) . "%'"; break;
+ }
+
+ if ($i || $row_ak->condition_join == 'AND') ++$i;
+ }
+
+ if (!empty($where))
+ {
+ $from = ' FROM ' . PREFIX . '_document_fields AS t0 ' . implode(' ', $from);
+ $where = ' WHERE ' . (($i) ? implode(' AND ', $where) : '(' . implode(') OR(', $where) . ')');
+ $retval = 'AND a.Id = ANY(SELECT t0.document_id' . $from . $where . ')';
+ }
+
+ if (defined('ACP'))
+ {
+ $AVE_DB->Query("
+ UPDATE " . PREFIX . "_request
+ SET request_where_cond = '" . addslashes($retval) . "'
+ WHERE Id = '" . $request_settings->Id . "'
+ ");
+ }
+
+ return $retval;
+}
+
+/**
+ * Функция обработки тэгов полей с использованием шаблонов
+ * в соответствии с типом поля
+ *
+ * @param int $rubric_id идентификатор рубрики
+ * @param int $document_id идентификатор документа
+ * @param int $maxlength максимальное количество символов обрабатываемого поля
+ * @return string
+ */
+ function request_get_document_field ($field_id, $document_id, $maxlength = null, $rubric_id = 0)
+ {
+ if (! is_numeric($document_id) || $document_id < 1)
+ return '';
+
+ $_maxlength = $maxlength;
+
+ $document_fields = get_document_fields($document_id);
+
+ // ToDo
+ 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' || $maxlength == 'strip')
+ {
+ if ($maxlength == 'more')
+ {
+ // ToDo - Вывести в настройки или в настройки самого запроса
+ $teaser = explode(' ', $field_value);
+ $field_value = $teaser[0];
+ }
+ elseif ($maxlength == 'esc')
+ {
+ $field_value = addslashes($field_value);
+ }
+ elseif ($maxlength == 'img')
+ {
+ $field_value = getImgSrc($field_value);
+ }
+ elseif ($maxlength == 'strip')
+ {
+ $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);
+ }
+ }
+ elseif (is_numeric($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 = '', $req_item_num = null, $items_count = null, $is_last = null)
+{
+ global
+ $AVE_DB,
+ $params_of_teaser,
+ $use_cache,
+ $request_id,
+ $request_changed,
+ $request_changed_elements;
+
+ if (is_array($mixed)) {
+ $row = intval($mixed[1]);
+ } else if (is_numeric($mixed)) {
+ $row = intval($mixed);
+ }
+
+ $row = (is_object($mixed) ? $mixed : getDocument($row));
+
+ unset ($mixed);
+
+ if (! $row) {
+ return '';
+ }
+
+ $tparams_id = '';
+ if ($tparams != '') {
+ $tparams_id = $row->Id . md5($tparams);
+ $params_of_teaser[$tparams_id] = [];
+ $tparams = trim($tparams,'[]:');
+ $params_of_teaser[$tparams_id] = explode('|',$tparams);
+ }
+
+ $sql = "
+ SELECT
+ rubric_teaser_template
+ FROM
+ " . PREFIX . "_rubrics
+ WHERE
+ Id = '" . intval($row->rubric_id) . "'
+ ";
+
+ $template = ($template > ''
+ ? $template
+ : $AVE_DB->Query($sql)->GetCell());
+
+ $hash = 'g-' . UGROUP;
+ $hash .= 'r-' . $request_id;
+ $hash .= 't-' . $row->Id;
+
+ if ($req_item_num !== null && $items_count !== null) {
+ $hash .= 'num-' . $req_item_num;
+ $hash .= 'total-' . $items_count;
+ }
+
+ $hash = md5($hash);
+
+ $cache_id = 'requests/elements/' . (floor($row->Id / 1000)) . '/' . $row->Id;
+ $cachefile_docid = BASE_DIR . '/tmp/cache/sql/' . $cache_id . '/' . $hash . '.element';
+
+ if (file_exists($cachefile_docid) && isset($use_cache) && $use_cache == 1) {
+ $check_file = $request_changed_elements;
+ if ($check_file > filemtime($cachefile_docid)) {
+ unlink ($cachefile_docid);
+ }
+ } else {
+ if (file_exists($cachefile_docid)) {
+ unlink ($cachefile_docid);
+ }
+ }
+
+ if (defined('DEV_MODE') AND DEV_MODE) {
+ $cachefile_docid = null;
+ }
+
+ if (! file_exists($cachefile_docid)) {
+ $link = rewrite_link('index.php?id=' . $row->Id . '&doc=' . (empty($row->document_alias) ? prepare_url($row->document_title) : $row->document_alias));
+ $item = $template;
+
+ // Обработка всех условных тегов через TagProcessor
+ if ($req_item_num !== null && $items_count !== null) {
+ $tagProcessor = new TagProcessor($req_item_num, $is_last, $row, (int)$row->rubric_id, $items_count);
+ $item = $tagProcessor->process($item);
+ }
+
+ // Парсим теги визуальных блоков
+ $item = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $item);
+
+ // Парсим теги системных блоков
+ $item = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)(|:\{(.*?)\})\]/',
+ function ($m) {
+ return parse_sysblock($m[1], $m[2]);
+ },
+ $item);
+
+ // Парсим элементы полей
+ $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/',
+ function ($m) use ($row) {
+ return get_field_element($m[1], $m[2], $m[3], (int)$row->Id);
+ },
+ $item);
+
+ // Парсим теги полей
+ $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)\]\[(more|esc|img|strip|[0-9-]+)]/',
+ function ($match) use ($row) {
+ return request_get_document_field($match[1], (int)$row->Id, $match[2], (int)$row->rubric_id);
+ },
+ $item);
+
+ // Повторно парсим теги полей
+ $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)\]\[(more|esc|img|strip|[0-9-]+)]/',
+ function ($m) use ($row) {
+ return request_get_document_field($m[1], (int)$row->Id, $m[2], (int)$row->rubric_id);
+ },
+ $item);
+
+ // Возвращаем поле документа из БД (document_***)
+ $item = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
+ function ($m) use ($row) {
+ return isset($row->{$m[1]}) ? $row->{$m[1]} : null;
+ },
+ $item
+ );
+
+ // Если пришел вызов на активацию языковых файлов
+ $item = preg_replace_callback(
+ '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
+ function ($m) {
+ global $AVE_Template;
+ return $AVE_Template->get_config_vars($m[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]+)\]/',
+ 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 != '') {
+ $item = preg_replace_callback('/\[tparam:([0-9]+)\]/',
+ function ($m) use ($tparams_id) {
+ return f_params_of_teaser($tparams_id, $m[1]);
+ },
+ $item);
+ } else {
+ $item = preg_replace('/\[tparam:([0-9]+)\]/', '', $item);
+ }
+
+ $item = str_replace('[tag:domain]', getSiteUrl(), $item);
+ $item = str_replace('[tag:link]', $link, $item);
+ $item = str_replace('[tag:docid]', $row->Id, $item);
+ $item = str_replace('[tag:itemid]', $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]', translate_date(strftime(DATE_FORMAT, $row->document_published)), $item);
+ $item = str_replace('[tag:doctime]', translate_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-. \/]+)\]/',
+ function ($m) use ($row) {
+ 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+)\]/',
+ function ($m) use ($row) {
+ 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);
+
+ Registry::remove('documents', $row->Id);
+ Registry::remove('fields', $row->Id);
+ Registry::remove('fields_param', $row->Id);
+
+ unset($row, $template);
+
+ return $item;
+}
+
+/**
+ * Парсинг запроса
+ *
+ * @param int|string $id Идентификатор или псевдоним запроса
+ * @return string
+ */
+function request_parse($id)
+{
+ global $AVE_Core, $AVE_DB, $request_documents;
+
+ // Начальная проверка ID
+ if (is_array($id)) {
+ $id = $id[1];
+ }
+
+ // Получаем информацию о запросе. Эта функция должна создать .settings файл
+ $request = request_get_settings($id);
+
+ // Выходим, если запрос не найден
+ if (!is_object($request)) {
+ return '';
+ }
+
+ // Фиксируем время начала генерации запроса
+ Debug::startTime('request_' . $id);
+
+ // Инициализация переменных из настроек запроса
+ $limit = ($request->request_items_per_page < 1) ? 1 : $request->request_items_per_page;
+ $main_template = $request->request_template_main;
+ $item_template = $request->request_template_item;
+ $request_order_by = $request->request_order_by;
+ $request_order_by_nat = intval($request->request_order_by_nat);
+ $request_asc_desc = $request->request_asc_desc;
+
+ // Генерируем строку условий
+ $where_cond = request_get_condition_sql_string($request->Id);
+ $where_cond = str_replace('%%PREFIX%%', PREFIX, $where_cond);
+
+ // Динамическое формирование WHERE-части запросов
+ $where_common = "
+ a.Id != '1'
+ AND a.Id != '" . PAGE_NOT_FOUND_ID . "'
+ AND a.rubric_id = '" . (int)$request->rubric_id . "'
+ AND a.document_deleted != '1'
+ AND a.document_status != '0'
+ " . $hide_current_condition . "
+ " . $owner_condition . "
+ " . $lang_condition . "
+ " . $where_cond . "
+ " . $doctime . "
+ ";
+
+ // Определение частей запроса в зависимости от наличия модуля комментариев и нативной сортировки
+ $join_comment = !empty($AVE_Core->install_modules['comment']->Status)
+ ? "LEFT JOIN " . PREFIX . "_modul_comment_info AS b ON b.document_id = a.Id"
+ : "";
+ $select_comment_count = !empty($AVE_Core->install_modules['comment']->Status)
+ ? ", COUNT(b.document_id) AS nums"
+ : "";
+ $group_by_doc_id = !empty($AVE_Core->install_modules['comment']->Status)
+ ? "GROUP BY a.Id"
+ : "";
+
+ if ($request_order_by_nat != 0) {
+ $join_fields = "LEFT JOIN " . PREFIX . "_document_fields AS d ON a.Id = d.document_id";
+ $where_fields = "AND d.rubric_field_id = " . intval($request_order_by_nat);
+ $select_fields = ", d.field_value, d.rubric_field_id";
+ $order_by = "ORDER BY d.field_value " . ($request_asc_desc === 'DESC' ? 'DESC' : 'ASC');
+ } else {
+ $join_fields = "";
+ $where_fields = "";
+ $select_fields = "";
+ $order_by = "ORDER BY " . $request_order_by . " " . $request_asc_desc;
+ }
+
+ $num_items = 0;
+ $num_pages = 0;
+ $start = 0;
+
+ // Условное выполнение запроса для подсчета общего количества элементов
+ if ($request->request_show_pagination == 1 || $request->request_count_items == 1) {
+ // Формируем запрос для подсчета количества элементов
+ $count_sql = "
+ SELECT COUNT(*)
+ FROM " . PREFIX . "_documents AS a
+ " . $join_fields . "
+ WHERE
+ " . $where_common . "
+ " . $where_fields . "
+ ";
+
+ // Получаем общее количество элементов, используя кеширование
+ $num_items = $AVE_DB->Query($count_sql, (int)$request->request_cache_lifetime, 'rqs_' . $id, true, '.count')->GetCell();
+ }
+
+ // Если пагинация включена, вычисляем количество страниц и начальную позицию
+ if ($request->request_show_pagination == 1) {
+ $num_pages = ceil($num_items / $limit);
+ $start = get_current_page('page') * $limit - $limit;
+ }
+
+ // Формируем финальный запрос для выборки данных
+ $main_sql_query = "
+ SELECT
+ a.Id,
+ a.document_title,
+ a.document_alias,
+ a.document_parent,
+ a.document_author_id,
+ a.document_count_view,
+ a.document_published,
+ a.document_lang
+ " . $select_comment_count . "
+ " . $select_fields . "
+ FROM
+ " . PREFIX . "_documents AS a
+ " . $join_comment . "
+ " . $join_fields . "
+ WHERE
+ " . $where_common . "
+ " . $where_fields . "
+ " . $group_by_doc_id . "
+ " . $order_by . "
+ LIMIT " . $start . "," . $limit . "
+ ";
+
+ // Отладочный вывод SQL-запроса, если это необходимо
+ if ($request->request_show_sql == 1) {
+ $return = Debug::_print($main_sql_query);
+ return $return;
+ }
+
+ // Выполняем запрос с кешированием, создавая файл .request
+ Debug::startTime('SQL');
+ $q = $AVE_DB->Query($main_sql_query, (int)$request->request_cache_lifetime, 'rqs_' . $id, true, '.request');
+ $GLOBALS['block_generate']['REQUESTS'][$id]['SQL'] = Debug::endTime('SQL');
+
+ $rows = array();
+ $request_documents = array();
+ while ($row = $q->FetchRow()) {
+ array_push($request_documents, $row->Id);
+ array_push($rows, $row);
+ }
+
+ // Условное отображение контента
+ if ($q->NumRows() > 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 = '';
+ if ($request->request_show_pagination == 1 && $num_pages > 1) {
+ @$GLOBALS['page_id'][$_REQUEST['id']]['page'] = (isset($GLOBALS['page_id'][$_REQUEST['id']]['page']) && $GLOBALS['page_id'][$_REQUEST['id']]['page'] > $num_pages) ? @$GLOBALS['page_id'][$_REQUEST['id']]['page'] : $num_pages;
+ $queries = ($request->request_use_query == 1 || (isset($params['ADD_GET']) && $params['ADD_GET'] == 1)) ? ((isset($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : '') : '';
+ $pagination_base = '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) . '&page={s}';
+ $pagination_params = ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage'])) ? '&artpage=' . $_REQUEST['artpage'] : '') . ((isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage'])) ? '&apage=' . $_REQUEST['apage'] : '');
+ $pagination_full = $pagination_base . $pagination_params . clean_php($queries);
+ $pagination_id = (isset($params['PAGINATION']) && $params['PAGINATION'] > 0) ? $params['PAGINATION'] : $request->request_pagination;
+ $pagination = AVE_Paginations::getPagination($num_pages, 'page', $pagination_full, $pagination_id);
+
+ // Костыли для главной страницы
+ $pagination = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($pagination)));
+ $pagination = str_ireplace('"//' . URL_SUFF . '"', '"/"', $pagination);
+ if ($request->request_use_query == 1 || (isset($params['ADD_GET']) && $params['ADD_GET'] == 1)) {
+ $pagination = preg_replace('/(?request_cache_elements;
+
+ $request_id = $request->Id;
+
+ $request_changed = $request->request_changed;
+ $request_changed_elements = $request->request_changed_elements;
+
+ Debug::startTime('ELEMENTS_ALL');
+
+ foreach ($rows as $row) {
+ $x++;
+ $last_item = ($x == $items_count);
+ $req_item_num = $x;
+
+ // Передаем элемент для обработки и кэширования в showrequestelement.
+ $items .= showrequestelement($row, $item_template, '', $req_item_num, $items_count, $last_item);
+ }
+
+ $GLOBALS['block_generate']['REQUESTS'][$id]['ELEMENTS']['ALL'] = Debug::endTime('ELEMENTS_ALL');
+
+ // Обработка основного шаблона
+ $main_template = str_replace('[tag:pages]', $pagination, $main_template);
+ $main_template = str_replace('[tag:docid]', $AVE_Core->curentdoc->Id, $main_template);
+ $main_template = str_replace('[tag:pagetitle]', stripslashes(htmlspecialchars_decode($AVE_Core->curentdoc->document_title)), $main_template);
+ $main_template = str_replace('[tag:pages:curent]', get_current_page('page'), $main_template);
+ $main_template = str_replace('[tag:pages:total]', $num_pages, $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: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:docauthor]', get_username_by_id($AVE_Core->curentdoc->document_author_id), $main_template);
+ $main_template = preg_replace_callback('/\[tag:dropdown:([,0-9]+)\]/', function($m) use ($request) {
+ return request_get_dropdown($m[1], (int)$request->rubric_id, (int)$request->Id);
+ }, $main_template);
+ $main_template = preg_replace_callback('/\[tag:date:([a-zA-Z0-9-. \/]+)\]/', function ($match) use ($AVE_Core) {
+ return translate_date(date($match[1], $AVE_Core->curentdoc->document_published));
+ }, $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);
+ $main_template = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $main_template);
+ $main_template = preg_replace_callback('/\[tag:block:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_block', $main_template);
+
+ $return = str_replace('[tag:content]', $items, $main_template);
+ $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']['REQUESTS'][$id]['TIME'] = 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/' . 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 = substr($field_value, 0, $maxlength) . (strlen($field_value) > $maxlength ? '... ' : '');
+ }
+
+ return $field_value;
+}
+
+/**
+ * Функция формирования выпадающих списков
+ * для управления условиями запроса в публичной части
+ *
+ * @param string $dropdown_ids идентификаторы полей
+ * типа выпадающий список указанные через запятую
+ * @param int $rubric_id идентификатор рубрики
+ * @param int $request_id идентификатор запроса
+ * @return string
+ */
+function request_get_dropdown($dropdown_ids, $rubric_id, $request_id)
+{
+ global $AVE_Core, $AVE_DB, $AVE_Template;
+
+ // Получаем настройки запроса
+ $request_settings = request_get_settings($request_id);
+
+ if (!is_object($request_settings)) {
+ return '';
+ }
+
+ $dropdown_ids = explode(',', preg_replace('/[^,\\d]/', '', $dropdown_ids));
+ $dropdown_ids[] = 0;
+ $dropdown_ids = implode(',', $dropdown_ids);
+ $doc = 'doc_' . $AVE_Core->curentdoc->Id;
+ $control = array();
+
+ // Для кеширования, используем $request_id в качестве уникального идентификатора.
+ $sql = $AVE_DB->Query(
+ "
+ SELECT
+ Id,
+ rubric_field_title,
+ rubric_field_default
+ FROM " . PREFIX . "_rubric_fields
+ WHERE Id IN(" . $dropdown_ids . ")
+ AND rubric_id = '" . $rubric_id . "'
+ AND rubric_field_type = 'drop_down'
+ ", -1, 'rqs_' . $request_id, true, '.dropdown');
+
+ while ($row = $sql->FetchRow())
+ {
+ $dropdown['titel'] = $row->rubric_field_title;
+ $dropdown['selected'] = isset($_SESSION[$doc]['req_' . $request_id][$row->Id]) ? $_SESSION[$doc]['req_' . $request_id][$row->Id] : '';
+ $dropdown['options'] = $_SESSION['val_' . $row->Id] = explode(',', $row->rubric_field_default);
+ $control[$row->Id] = $dropdown;
+ }
+
+ $AVE_Template->assign('request_id', $request_id);
+ $AVE_Template->assign('ctrlrequest', $control);
+ return $AVE_Template->fetch(BASE_DIR . '/templates/' . THEME_FOLDER . '/tpl/request/public.tpl');
+}
+
+?>
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/templates/default/index.php b/inc/query_variants/safe_files/templates/default/index.php
new file mode 100644
index 0000000..5ca71c3
--- /dev/null
+++ b/inc/query_variants/safe_files/templates/default/index.php
@@ -0,0 +1,8 @@
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/templates/default/tpl/index.php b/inc/query_variants/safe_files/templates/default/tpl/index.php
new file mode 100644
index 0000000..4ca25aa
--- /dev/null
+++ b/inc/query_variants/safe_files/templates/default/tpl/index.php
@@ -0,0 +1,4 @@
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/templates/default/tpl/request/index.php b/inc/query_variants/safe_files/templates/default/tpl/request/index.php
new file mode 100644
index 0000000..4ca25aa
--- /dev/null
+++ b/inc/query_variants/safe_files/templates/default/tpl/request/index.php
@@ -0,0 +1,4 @@
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/templates/default/tpl/request/public.tpl b/inc/query_variants/safe_files/templates/default/tpl/request/public.tpl
new file mode 100644
index 0000000..bcdf9ab
--- /dev/null
+++ b/inc/query_variants/safe_files/templates/default/tpl/request/public.tpl
@@ -0,0 +1,16 @@
+
+
+
\ No newline at end of file
diff --git a/inc/query_variants/safe_files/templates/index.php b/inc/query_variants/safe_files/templates/index.php
new file mode 100644
index 0000000..5ca71c3
--- /dev/null
+++ b/inc/query_variants/safe_files/templates/index.php
@@ -0,0 +1,8 @@
+
\ No newline at end of file