diff --git a/class/class.settings.php b/class/class.settings.php index 2e88e73..bfe1866 100644 --- a/class/class.settings.php +++ b/class/class.settings.php @@ -59,7 +59,78 @@ $AVE_Template->assign('content', $AVE_Template->fetch('settings/settings_main.tpl')); } - /** +/** + * Переключает файлы запросов (UNLINK+COPY) и очищает связанные таблицы в БД. + * + * @param bool $use_safe_version TRUE для безопасной версии, FALSE для оригинальной. + * @return bool TRUE в случае успеха, FALSE в случае ошибки. + */ + private function _switchQueryFiles($use_safe_version) + { + // Получаем доступ к глобальному объекту базы данных + global $AVE_DB; + + // 1. Загружаем список файлов для замены (Манифест) + $manifest_path = BASE_DIR . '/inc/query_variants/query_manifest.php'; + + $manifest = @require $manifest_path; + + if (!is_array($manifest) || empty($manifest)) { + return false; + } + + // 2. Определяем исходную папку + $source_dir_name = $use_safe_version ? 'safe_files' : 'original_files'; + $source_base = BASE_DIR . '/inc/query_variants/' . $source_dir_name; + + $error_count = 0; + + // 3. ИТЕРАЦИЯ И КОПИРОВАНИЕ + foreach ($manifest as $relative_path) { + + $source_file = $source_base . '/' . $relative_path; + $target_file = BASE_DIR . '/' . $relative_path; + + if (!file_exists($source_file)) { + $error_count++; + continue; + } + + // 4. Создаем папку назначения, если ее нет + $target_dir = dirname($target_file); + if (!is_dir($target_dir)) { + @mkdir($target_dir, 0775, true); + } + + // 5. ГАРАНТИЯ ПЕРЕЗАПИСИ: Удаляем старый файл перед копированием + if (file_exists($target_file)) { + if (!@unlink($target_file)) { + $error_count++; + continue; + } + } + + // 6. Копируем + if (!@copy($source_file, $target_file)) { + $error_count++; + } + } + + // 7. ОЧИСТКА БАЗЫ ДАННЫХ + if ($error_count === 0) + { + // Используем константу PREFIX для определения префикса таблиц + $AVE_DB->query("DELETE FROM `" . PREFIX . "_request`"); + $AVE_DB->query("DELETE FROM `" . PREFIX . "_request_conditions`"); + } + + // 8. Возвращаем результат + return ($error_count === 0); + } + + + +/** * Метод отображения дополнительных настроек * */ @@ -71,11 +142,19 @@ if (isset($_REQUEST['more'])) { $set = ' $type) { foreach($type as $k => $v) { + // ИЗВЛЕКАЕМ ЗНАЧЕНИЕ ДЛЯ ПЕРЕКЛЮЧЕНИЯ ФАЙЛОВ + // Сохраняем значение переменной из формы до ее преобразования. + if ($k == 'REQUEST_USE_VERSION') { + $request_use_version_value = $v; + } + switch ($GLOBALS['CMS_CONFIG'][$key][$k]['TYPE']) { case 'bool' : @@ -108,8 +187,18 @@ $result = file_put_contents(BASE_DIR . '/config/config.inc.php', $set); - if ($result > 0) + if ($result > 0) { + $new_query_setting = (bool)$request_use_version_value; + + // Вызываем функцию и сохраняем результат + $switch_success = $this->_switchQueryFiles($new_query_setting); + + // Если переключение не удалось, записываем это в лог (но показываем пользователю успех) + if (!$switch_success) { + reportLog('ВНИМАНИЕ: Конфигурация сохранена, но переключение файлов при вызове AJAX не удалось (возможна блокировка файла).'); + } + $message = $AVE_Template->get_config_vars('SETTINGS_SAVED'); $header = $AVE_Template->get_config_vars('SETTINGS_SUCCESS'); $theme = 'accept'; @@ -117,6 +206,7 @@ } else { + // ... (если не удалось записать config.inc.php) $message = $AVE_Template->get_config_vars('SETTINGS_SAVED_ERR'); $header = $AVE_Template->get_config_vars('SETTINGS_ERROR'); $theme = 'error'; diff --git a/inc/config.php b/inc/config.php index a9ca5f3..bab903a 100644 --- a/inc/config.php +++ b/inc/config.php @@ -484,6 +484,14 @@ /* ======================================================================================================== */ + //-- Использовать по умолчанию запросы из AVE.CMS ver 2.09RC1 + $GLOBALS['CMS_CONFIG']['_CONST_REQUEST']['REQUEST_USE_VERSION'] = [ + 'DESCR' => 'Использовать безопасные запросы из ver 2.09RC1
(Если выбрать \'Нет\', то будут использоваться оригинальные запросы)', + 'DEFAULT' => true, + 'TYPE' => 'bool', + 'VARIANT' => '' + ]; + //-- Окончание в полях запроса $GLOBALS['CMS_CONFIG']['_CONST_REQUEST']['REQUEST_ETC'] = [ 'DESCR' => 'Окончание в полях запроса', diff --git a/inc/query_variants/original_files/admin/request.php b/inc/query_variants/original_files/admin/request.php new file mode 100644 index 0000000..df16c5f --- /dev/null +++ b/inc/query_variants/original_files/admin/request.php @@ -0,0 +1,105 @@ +rubricPermissionFetch(); + + $AVE_Template->config_load(BASE_DIR . "/admin/lang/" . $_SESSION['admin_language'] . "/request.txt", 'request'); + + switch ($_REQUEST['action']) + { + case '': + if(check_permission_acp('request_view')) + { + $AVE_Rubric->rubricTemplateShow(0, 1); + $AVE_Request->requestListShow(); + } + break; + + case 'edit': + if(check_permission_acp('request_edit')) + { + $AVE_Rubric->rubricTemplateShow(0, 1); + $AVE_Request->requestEdit($_REQUEST['Id']); + } + break; + + case 'copy': + if(check_permission_acp('request_edit')) + { + $AVE_Request->requestCopy((int)$_REQUEST['Id']); + } + break; + + case 'new': + if(check_permission_acp('request_edit')) + { + $AVE_Rubric->rubricTemplateShow(0, 1); + $AVE_Request->requestNew(); + } + break; + + case 'delete_query': + if(check_permission_acp('request_edit')) + { + $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/original_files/admin/templates/request/change.tpl b/inc/query_variants/original_files/admin/templates/request/change.tpl new file mode 100644 index 0000000..1671bbe --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/change.tpl @@ -0,0 +1,39 @@ +{if $smarty.request.sub == ''} +
+ +   + + +
+{else} + {foreach from=$fields_list item=field_group} + + {foreach from=$field_group.fields item=field} + {if $field_id == $field.Id} +
+ {$field.rubric_field_title|escape} (ID: {$field.Id|escape}) + +
+ {/if} + {/foreach} + + {/foreach} +{/if} diff --git a/inc/query_variants/original_files/admin/templates/request/cond_list.tpl b/inc/query_variants/original_files/admin/templates/request/cond_list.tpl new file mode 100644 index 0000000..f4ebfef --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/cond_list.tpl @@ -0,0 +1,127 @@ +
+ + + + + + + + + + + + + + + + + + + + + + {if $conditions} + + {foreach name=cond from=$conditions item=condition} + + + + + + + + + + + + + + {/foreach} + + {else} + + + + {/if} + +
{#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
condition_status ==1}checked{/if} class="toprightDir float" /> + {foreach from=$fields_list item=field_group} + + {foreach from=$field_group.fields item=field} + {if $condition->condition_field_id == $field.Id} + + {/if} + {/foreach} + + {/foreach} + + + + +
+
    +
  • {#REQUEST_COND_MESSAGE#}
  • +
+
+ + {if $conditions} +
+ + + {#REQUEST_OR#} +   + {if $smarty.request.pop} + + {/if} +
+
+ {/if} + + + {if $conditions} + + {/if} diff --git a/inc/query_variants/original_files/admin/templates/request/conditions.tpl b/inc/query_variants/original_files/admin/templates/request/conditions.tpl new file mode 100644 index 0000000..270c06e --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/conditions.tpl @@ -0,0 +1,421 @@ + + +
+
{#REQUEST_CONDITIONS#}
+
+ +
+
+ {#REQUEST_CONDITION_TIP#} +
+
+ + + +
+ +
+ +
+
{#REQUEST_NEW_CONDITION#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
+ + + + + + +
+
+ +
+
+
+
+ +
+
+
{#REQUEST_CONDITION#}
+ {if !$smarty.request.pop} + + {/if} +
+ +
+ + + + + + + + + + + + + + + + + + + + + + {if $conditions} + + {foreach name=cond from=$conditions item=condition} + + + + + + + + + + + + + {/foreach} + + {else} + + + + {/if} + +
{#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
condition_status ==1}checked{/if} class="toprightDir float" /> + + {foreach from=$fields_list item=field_group} + + {foreach from=$field_group.fields item=field} + {if $condition->condition_field_id == $field.Id} + + {/if} + {/foreach} + + {/foreach} + + + + + +
+
    +
  • {#REQUEST_COND_MESSAGE#}
  • +
+
+ {if $conditions} +
+ + + {#REQUEST_OR#} +   + {if $smarty.request.pop} + + {/if} +
+
+ {/if} + +
+ +
+ + +
+ + \ No newline at end of file diff --git a/inc/query_variants/original_files/admin/templates/request/form.tpl b/inc/query_variants/original_files/admin/templates/request/form.tpl new file mode 100644 index 0000000..143a216 --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/form.tpl @@ -0,0 +1,748 @@ + + +{if $smarty.request.action=='edit'} +
+
{#REQUEST_EDIT2#}
+
+ {#REQUEST_CONDITION_EDIT#} +
+
+
+
{#REQUEST_EDIT_TIP#}
+
+{else} +
+
{#REQUEST_NEW#}
+
+
+
{#REQUEST_NEW_TIP#}
+
+{/if} + + + + +{if $errors} + +{/if} + +{if !check_permission('request_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==''} + +{/if} + +
+ + + +
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{#REQUEST_HEADER_SELF#}
{#REQUEST_NAME2#}
+
+ [?] {#REQUEST_ALIAS#}: +
+
+
+   + + + + +
+
{#REQUEST_CACHE#}{#REQUEST_CACHE_ELEMENTS#}request_cache_elements}checked="checked"{/if}/>
{#REQUEST_SELECT_RUBRIK#} + + +
{#REQUEST_DESCRIPTION#}
{#REQUEST_INTERNAL_INFO#}
{#REQUEST_CONDITION#} + {if $iframe == 'no'} + + {/if} + {if $iframe != 'no'} + {#REQUEST_BUTTON_COND#} + {/if} +
{#REQUEST_HEADER_NAME#}{#REQUEST_HEADER_PARAMETR#}{#REQUEST_HEADER_NAME#}{#REQUEST_HEADER_PARAMETR#}
{#REQUEST_HIDE_CURRENT#}request_hide_current}checked="checked"{/if}/>{#REQUEST_ONLY_OWNER#}request_only_owner}checked="checked"{/if}/>
{#REQUEST_SORT_BY_NAT#} + + {#REQUEST_SORT_BY#} + +
{#REQUEST_ASC_DESC#} + + {#REQUEST_DOC_PER_PAGE#} + +
{#REQUEST_PAGINATION#}
{#REQUEST_SHOW_NAVI#}request_show_pagination=='1'} checked="checked"{/if} />{#REQUEST_NAVI_TPL#} + +
{#REQUEST_COUNT_ITEMS#}request_count_items == '1'} checked="checked"{/if} />{#REQUEST_USE_QUERY#}request_use_query == '1'} checked="checked"{/if} />
{#REQUEST_OTHER#}
{#REQUEST_USE_LANG#}request_lang == '1'} checked="checked"{/if} />
{#REQUEST_SHOW_STAT#}request_show_statistic == '1'} checked="checked"{/if} />{#REQUEST_SHOW_SQL#}request_show_sql == '1'} checked="checked"{/if} />
{#REQUEST_HEADER_EXTERNAL#}
{#REQUEST_EXTERNAL#}request_external == '1'} checked="checked"{/if} />{#REQUEST_ONLY_AJAX#}request_ajax == '1'} checked="checked"{/if} />
+
+ +
+ + + + + +
+ +
+ +
+
+ {if $smarty.request.action=='edit'} + + {else} + + {/if} + {#REQUEST_OR#} + {if $smarty.request.action=='edit'} + + {else} + + {/if} + {#REQUEST_CANCEL#} +
+
+ +
+ +
+ +
+ +{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} diff --git a/inc/query_variants/original_files/admin/templates/request/list.tpl b/inc/query_variants/original_files/admin/templates/request/list.tpl new file mode 100644 index 0000000..317ae9a --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/list.tpl @@ -0,0 +1,270 @@ + + +
{#REQUEST_TITLE#}
+ +
+
+ {#REQUEST_TIP#} +
+
+ + + +
+ + +
+
+
+ + {if $items} + + + + + + + + + + + + {foreach from=$items item=item} + + + + + + + + + + + + + + + + + + + + {/foreach} + {else} + + + + {/if} + +
{#REQUEST_ID#}{#REQUEST_NAME#}{#REQUEST_AUTHOR#}{#REQUEST_DATE_CREATE#}{#REQUEST_SYSTEM_TAG#}{#REQUEST_ACTIONS#}
{$item->Id} + {if check_permission('request_edit')} + + {$item->request_title|escape} + + {else} + {$item->request_title|escape} + {/if} + {if $item->request_description != ''} +
+ {$item->request_description|escape|default:#REQUEST_NO_DESCRIPTION#} + {/if} +
{$item->request_author|escape} + {$item->request_created|date_format:$TIME_FORMAT|pretty_date} + +
+ + + + +
+
+ {if check_permission('request_edit')} + + {else} + + {/if} + + {if check_permission('request_edit')} + + {else} + + {/if} + + {if check_permission('request_edit')} + + {else} + + {/if} + + {if check_permission('request_edit')} + + {else} + + {/if} +
+
    +
  • {#REQUEST_NO_REQUST#}
  • +
+
+
+ +
+ {if check_permission('request_edit')} + + {/if} +
+ +
+
+ +{literal} + +{/literal} + +{if $page_nav} + +{/if} \ No newline at end of file diff --git a/inc/query_variants/original_files/admin/templates/request/nav.tpl b/inc/query_variants/original_files/admin/templates/request/nav.tpl new file mode 100644 index 0000000..7754227 --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/nav.tpl @@ -0,0 +1 @@ +
  • {#MAIN_QUERIES#}
  • \ No newline at end of file diff --git a/inc/query_variants/original_files/admin/templates/request/request.tpl b/inc/query_variants/original_files/admin/templates/request/request.tpl new file mode 100644 index 0000000..033e69a --- /dev/null +++ b/inc/query_variants/original_files/admin/templates/request/request.tpl @@ -0,0 +1 @@ +for old request \ No newline at end of file diff --git a/inc/query_variants/original_files/class/class.request.php b/inc/query_variants/original_files/class/class.request.php new file mode 100644 index 0000000..01e6bd5 --- /dev/null +++ b/inc/query_variants/original_files/class/class.request.php @@ -0,0 +1,974 @@ +_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('rid', 0); + + // Получаем список запросов + $AVE_Template->assign('items', $this->_requestListGet()); + + // Передаем в шаблон и отображаем страницу со списком + $AVE_Template->assign('content', $AVE_Template->fetch('request/list.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_only_owner = (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0); + $row->request_cache_lifetime = (int)($_REQUEST['request_cache_lifetime']); + $row->request_lang = (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0); + $row->request_cache_elements = (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0); + $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_show_sql = (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0); + + 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_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_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_cache_lifetime = '" . (isset($_REQUEST['request_cache_lifetime']) ? (int)($_REQUEST['request_cache_lifetime']) : 0) . "', + request_lang = '" . (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0). "', + request_cache_elements = '" . (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0). "', + request_show_statistic = '" . (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0). "', + request_external = '" . (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0). "', + request_ajax = '" . (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0). "', + request_show_sql = '" . (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 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_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_only_owner = (isset($_REQUEST['request_only_owner']) ? (int)($_REQUEST['request_only_owner']) : 0); + $row->request_cache_lifetime = (isset($_REQUEST['request_cache_lifetime']) ? (int)($_REQUEST['request_cache_lifetime']) : 0); + $row->request_lang = (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0); + $row->request_cache_elements = (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0); + $row->request_show_statistic = (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0); + $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_show_sql = (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 0); + + $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_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_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_cache_lifetime = '" . (isset($_REQUEST['request_cache_lifetime']) ? (int)($_REQUEST['request_cache_lifetime']) : '-1') . "', + request_lang = '" . (isset($_REQUEST['request_lang']) ? (int)$_REQUEST['request_lang'] : 0). "', + request_cache_elements = '" . (isset($_REQUEST['request_cache_elements']) ? (int)$_REQUEST['request_cache_elements'] : 0). "', + request_show_statistic = '" . (isset($_REQUEST['request_show_statistic']) ? (int)$_REQUEST['request_show_statistic'] : 0). "', + request_external = '" . (isset($_REQUEST['request_external']) ? (int)$_REQUEST['request_external'] : 0). "', + request_ajax = '" . (isset($_REQUEST['request_ajax']) ? (int)$_REQUEST['request_ajax'] : 0). "', + request_show_sql = '" . (isset($_REQUEST['request_show_sql']) ? (int)$_REQUEST['request_show_sql'] : 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, $AVE_Template; + + // Выполняем запрос к БД на получение информации о копиреумом запросе + $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; + } + + $row = $sql->FetchRow(); + + // Выполняем запрос к БД на добавление нового запроса на основании полученных ранее данных + $AVE_DB->Query(" + INSERT " . PREFIX . "_request + SET + rubric_id = '" . (int)$row->rubric_id . "', + request_items_per_page = '" . $row->request_items_per_page . "', + request_title = '" . $_REQUEST['cname'] . "', + 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_use_query = '" . $row->request_use_query . "', + request_count_items = '" . $row->request_count_items . "', + request_hide_current = '" . $row->request_hide_current . "', + request_lang = '" . $row->request_lang . "', + request_cache_elements = '" . (isset($row->request_cache_elements) ? $row->request_cache_elements : 0) . "' + "); + + // Получаем id добавленной записи + $iid = $AVE_DB->InsertId(); + + // Сохраняем системное сообщение в журнал + reportLog($AVE_Template->get_config_vars('REQUEST_COPY_SUC') . ' (' . stripslashes(htmlspecialchars($this->get_request_by_id($request_id)->request_title, ENT_QUOTES)) . ') ( Id:'.$iid.' )'); + + // Выполняем запрос к БД и получаем все условия запроса для копируемого запроса + $sql = $AVE_DB->Query(" + SELECT * + FROM + " . PREFIX . "_request_conditions + WHERE + request_id = '" . $request_id . "' + "); + + // Обрабатываем полученные данные и + while ($row_cond = $sql->FetchRow()) + { + // Выполняем запрос к БД на добавление условий для нового, скопированного запроса + $AVE_DB->Query(" + INSERT + " . PREFIX . "_request_conditions + SET + request_id = '" . $iid . "', + condition_compare = '" . $row_cond->condition_compare . "', + condition_field_id = '" . $row_cond->condition_field_id . "', + condition_value = '" . $row_cond->condition_value . "', + condition_join = '" . $row_cond->condition_join . "' + "); + } + + // Выполянем переход к списку запросов + header('Location:index.php?do=request&cp=' . SESSION); + exit; + } + + + /** + * Метод, предназначенный для удаления запроса + * + * @param int $request_id идентификатор запроса + */ + function requestDelete($request_id) + { + global $AVE_DB, $AVE_Template; + + $request_name = $this->get_request_by_id($request_id)->request_title; + + // Выполняем запрос к БД на удаление общей информации о запросе + $AVE_DB->Query(" + DELETE FROM + " . PREFIX . "_request + WHERE + Id = '" . $request_id . "' + "); + + // Выполняем запрос к БД на удаление условий запроса + $AVE_DB->Query(" + DELETE FROM + " . PREFIX . "_request_conditions + WHERE + request_id = '" . $request_id . "' + "); + + $AVE_DB->clearRequest($request_id); + + // Сохраняем системное сообщение в журнал + reportLog($AVE_Template->get_config_vars('REQUEST_DELETE_SUC') . ' (' . stripslashes(htmlspecialchars($request_name, ENT_QUOTES)) . ') ( Id:' . $request_id . ' )'); + + // Выполянем переход к списку запросов + 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/original_files/functions/func.parserequest.php b/inc/query_variants/original_files/functions/func.parserequest.php new file mode 100644 index 0000000..8bf0404 --- /dev/null +++ b/inc/query_variants/original_files/functions/func.parserequest.php @@ -0,0 +1,1433 @@ +Query($sql, -1, 'rqs_' . $id, true, '.settings')->FetchRow(); + + // Выходим, если нет запроса + if (! is_object($reqest_settings)) + return ''; + else + return $reqest_settings; + } + + + /** + * Обработка условий запроса. + * Возвращает строку условий в SQL-формате + * + * @param int $id идентификатор запроса + * @param bool $update_db + * + * @return array + */ + function request_get_condition_sql_string ($id, $update_db = false) + { + global $AVE_DB, $AVE_Core; + + $id = (int)$id; + $from = []; + $where = []; + + $sql = " + SELECT + * + FROM + " . PREFIX . "_request_conditions + WHERE + request_id = '" . $id . "' + AND + condition_status = '1' + ORDER BY + condition_position ASC; + "; + + $request_settings = request_get_settings($id); + + $sql_ak = $AVE_DB->Query($sql, -1, 'rqc_' . $id, true, '.conditions'); + + // Обрабатываем выпадающие списки + + 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]; + } + + 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; + + $numeric = []; + + if (! defined('ACP')) + { + $query = " + SELECT + Id, + rubric_field_numeric + FROM + " . PREFIX . "_rubric_fields + WHERE + rubric_id = '". $request_settings->rubric_id."' + "; + + $sql = $AVE_DB->Query($query); + + while ($row = $sql->FetchAssocArray()) + $numeric[$row['Id']] = $row['rubric_field_numeric']; + } + + 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])) + { + $numeric[$fid] = (bool)$AVE_DB->Query(" + SELECT + rubric_field_numeric + FROM + " . PREFIX . "_rubric_fields + WHERE + Id = '" . $fid . "' + ")->GetCell(); + } + + $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'' && !isset(\$t[$fid])) {echo \"%%PREFIX%%_document_fields AS t$fid,\"; \$t[$fid]=1;} ?>"; + + // обрабатываем условия + switch ($type) + { + case 'N<':case '<': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv < UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + case 'N>':case '>': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv > UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + case 'N<=':case '<=': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv <= UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + case 'N>=':case '>=': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv >= UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + + case '==': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv = UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + case '!=': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv != UPPER('\$v[$i]'))) $join\" : '' ?>"; break; + case '%%': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('%\$v[$i]%'))) $join\" : '' ?>"; break; + case '%': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv LIKE UPPER('\$v[$i]%'))) $join\" : '' ?>"; break; + case '--': $where[] = "'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT LIKE UPPER('%\$v[$i]%'))) $join\" : '' ?>"; break; + case '!-': $where[] = "'' ? \"(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]{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]{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]{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]{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[] = " '' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv=ANY(\$v[$i]))) $join\" : ''; ?>"; break; + case 'FRE': $where[] = " '' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND (\$v[$i]))) $join\" : ''; ?>"; break; + } + + $i++; + } + + $retval = []; + + if (! empty($where) || ! empty($where_dd)) + { + 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 = ['from' => $from, 'where' => $where . $where_dd]; + } + else + { + $from = implode(' ', $from); + $where = implode(' ', $where) . " "; + $retval = ['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 = '" . $id . "' + "); + + $AVE_DB->clearRequest($id); + } + + return @$retval; + } + + + /** + * Функция обработки тэгов полей с использованием шаблонов + * в соответствии с типом поля + * + * @param $field_id + * @param int $document_id идентификатор документа + * @param string $maxlength максимальное количество символов обрабатываемого поля + * @param int $rubric_id идентификатор рубрики + * + * @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 = '') + { + global + $AVE_DB, + $req_item_num, + $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); // Создаем уникальный id для каждого набора параметров + $params_of_teaser[$tparams_id] = []; // Для отмены лишних ворнингов + $tparams = trim($tparams,'[]:'); // Удаляем: слева ':[', справа ']' + $params_of_teaser[$tparams_id] = explode('|',$tparams); // Заносим параметры в массив уникального id + } + + $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; // ID Запроса + $hash .= 't-' . $row->Id; // ID документа + + $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); + } + + // Если включен DEV MODE, то отключаем кеширование запросов + if (defined('DEV_MODE') AND DEV_MODE) + $cachefile_docid = null; + + if (! file_exists($cachefile_docid)) + { + // Если включено в настройках, проверять поле по содержимому + if (defined('USE_GET_FIELDS') && USE_GET_FIELDS) + { + $template = preg_replace("/\[tag:if_notempty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\', '.$row->Id.'), ENT_QUOTES)) != \'\') { '.'?'.'>', $template); + $template = preg_replace("/\[tag:if_empty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\', '.$row->Id.'), ENT_QUOTES)) == \'\') { '.'?'.'>', $template); + } + else + { + $template = preg_replace("/\[tag:if_notempty:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[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|strip|[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}+)(|:\{(.*?)\})\]/', + 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 != '') + { + // Заменяем tparam в тизере + $item = preg_replace_callback('/\[tparam:([0-9]+)\]/', + function ($m) use ($tparams_id) + { + return f_params_of_teaser($tparams_id, $m[1]); + }, + $item); + } + else + { + // Если чистый запрос тизера, просто вытираем 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: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 $id идентификатор запроса + * @param array $params + * + * @return string + */ + function request_parse ($id, $params = []) + { + global $AVE_Core, $AVE_DB, $request_documents; + + // Если id пришёл из тега, берём нужную часть массива + if (is_array($id)) + $id = $id[1]; + + $t = []; + $a = []; + $v = []; + + // Получаем информацию о запросе + $request = request_get_settings($id); + + // Фиксируем время начала генерации запроса + Debug::startTime('request_' . $id); + + // Массив для полей SELECT + $request_select = []; + // Массив для присоединения таблиц JOIN + $request_join = []; + // Массив для добавления условий WHERE + $request_where = []; + // Массив для сортировки результатов ORDER BY + $request_order = []; + // Массив для сортировки результатов ORDER BY + $request_order_fields = []; + + $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] = ""; + + // Если в сортировке указано 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'; + + // ToDo - ХЗ что это + $request_order[$sort] = "$fid " . $asc_desc; + } + } + } + // Сортировка по полю из настроек (только если не передана другая в параметрах) + elseif ($request->request_order_by_nat) + { + $fid = (int)$request->request_order_by_nat; + + // Добавляем с учётом переменной $t из условий, чтобы не выбирать те же таблиы заново - это оптимизирует время + $request_join[$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 (! $request->request_where_cond) + $where_cond = request_get_condition_sql_string($request->Id, false); + // иначе, берём из запроса + 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('page') * $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); + + if (! isset($params['SQL_QUERY'])) + { + // Составляем запрос к БД + $sql = " ?> + SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS + #REQUEST = $request->Id + a.Id + " . $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 . " + 0) + { + $sql_request = str_replace($search, '', $sql_request); + } + } + } + else + { + $sql_request = $params['SQL_QUERY']; + } + + // Если просили просто показать сформированный запрос + if ((isset($params['DEBUG']) && $params['DEBUG'] == 1) || $request->request_show_sql == 1) + { + $return = Debug::_print($sql_request); + + return $return; + } + + Debug::startTime('SQL'); + + // Выполняем запрос к бд + $sql = $AVE_DB->Query($sql_request, (int)$request->request_cache_lifetime, 'rqs_' . $id, true, '.request'); + + $GLOBALS['block_generate']['REQUESTS'][$id]['SQL'] = Debug::endTime('SQL'); + + // Если просили просто вернуть резльтат запроса, возвращаем результат + 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, 'rqs_' . $id); + else + $num_items = ((isset($params['NO_FOUND_ROWS']) && $params['NO_FOUND_ROWS'] == 1) || ! $request->request_count_items + ? 0 + : $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['page']) && is_numeric($_REQUEST['page']) && $_REQUEST['page'] > $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['apage']) && is_numeric($_REQUEST['apage'])) + ? '&apage=' . $_REQUEST['apage'] + : '')); + + header('Location:' . $redirect_link); + exit; + } + + // Запоминаем глобально + @$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); + + $pagination = ''; + + // Если кол-во страниц больше 1й + 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) + + . '&page={s}' + + . ((isset($_REQUEST['artpage']) && is_numeric($_REQUEST['artpage'])) + ? '&artpage=' . $_REQUEST['artpage'] + : '') + + . ((isset($_REQUEST['apage']) && is_numeric($_REQUEST['apage'])) + ? '&apage=' . $_REQUEST['apage'] + : '') + + // Добавляем GET-запрос в пагинацию + . clean_php($queries) + ; + + // ID пагинации + $pagination_id = (isset($params['PAGINATION']) && $params['PAGINATION'] > 0) + ? $params['PAGINATION'] + : $request->request_pagination; + + // Собираем пагинацию + $pagination = AVE_Paginations::getPagination($num_pages, 'page', $pagination, $pagination_id); + + // Костыли для Главной страницы + $pagination = str_ireplace('"//"', '"/"', str_ireplace('///', '/', rewrite_link($pagination))); + $pagination = str_ireplace('"//' . URL_SUFF . '"', '"/"', $pagination); + } + } + + // Элементы запроса + $rows = []; + + // id найденных документов + $request_documents = []; + + 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, $request_id, $request_changed, $request_changed_elements; + + $use_cache = $request->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 ? true : false); + $item_num = $x; + $req_item_num = $item_num; + + Debug::startTime('ELEMENT_' . $item_num); + + $item = showrequestelement($row->Id, $request->request_template_item); + + $GLOBALS['block_generate']['REQUESTS'][$id]['ELEMENTS'][$item_num] = Debug::endTime('ELEMENT_' . $item_num); + + $item = str_replace('[tag:item_num]', $item_num, $item); + $item = '<'.'?php $item_num='.var_export($item_num,1).'; $last_item='.var_export($last_item,1).'?'.'>'.$item; + $item = '<'.'?php $req_item_id = ' . $row->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; + + Registry::remove('documents', $row->Id); + Registry::remove('fields', $row->Id); + Registry::remove('fields_param', $row->Id); + } + + $GLOBALS['block_generate']['REQUESTS'][$id]['ELEMENTS']['ALL'] = Debug::endTime('ELEMENTS_ALL'); + + // ============ Обрабатываем теги запроса ============ // + + //-- Парсим теги визуальных блоков + $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 = 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 + ); + + $str_replace = [ + //-- ID Документа + '[tag:docid]' => $AVE_Core->curentdoc->Id, + //-- ID Автора + '[tag:docauthorid]' => $AVE_Core->curentdoc->document_author_id, + //-- Имя автора + '[tag:docauthor]' => get_username_by_id($AVE_Core->curentdoc->document_author_id), + //-- Время - 1 день назад + '[tag:humandate]' => human_date($AVE_Core->curentdoc->document_published), + //-- Дата создания + '[tag:docdate]' => pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), + //-- Время создания + '[tag:doctime]' => pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), + //-- Домен + '[tag:domain]' => getSiteUrl(), + //-- Заменяем тег пагинации на пагинацию + '[tag:pages]' => $pagination, + //-- Общее число элементов запроса + '[tag:doctotal]' => $num_items, + //-- Показано элементов запроса на странице + '[tag:doconpage]' => $x, + //-- Номер страницы пагинации + '[tag:pages:curent]' => get_current_page('page'), + //-- Общее кол-во страниц пагинации + '[tag:pages:total]' => $num_pages, + //-- Title + '[tag:pagetitle]' => stripslashes(htmlspecialchars_decode($AVE_Core->curentdoc->document_title)), + //-- Alias + '[tag:alias]' => (isset($AVE_Core->curentdoc->document_alias) ? $AVE_Core->curentdoc->document_alias : '') + ]; + + $main_template = str_replace(array_keys($str_replace), array_values($str_replace), $main_template); + + //-- Возвращаем параметр документа из БД + $main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u', + function ($match) use ($row) + { + 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); + + unset ($items, $main_template, $str_replace, $pagination); + + //-- Парсим тег [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']['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; + } + + + + function parse_request ($id, $params = []) + { + global $AVE_Core; + + // Получаем информацию о запросе + $request = request_get_settings($id); + + // Фиксируем время начала генерации запроса + Debug::startTime('request_' . $id); + + // Элементы запроса + $rows = $params['ROWS']; + + //-- Обрабатываем шаблоны элементов + $items = ''; + + //-- Счетчик + $x = 0; + + //-- Общее число элементов + $items_count = $num_items= count($rows); + + global $req_item_num, $use_cache, $request_id, $request_changed, $request_changed_elements; + + $use_cache = $request->request_cache_elements; + + $request_id = $request->Id; + + $request_changed = $request->request_changed; + $request_changed_elements = $request->request_changed_elements; + + $limit = (isset($params['LIMIT']) && is_numeric($params['LIMIT']) && $params['LIMIT'] > '') + ? (int)$params['LIMIT'] + : (int)$request->request_items_per_page; + + // Кол-во страниц + $num_pages = ($limit > 0) + ? ceil($num_items / $limit) + : 0; + + Debug::startTime('ELEMENTS_ALL'); + + foreach ($rows AS $row) + { + $x++; + $last_item = ($x == $items_count ? true : false); + $item_num = $x; + $req_item_num = $item_num; + + Debug::startTime('ELEMENT_' . $item_num); + + $item = showrequestelement($row, $request->request_template_item); + + $GLOBALS['block_generate']['REQUESTS'][$id]['ELEMENTS'][$item_num] = Debug::endTime('ELEMENT_' . $item_num); + + $item = str_replace('[tag:item_num]', $item_num, $item); + $item = '<'.'?php $item_num='.var_export($item_num,1).'; $last_item='.var_export($last_item,1).'?'.'>'.$item; + $item = '<'.'?php $req_item_id = ' . $row . '; ?>' . $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; + + Registry::remove('documents', $row); + Registry::remove('fields', $row); + Registry::remove('fields_param', $row); + } + + $GLOBALS['block_generate']['REQUESTS'][$id]['ELEMENTS']['ALL'] = Debug::endTime('ELEMENTS_ALL'); + + // Приступаем к обработке шаблона + $main_template = $request->request_template_main; + + // ============ Обрабатываем теги запроса ============ // + + //-- Парсим теги визуальных блоков + $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 = 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 + ); + + $str_replace = [ + //-- ID Документа + '[tag:docid]' => $AVE_Core->curentdoc->Id, + //-- ID Автора + '[tag:docauthorid]' => $AVE_Core->curentdoc->document_author_id, + //-- Имя автора + '[tag:docauthor]' => get_username_by_id($AVE_Core->curentdoc->document_author_id), + //-- Время - 1 день назад + '[tag:humandate]' => human_date($AVE_Core->curentdoc->document_published), + //-- Дата создания + '[tag:docdate]' => pretty_date(strftime(DATE_FORMAT, $AVE_Core->curentdoc->document_published)), + //-- Время создания + '[tag:doctime]' => pretty_date(strftime(TIME_FORMAT, $AVE_Core->curentdoc->document_published)), + //-- Домен + '[tag:domain]' => getSiteUrl(), + //-- Заменяем тег пагинации на пагинацию + '[tag:pages]' => $pagination, + //-- Общее число элементов запроса + '[tag:doctotal]' => $num_items, + //-- Показано элементов запроса на странице + '[tag:doconpage]' => $x, + //-- Номер страницы пагинации + '[tag:pages:curent]' => get_current_page('page'), + //-- Общее кол-во страниц пагинации + '[tag:pages:total]' => $num_pages, + //-- Title + '[tag:pagetitle]' => stripslashes(htmlspecialchars_decode($AVE_Core->curentdoc->document_title)), + //-- Alias + '[tag:alias]' => (isset($AVE_Core->curentdoc->document_alias) ? $AVE_Core->curentdoc->document_alias : '') + ]; + + $main_template = str_replace(array_keys($str_replace), array_values($str_replace), $main_template); + + //-- Возвращаем параметр документа из БД + $main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u', + function ($match) use ($row) + { + 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); + + unset ($items, $main_template, $str_replace, $pagination); + + //-- Парсим тег [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']['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/' . ((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 == ''} +

    +{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} + + {foreach name=cond from=$conditions item=condition} + + + + + + + + + + + + + + {/foreach} + + {else} + + + + {/if} + +
    {#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
    condition_status ==1}checked{/if} class="toprightDir float" /> + {foreach from=$fields_list item=field_group} + + {foreach from=$field_group.fields item=field} + {if $condition->condition_field_id == $field.Id} + + {/if} + {/foreach} + + {/foreach} + + + + +
    +
      +
    • {#REQUEST_COND_MESSAGE#}
    • +
    +
    + + {if $conditions} +
    + + + {#REQUEST_OR#} +   + {if $smarty.request.pop} + + {/if} +
    +
    + {/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#}
    +
    + +
    +
    + {#REQUEST_CONDITION_TIP#} +
    +
    + + + +
    + +
    + +
    +
    {#REQUEST_NEW_CONDITION#}
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    {#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
    + + + + + + +
    +
    + +
    +
    +
    +
    + +
    +
    +
    {#REQUEST_CONDITION#}
    + {if !$smarty.request.pop} + + {/if} +
    + +
    + + + + + + + + + + + + + + + + + + + + + + {if $conditions} + + {foreach name=cond from=$conditions item=condition} + + + + + + + + + + + + + {/foreach} + + {else} + + + + {/if} + +
    {#REQUEST_FROM_FILED#}{#REQUEST_OPERATOR#}{#REQUEST_CONDITION_JOIN#}{#REQUEST_VALUE#}
    condition_status ==1}checked{/if} class="toprightDir float"/> + + {foreach from=$fields_list item=field_group} + + {foreach from=$field_group.fields item=field} + {if $condition->condition_field_id == $field.Id} + + {/if} + {/foreach} + + {/foreach} + + + + + +
    +
      +
    • {#REQUEST_COND_MESSAGE#}
    • +
    +
    + {if $conditions} +
    +
    + + {#REQUEST_OR#} +   + {if $smarty.request.pop} + + {/if} +
    +
    + {/if} + +
    + +
    +
    + +
    + + \ 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'} +
    +
    {#REQUEST_EDIT2#}
    + +
    +
    +
    {#REQUEST_EDIT_TIP#}
    +
    +{else} +
    +
    {#REQUEST_NEW#}
    +
    +
    +
    {#REQUEST_NEW_TIP#}
    +
    +{/if} + + + +{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} + + +
    + + + + +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {if $row->request_external == '1'} + + + + {/if} + +
    {#REQUEST_HEADER_SELF#}
    {#REQUEST_NAME2#}
    +
    + [?] {#REQUEST_ALIAS#}: +
    +
    +
    +   + + + + +
    +
    {#REQUEST_CACHE#}{#REQUEST_CACHE_ELEMENTS#}request_cache_elements}checked="checked"{/if}/>
    {#REQUEST_SELECT_RUBRIK#} + + +
    {#REQUEST_DESCRIPTION#}
    {#REQUEST_INTERNAL_INFO#}
    {#REQUEST_CONDITION#} + {if $iframe == 'no'} + + {/if} + {if $iframe != 'no'} + {#REQUEST_BUTTON_COND#} + {/if} +
    {#REQUEST_HEADER_NAME#}{#REQUEST_HEADER_PARAMETR#}{#REQUEST_HEADER_NAME#}{#REQUEST_HEADER_PARAMETR#}
    {#REQUEST_HIDE_CURRENT#}request_hide_current}checked="checked"{/if}/>{#REQUEST_ONLY_OWNER#}request_only_owner}checked="checked"{/if}/>
    +
    + [?] {#REQUEST_SORT_BY#}: +
    +
    + + +
    + [?] {#REQUEST_SORT_BY_NAT#}: +
    +
    + +
    {#REQUEST_ASC_DESC#} + + {#REQUEST_DOC_PER_PAGE#} + +
    {#REQUEST_PAGINATION#}
    {#REQUEST_SHOW_NAVI#}request_show_pagination=='1'} checked="checked"{/if} />{#REQUEST_NAVI_TPL#} + +
    {#REQUEST_COUNT_ITEMS#}request_count_items == '1'} checked="checked"{/if} />{#REQUEST_USE_QUERY#}request_use_query == '1'} checked="checked"{/if} />
    {#REQUEST_OTHER#}
    {#REQUEST_USE_LANG#}request_lang == '1'} checked="checked"{/if} />
    {#REQUEST_SHOW_STAT#}request_show_statistic == '1'} checked="checked"{/if} />{#REQUEST_SHOW_SQL#}request_show_sql == '1'} checked="checked"{/if} />
    {#REQUEST_HEADER_EXTERNAL#}
    +
    + [?] {#REQUEST_EXTERNAL#} +
    +
    request_external == '1'} checked="checked"{/if} />{#REQUEST_ONLY_AJAX#}request_ajax == '1'} checked="checked"{/if} />
    + +
    +
    +
    + + + + + +
    +
    +
    +
    + {if $smarty.request.action=='edit'} + + {else} + + {/if} + {#REQUEST_OR#} + {if $smarty.request.action=='edit'} + + {else} + + {/if} + {#REQUEST_CANCEL#} +
    +
    + +
    + + +
    + + + +
    + +{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#}
    + +
    +
    + {#REQUEST_TIP#} +
    +
    + + +
    + +
    +
    +
    + + {if $items} + + + + + + + + + + + + {foreach from=$items item=item} + + + + + + + + + + + + + + + + + + {/foreach} {else} + + + + {/if} + +
    {#REQUEST_ID#}{#REQUEST_NAME#}{#REQUEST_AUTHOR#}{#REQUEST_DATE_CREATE#}{#REQUEST_SYSTEM_TAG#}{#REQUEST_ACTIONS#}
    {$item->Id} + {if check_permission('request_edit')} + + {$item->request_title|escape} + + {else} + {$item->request_title|escape} + {/if} {if $item->request_description != ''} +
    + {$item->request_description|escape|default:#REQUEST_NO_DESCRIPTION#} {/if} +
    {$item->request_author|escape} + {$item->request_created|date_format:$TIME_FORMAT|pretty_date} + +
    + + + + +
    +
    + {if check_permission('request_edit')} + + {else} + + {/if} + + {if check_permission('request_edit')} + + {else} + + {/if} + + {if check_permission('request_new')} + + {else} + + {/if} + + {if check_permission('request_del')} + + {else} + + {/if} +
    +
      +
    • {#REQUEST_NO_REQUST#}
    • +
    +
    +
    +
    + + {if check_permission('request_new')} + + + + {/if} +
    +
    +
    + +{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 @@ +

    + + +{foreach from=$ctrlrequest item=items key=selname} + +{/foreach} + + +
    + + +
    + \ 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