Browse Source

Fixes

master
M@d D3n 6 years ago
parent
commit
543966f737
  1. 34
      .htaccess
  2. 29
      README.md
  3. 164
      admin/functions/func.admin.common.php
  4. 4
      admin/templates/rubs/form.tpl
  5. 2
      admin/templates/sysblocks/list.tpl
  6. 92
      class/class.core.php
  7. 425
      class/class.debug.php
  8. 30
      class/class.meta.php
  9. 5
      class/class.modules.php
  10. 246
      class/class.session.php
  11. 170
      class/class.utm.php
  12. 163
      fields/checkbox_multi/field.php
  13. 163
      fields/multi_checkbox/field.php
  14. 0
      fields/multi_checkbox/lang/bg.txt
  15. 0
      fields/multi_checkbox/lang/cz.txt
  16. 0
      fields/multi_checkbox/lang/en.txt
  17. 0
      fields/multi_checkbox/lang/pl.txt
  18. 0
      fields/multi_checkbox/lang/ru.txt
  19. 0
      fields/multi_checkbox/lang/ua.txt
  20. 0
      fields/multi_checkbox/tpl/field-doc.tpl
  21. 0
      fields/multi_checkbox/tpl/field-req.tpl
  22. 0
      fields/multi_checkbox/tpl/field.tpl
  23. 463
      fields/tags/field.php
  24. 6
      functions/func.block.php
  25. 6
      functions/func.breadcrumbs.php
  26. 104
      functions/func.common.php
  27. 4
      functions/func.documents.php
  28. 36
      functions/func.fields.php
  29. 1421
      functions/func.helpers.php
  30. 6
      functions/func.login.php
  31. 390
      functions/func.mail.php
  32. 119
      functions/func.modulglobals.php
  33. 2
      functions/func.navigation.php
  34. 230
      functions/func.pagination.php
  35. 197
      functions/func.parserequest.php
  36. 8
      functions/func.sysblock.php
  37. 6
      functions/func.thumbnails.php
  38. 412
      functions/func.users.php
  39. 4
      functions/func.watermarks.php
  40. 12
      inc/init.php
  41. 1
      install/data_base.sql

34
.htaccess

@ -11,7 +11,6 @@ Options -Indexes +FollowSymLinks
# | PHP Configuration | # | PHP Configuration |
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
<ifModule mod_php5.c>
php_value default_charset utf-8 php_value default_charset utf-8
#Отлючаем вывод ошибок #Отлючаем вывод ошибок
@ -40,39 +39,6 @@ Options -Indexes +FollowSymLinks
php_flag magic_quotes_runtime off php_flag magic_quotes_runtime off
php_flag register_globals off php_flag register_globals off
</ifModule>
<ifModule !mod_php5.c>
php_value default_charset utf-8
#Отлючаем вывод ошибок
#php_value error_reporting E_NONE
# Этот параметр устанавливает максимальное время в секундах, позволяющее скрипту запускаться прежде, чем он завершается синтаксическим анализатором.
#php_value max_execution_time 300
# Максимальное время загрузки данных для скрипта, в том числе и файлов из формы
#php_value max_input_time 300
# Ограничивает максимальный объем данных, получаемых от пользователя методом POST
#php_value post_max_size 32M
# Устанавливает максимальный размер файла, который может быть получен методом POST (меньше, чем post_max_size)
#php_value upload_max_filesize 32M
# Максимальное кол-во загружаемых файлов
#php_value max_file_uploads 50
# Включаем у PHP короткие <?
#php_value short_open_tag On
php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off
php_flag register_globals off
</ifModule>
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# | CORS-enabled images | # | CORS-enabled images |

29
README.md

@ -5,8 +5,6 @@
* [Системные требования](#Системные-требования) * [Системные требования](#Системные-требования)
* [Модули](#Модули)
* [Установка](#Установка) * [Установка](#Установка)
* [Ресурсы](#Ресурсы) * [Ресурсы](#Ресурсы)
@ -21,34 +19,9 @@
* ПО WEB сервера: * ПО WEB сервера:
* Apache >= 1.3 * Apache >= 1.3
* Nginx >= 1.6.2 * Nginx >= 1.6.2
* PHP >= 5.6.x разрешить использовать короткие теги short_open_tag = On (zlib, cURL, mbString, JSON) * PHP >= 5.6.x (zlib, cURL, mbString, JSON)
* PHP >= 7.x ... <= 7.2.x * PHP >= 7.x ... <= 7.2.x
## Модули
Описание и загрузка модулей
| Наименование | Описание |
|---------------------------------|-----------------------------|
| [Комментарии] | Система комментирования публикаций. |
| [Контактные формы] | Модуль предназначен для создания различных веб-форм для контактов.Поддержка различных типов полей. |
| [Публикатор документов] | Данный модуль предназначен для создания форм ввода и редактирования документов на сайте. |
| [Вопрос-Ответ (FAQ)] | Модуль создания раширенной справочной системы на основе тегов. |
| [Галерея] | Модуль для создания и управления галереями изображений. |
| [Авторизация] | Модуль поддержки Регистрации/Авторизации пользователей. |
| [Рассылки] | Модуль позволяет осуществлять рассылки новостей и другой информации пользователям. |
| [Похожие документы] | Модуль позволяет выводить список связанных документов *(Связующим элементом документов является первое слово из поля Ключевые слова.)* |
| [Быстрый переход] | Данный модуль является альтернативным способом организации меню навигации на сайте. Он представлен в виде выпадающего списка разделов и подразделов вашего сайта. |
| [RSS] | Данный модуль предзназначен для организации RSS потоков на вашем сайте. |
| [Поиск] | Организация поиска по сайту. |
| [Карта сайта] | Построение карты сайта на базе пунктов меню навигации. |
| [Корзина] | Модуль электронной комерции. |
| [Импорт] | Импорт документов в выбранную рубрику. |
| [Рейтинг документов] | Поддержка оценок для публикаций. |
| [Навигация по документам рубрики] | Данный модуль позволяет организовать навигацию по документам в пределах рубрики. |
И другие
## Установка ## Установка
1. Распакуйте содержимое архива в новую папку на вашем локальном компьютере. 1. Распакуйте содержимое архива в новую папку на вашем локальном компьютере.

164
admin/functions/func.admin.common.php

@ -12,23 +12,32 @@
/** /**
* Если был referer, то перенапрявляем на него * Если был referer, то перенапрявляем на него
* *
* @param * @return mixed|null|string $link
* @return $link
*/ */
function get_referer_admin_link() function get_referer_admin_link()
{ {
static $link = null; static $link = null;
$ok = false;
if ($link === null) if ($link === null)
{ {
if (isset($_SERVER['HTTP_REFERER'])) if (isset($_SERVER['HTTP_REFERER']))
{ {
$link = parse_url($_SERVER['HTTP_REFERER']); $link = parse_url($_SERVER['HTTP_REFERER']);
$ok = (trim($link['host']) == $_SERVER['HTTP_HOST']) ? true : false;
$ok = (trim($link['path']) != '/admin/admin.php') ? true : false;
$ok = (trim($link['host']) == $_SERVER['HTTP_HOST'])
? true
: false;
$ok = (trim($link['path']) != '/admin/admin.php')
? true
: false;
} }
$link = ($ok === true ? $_SERVER['HTTP_REFERER'] : '/admin/index.php');
$link = ($ok === true
? $_SERVER['HTTP_REFERER']
: '/admin/index.php');
} }
return $link; return $link;
@ -38,11 +47,11 @@
/** /**
* Получаем кол-во записей в журналах событий * Получаем кол-во записей в журналах событий
* *
* @return Array массив из кол-ва записей * @return void массив из кол-ва записей
*/ */
function getLogRecords() function getLogRecords()
{ {
global $AVE_DB, $AVE_Template; global $AVE_Template;
$logs = array(); $logs = array();
$logdata = array(); $logdata = array();
@ -54,17 +63,17 @@
$_sqldir = BASE_DIR . '/tmp/logs/sql.php'; $_sqldir = BASE_DIR . '/tmp/logs/sql.php';
if (file_exists($_logdir)) if (file_exists($_logdir))
@eval(' ?>' . file_get_contents($_logdir) . '<?php '); @eval(' ?>' . file_get_contents($_logdir) . '<?'.'php ');
$logs['logs'] = count($logdata); $logs['logs'] = count($logdata);
if (file_exists($_404dir)) if (file_exists($_404dir))
@eval(' ?>' . file_get_contents($_404dir) . '<?php '); @eval(' ?>' . file_get_contents($_404dir) . '<?'.'php ');
$logs['404'] = count($log404); $logs['404'] = count($log404);
if (file_exists($_sqldir)) if (file_exists($_sqldir))
@eval(' ?>' . file_get_contents($_sqldir) . '<?php '); @eval(' ?>' . file_get_contents($_sqldir) . '<?'.'php ');
$logs['sql'] = count($logsql); $logs['sql'] = count($logsql);
@ -81,17 +90,18 @@
* Список пользователей за последние $onlinetime секунд * Список пользователей за последние $onlinetime секунд
* *
* @param int $onlinetime количество секунд * @param int $onlinetime количество секунд
* @return Array массив из пользователей отсортированный по последней активности *
* @return void массив из пользователей отсортированный по последней активности
*/ */
function get_online_users($onlinetime = USERS_TIME_SHOW) function get_online_users($onlinetime = USERS_TIME_SHOW)
{ {
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$time=(time()-intval($onlinetime)); $time = (time() - intval($onlinetime));
$sql=@$AVE_DB->Query("SELECT * FROM ".PREFIX."_users WHERE last_visit>".$time." ORDER BY last_visit DESC"); $sql = @$AVE_DB->Query("SELECT * FROM " . PREFIX . "_users WHERE last_visit > " . $time . " ORDER BY last_visit DESC");
$online_users=Array(); $online_users = array();
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
@ -124,6 +134,7 @@
return $file_size; return $file_size;
} }
/** /**
* Извлечение из БД статистики по основным компонентам системы * Извлечение из БД статистики по основным компонентам системы
* *
@ -187,7 +198,8 @@
*/ */
function get_dir_size($directory) function get_dir_size($directory)
{ {
if (!is_dir($directory)) return -1; if (! is_dir($directory))
return -1;
$size = 0; $size = 0;
@ -402,7 +414,7 @@
function file_download($filename, $retbytes = true) function file_download($filename, $retbytes = true)
{ {
$chunksize = 1*(1024*1024); $chunksize = 1 * (1024 * 1024);
$buffer = ''; $buffer = '';
$cnt = 0; $cnt = 0;
@ -411,7 +423,7 @@
if ($handle === false) if ($handle === false)
return false; return false;
while (!feof($handle)) while (! feof($handle))
{ {
$buffer = fread($handle, $chunksize); $buffer = fread($handle, $chunksize);
@ -425,7 +437,8 @@
$status = fclose($handle); $status = fclose($handle);
if ($retbytes && $status) return $cnt; if ($retbytes && $status)
return $cnt;
return $status; return $status;
} }
@ -468,16 +481,20 @@
//Проверка на наличие модуля Контакты и новых писем //Проверка на наличие модуля Контакты и новых писем
function ContactsModuleCheck() { function ContactsModuleCheck()
{
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_module WHERE ModuleFunction = 'contact' and ModuleStatus = '1'"); $sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_module WHERE ModuleFunction = 'contact' and ModuleStatus = '1'");
$enable = $sql->numrows(); $enable = $sql->NumRows();
if ($enable != "0" || $enable != ""){ if ($enable != "0" || $enable != "")
{
$contacts = "1"; $contacts = "1";
$sql_num = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_contact_info WHERE Aw_Zeit = '0'"); $sql_num = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_modul_contact_info WHERE Aw_Zeit = '0'");
$num_posts = $sql_num->numrows(); $num_posts = $sql_num->NumRows();
} else { }
else
{
$contacts = "0"; $contacts = "0";
} }
$AVE_Template->assign('num_posts', $num_posts); $AVE_Template->assign('num_posts', $num_posts);
@ -486,21 +503,26 @@
//Проверка на наличие модуля Логин //Проверка на наличие модуля Логин
function LoginModuleCheck() { function LoginModuleCheck()
{
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_module WHERE ModuleFunction = 'mod_login' and ModuleStatus = '1'"); $sql = $AVE_DB->Query("SELECT * FROM " . PREFIX . "_module WHERE ModuleFunction = 'mod_login' and ModuleStatus = '1'");
$enable = $sql->numrows();
if ($enable != "0" || $enable != ""){ $enable = $sql->NumRows();
$login_menu = "1";
} else { if ($enable != '0' || $enable != '')
$login_menu = "0"; $login_menu = '1';
} else
$login_menu = '0';
$AVE_Template->assign('login_menu', $login_menu); $AVE_Template->assign('login_menu', $login_menu);
} }
//Выводим на главную список последних 15 документов /**
* Выводим на главную список последних 15 документов
*/
function DisplayMainDocuments() function DisplayMainDocuments()
{ {
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
@ -516,31 +538,31 @@
WHERE 1 = 1 WHERE 1 = 1
AND rub.rubric_docs_active = '1' AND rub.rubric_docs_active = '1'
ORDER BY doc.document_published DESC LIMIT 0,10"); ORDER BY doc.document_published DESC LIMIT 0,10");
while($row = $sql->fetchrow()) { while($row = $sql->FetchRow()) {
$row->rubric_title = showrubricName($row->rubric_id); $row->rubric_title = showrubricName($row->rubric_id);
$row->document_title = stripslashes(htmlspecialchars_decode(pretty_chars($row->document_title))); $row->document_title = stripslashes(htmlspecialchars_decode(pretty_chars($row->document_title)));
$row->document_breadcrum_title = stripslashes(htmlspecialchars_decode(pretty_chars($row->document_breadcrum_title))); $row->document_breadcrum_title = stripslashes(htmlspecialchars_decode(pretty_chars($row->document_breadcrum_title)));
$row->document_author = get_username_by_id($row->document_author_id); // Получаем имя пользователя (Автора) $row->document_author = get_username_by_id($row->document_author_id); // Получаем имя пользователя (Автора)
$row->cantEdit = 0; $row->cantEdit = 0;
$row->canDelete = 0; $row->canDelete = 0;
$row->canEndDel = 0; $row->canEndDel = 0;
$row->canOpenClose = 0; $row->canOpenClose = 0;
$row->rubric_admin_teaser_template = @eval2var(' ?>'.($row->rubric_admin_teaser_template > '' $row->rubric_admin_teaser_template = @eval2var(' ?>'.($row->rubric_admin_teaser_template > ''
? @showrequestelement($row, $row->rubric_admin_teaser_template) ? @showrequestelement($row, $row->rubric_admin_teaser_template)
: '').'<?php '); : '') . '<?'.'php ');
// разрешаем редактирование и удаление // разрешаем редактирование и удаление
// если автор имеет право изменять свои документы в рубрике // если автор имеет право изменять свои документы в рубрике
// или пользователю разрешено изменять все документы в рубрике // или пользователю разрешено изменять все документы в рубрике
if ( ($row->document_author_id == @$_SESSION['user_id'] if (($row->document_author_id == @$_SESSION['user_id']
&& isset($_SESSION[$row->rubric_id . '_editown']) && @$_SESSION[$row->rubric_id . '_editown'] == 1) && isset($_SESSION[$row->rubric_id . '_editown']) && @$_SESSION[$row->rubric_id . '_editown'] == 1)
|| (isset($_SESSION[$row->rubric_id . '_editall']) && $_SESSION[$row->rubric_id . '_editall'] == 1) ) || (isset($_SESSION[$row->rubric_id . '_editall']) && $_SESSION[$row->rubric_id . '_editall'] == 1))
{ {
$row->cantEdit = 1; $row->cantEdit = 1;
$row->canDelete = 1; $row->canDelete = 1;
} }
// запрещаем редактирование главной страницы и страницу ошибки 404 если требуется одобрение Администратора // запрещаем редактирование главной страницы и страницу ошибки 404 если требуется одобрение Администратора
if ( ($row->Id == 1 || $row->Id == PAGE_NOT_FOUND_ID) if (($row->Id == 1 || $row->Id == PAGE_NOT_FOUND_ID)
&& isset($_SESSION[$row->rubric_id . '_newnow']) && @$_SESSION[$row->rubric_id . '_newnow'] != 1) && isset($_SESSION[$row->rubric_id . '_newnow']) && @$_SESSION[$row->rubric_id . '_newnow'] != 1)
{ {
$row->cantEdit = 0; $row->cantEdit = 0;
@ -570,57 +592,93 @@
$AVE_Template->assign('doc_start', $doc_start); $AVE_Template->assign('doc_start', $doc_start);
} }
/**
* @param $id
*
* @return mixed
*/
function showrubricName($id) function showrubricName($id)
{ {
global $AVE_DB; global $AVE_DB;
$sql = $AVE_DB->Query("SELECT rubric_title FROM " . PREFIX . "_rubrics WHERE Id='$id'"); $sql = $AVE_DB->Query("SELECT rubric_title FROM " . PREFIX . "_rubrics WHERE Id = '$id'");
$row = $sql->fetchrow(); $row = $sql->FetchRow();
return $row->rubric_title; return $row->rubric_title;
} }
/**
* @param $id
*
* @return mixed
*/
function showuserName($id) function showuserName($id)
{ {
global $AVE_DB; global $AVE_DB;
$sql = $AVE_DB->Query("SELECT user_name FROM " . PREFIX . "_users WHERE Id='$id'"); $sql = $AVE_DB->Query("SELECT user_name FROM " . PREFIX . "_users WHERE Id = '$id'");
$row = $sql->fetchrow(); $row = $sql->FetchRow();
return $row->user_name; return $row->user_name;
} }
/**
*
*/
function cacheShow() function cacheShow()
{ {
global $AVE_Template; global $AVE_Template;
$showCache = format_size(get_dir_size($AVE_Template->cache_dir_root)); $showCache = format_size(get_dir_size($AVE_Template->cache_dir_root));
echo json_encode(array($showCache, 'accept')); echo json_encode(array($showCache, 'accept'));
} }
/**
* @param $id
*
* @return mixed
*/
function templateName($id) function templateName($id)
{ {
global $AVE_DB; global $AVE_DB;
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
SELECT * FROM " . PREFIX . "_templates SELECT
WHERE Id = '$id' *
"); FROM
$row = $sql->fetchrow(); " . PREFIX . "_templates
WHERE
Id = '$id'
");
$row = $sql->FetchRow();
return $row->template_title; return $row->template_title;
} }
/**
* @param $id
*
* @return mixed
*/
function groupName($id) function groupName($id)
{ {
global $AVE_DB; global $AVE_DB;
$sql = $AVE_DB->Query(" $sql = $AVE_DB->Query("
SELECT * FROM " . PREFIX . "_user_groups SELECT
WHERE user_group = '$id' *
"); FROM
$row = $sql->fetchrow(); " . PREFIX . "_user_groups
WHERE
user_group = '$id'
");
$row = $sql->FetchRow();
return $row->user_group_name; return $row->user_group_name;
} }

4
admin/templates/rubs/form.tpl

@ -599,11 +599,11 @@
<strong>{$field.rubric_field_title}</strong> <strong>{$field.rubric_field_title}</strong>
</td> </td>
<td> <td>
<a class="rightDir" title="{#RUBRIK_INSERT_HELP#}" href="javascript:void(0);" onclick="textSelection2('[tag:rfld:{$field.Id}][0]', '');"><strong>[tag:rfld:{$field.Id}][150]</strong></a> <a class="rightDir" title="{#RUBRIK_INSERT_HELP#}" href="javascript:void(0);" onclick="textSelection2_1('[tag:rfld:{$field.Id}][0]', '');"><strong>[tag:rfld:{$field.Id}][150]</strong></a>
</td> </td>
<td> <td>
{if $field.rubric_field_alias} {if $field.rubric_field_alias}
<a class="rightDir" title="{#RUBRIK_INSERT_HELP#}" href="javascript:void(0);" onclick="textSelection2('[tag:rfld:{$field.rubric_field_alias}][0]', '');"><strong>[tag:rfld:{$field.rubric_field_alias}][0]</strong></a> <a class="rightDir" title="{#RUBRIK_INSERT_HELP#}" href="javascript:void(0);" onclick="textSelection2_1('[tag:rfld:{$field.rubric_field_alias}][0]', '');"><strong>[tag:rfld:{$field.rubric_field_alias}][0]</strong></a>
{/if} {/if}
</td> </td>
<td align="center"> <td align="center">

2
admin/templates/sysblocks/list.tpl

@ -120,7 +120,7 @@
<td align="center">{$sysblock->sysblock_author_id|escape}</td> <td align="center">{$sysblock->sysblock_author_id|escape}</td>
<td align="center"> <td align="center">
<span class="date_text dgrey">{$sysblock->sysblock_created|date_format:$TIME_FORMAT|translate_date}</span> <span class="date_text dgrey">{$sysblock->sysblock_created|date_format:$TIME_FORMAT|pretty_date}</span>
</td> </td>
<td> <td>

92
class/class.core.php

@ -72,7 +72,6 @@
* @param string $param параметр настройки, если не указан - все параметры * @param string $param параметр настройки, если не указан - все параметры
* @return mixed * @return mixed
*/ */
function _sysBlock($id, $param = '') function _sysBlock($id, $param = '')
{ {
global $AVE_DB; global $AVE_DB;
@ -100,6 +99,14 @@
} }
/**
* Получаем шаблон документа
*
* @param $rubric_id
* @param $template_id
*
* @return bool|null|string
*/
function _getMainTemplate($rubric_id, $template_id) function _getMainTemplate($rubric_id, $template_id)
{ {
global $AVE_DB; global $AVE_DB;
@ -179,6 +186,7 @@
: null; : null;
} }
/** /**
* Метод, предназначенный для получения шаблонов * Метод, предназначенный для получения шаблонов
* *
@ -286,6 +294,7 @@
return $out; return $out;
} }
/** /**
* Метод, предназначенный для получения шаблона модуля * Метод, предназначенный для получения шаблона модуля
* *
@ -342,6 +351,7 @@
return stripslashes($out); return stripslashes($out);
} }
/** /**
* Метод, предназначенный для получения прав доступа к документам рубрики * Метод, предназначенный для получения прав доступа к документам рубрики
* *
@ -402,7 +412,7 @@
/** /**
* Метод, предназначенный для обработки события 404 Not Found, т.е. когда страница не найдена. * Метод, предназначенный для обработки события 404 Not Found, т.е. когда страница не найдена.
* *
* @return unknown * @return void
*/ */
function _coreErrorPage404() function _coreErrorPage404()
{ {
@ -491,6 +501,7 @@
return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $document_id); return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $document_id);
} }
/** /**
* Метод, предназначенный для получения содержимого страницы с 404 ошибкой * Метод, предназначенный для получения содержимого страницы с 404 ошибкой
* *
@ -535,6 +546,7 @@
return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $page_not_found_id); return (isset($this->curentdoc->Id) && $this->curentdoc->Id == $page_not_found_id);
} }
/** /**
* Метод, предназначенный для получения МЕТА-тегов для различных модулей. * Метод, предназначенный для получения МЕТА-тегов для различных модулей.
* ToDo * ToDo
@ -565,6 +577,7 @@
return (isset($this->curentdoc->Id) && $this->curentdoc->Id == 1); return (isset($this->curentdoc->Id) && $this->curentdoc->Id == 1);
} }
/** /**
* Метод, предназначенный для определения статуса документа (доступен ли он к публикации). * Метод, предназначенный для определения статуса документа (доступен ли он к публикации).
* *
@ -614,6 +627,7 @@
return (! empty($this->curentdoc)); return (! empty($this->curentdoc));
} }
/** /**
* Метод парсинга тега [tag:(css|js):files] * Метод парсинга тега [tag:(css|js):files]
* для вывода css/js-файлов в шаблоне через combine.php * для вывода css/js-файлов в шаблоне через combine.php
@ -667,6 +681,13 @@
} }
/**
* @param $main_content
* @param $id
* @param $rubTmpl
*
* @return mixed|null|string|string[]
*/
function _main_content ($main_content, $id, $rubTmpl) function _main_content ($main_content, $id, $rubTmpl)
{ {
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
@ -674,13 +695,13 @@
// Проверяем теги полей в шаблоне рубрики на условие != '' // Проверяем теги полей в шаблоне рубрики на условие != ''
if (defined('USE_GET_FIELDS') && USE_GET_FIELDS) if (defined('USE_GET_FIELDS') && USE_GET_FIELDS)
{ {
$main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.'?'.'>', $rubTmpl); $main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.' ?'.'>', $rubTmpl);
$main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.'?'.'>', $main_content); $main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.' ?'.'>', $main_content);
} }
else else
{ {
$main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.'?'.'>', $rubTmpl); $main_content = preg_replace("/\[tag:if_notempty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) != \'\') { '.' ?'.'>', $rubTmpl);
$main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.'?'.'>', $main_content); $main_content = preg_replace("/\[tag:if_empty:fld:([a-zA-Z0-9-_]+)\]/u", '<'.'?php if((htmlspecialchars(document_get_field(\'$1\'), ENT_QUOTES)) == \'\') { '.' ?'.'>', $main_content);
} }
$main_content = str_replace('[tag:if:else]', '<?php }else{ ?>', $main_content); $main_content = str_replace('[tag:if:else]', '<?php }else{ ?>', $main_content);
@ -689,10 +710,10 @@
// Парсим элементы полей // Парсим элементы полей
$main_content = preg_replace_callback( $main_content = preg_replace_callback(
'/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', '/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/',
create_function( function ($m)
'$m', {
'return get_field_element($m[1], $m[2], $m[3], ' . $this->curentdoc->Id . ');' return get_field_element($m[1], $m[2], $m[3], $this->curentdoc->Id);
), },
$main_content $main_content
); );
@ -702,10 +723,10 @@
// Повторно парсим элементы полей // Повторно парсим элементы полей
$main_content = preg_replace_callback( $main_content = preg_replace_callback(
'/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', '/\[tag:fld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/',
create_function( function ($m)
'$m', {
'return get_field_element($m[1], $m[2], $m[3], ' . $this->curentdoc->Id . ');' return get_field_element($m[1], $m[2], $m[3], $this->curentdoc->Id);
), },
$main_content $main_content
); );
@ -744,8 +765,10 @@
// парсим теги в шаблоне рубрики // парсим теги в шаблоне рубрики
$main_content = preg_replace_callback( $main_content = preg_replace_callback(
'/\[tag:date:([a-zA-Z0-9-. \/]+)\]/', '/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
create_function('$m','return translate_date(date($m[1], '.$this->curentdoc->document_published.')); function ($m)
'), {
return translate_date(date($m[1], $this->curentdoc->document_published));
},
$main_content $main_content
); );
@ -786,6 +809,11 @@
} }
/**
* Получаем ID для кеша документа
*
* @return array|bool
*/
function _get_cache_id() function _get_cache_id()
{ {
$cache = array(); $cache = array();
@ -811,6 +839,13 @@
} }
/**
* Создаем компилированный документ
*
* @param $main_content
*
* @return bool
*/
function setCompileDocument ($main_content) function setCompileDocument ($main_content)
{ {
$cache = $this->_get_cache_id(); $cache = $this->_get_cache_id();
@ -841,6 +876,11 @@
} }
/**
* Получаем скомпилированный документ
*
* @return bool|string
*/
function getCompileDocument () function getCompileDocument ()
{ {
$cache = $this->_get_cache_id(); $cache = $this->_get_cache_id();
@ -1019,6 +1059,7 @@
} }
} }
/** /**
* Метод, предназанченный для сборки всей страницы в единое целое. * Метод, предназанченный для сборки всей страницы в единое целое.
* *
@ -1117,7 +1158,9 @@
// Выполняем Код рубрики До загрузки документа // Выполняем Код рубрики До загрузки документа
ob_start(); ob_start();
eval(' ?>' . $this->curentdoc->rubric_start_code . '<?php '); eval(' ?>' . $this->curentdoc->rubric_start_code . '<?php ');
ob_end_clean(); ob_end_clean();
// Получаем шаблон // Получаем шаблон
@ -1517,10 +1560,10 @@
// Парсим тизер документа // Парсим тизер документа
$out = preg_replace_callback( $out = preg_replace_callback(
'/\[tag:teaser:(\d+)(|:\[(.*?)\])\]/', '/\[tag:teaser:(\d+)(|:\[(.*?)\])\]/',
create_function( function ($m)
'$m', {
'return showteaser($m[1], $m[2]);' return showteaser($m[1], $m[2]);
), },
$out $out
); );
@ -1528,10 +1571,10 @@
if (defined('RUB_ID')) if (defined('RUB_ID'))
$out = preg_replace_callback( $out = preg_replace_callback(
'/\[tag:docauthoravatar:(\d+)\]/', '/\[tag:docauthoravatar:(\d+)\]/',
create_function( function ($m)
'$m', {
'return getAvatar('.intval($this->curentdoc->document_author_id).', $m[1]);' return getAvatar(intval($this->curentdoc->document_author_id), $m[1]);
), },
$out $out
); );
@ -1570,6 +1613,7 @@
echo $out; echo $out;
} }
/** /**
* Метод, предназначенный для формирования ЧПУ, а также для поиска документа и разбора * Метод, предназначенный для формирования ЧПУ, а также для поиска документа и разбора
* дополнительных параметров в URL * дополнительных параметров в URL

425
class/class.debug.php

@ -35,20 +35,29 @@
* Функция для вывода переменной (для отладки) * Функция для вывода переменной (для отладки)
* *
* @param mixed $var любая переменная * @param mixed $var любая переменная
* @param bool $exit
* @param null $bg
* @param bool $echo
*
* @return false|null|string|string[]
*/ */
public static function _echo($var, $exit = false, $bg = null) public static function _echo($var, $exit = false, $bg = null, $echo = true)
{ {
$code = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$backtrace = $backtrace[0]; $backtrace = $backtrace[0];
if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'])) if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file']))
{ {
$file = preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match); preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match);
$file = $match[1]; $file = $match[1];
} }
$fh = fopen((isset($file) ? $file : $backtrace['file']), 'r'); $fh = fopen((isset($file)
? $file
: $backtrace['file']), 'r');
$line = 0; $line = 0;
@ -71,7 +80,7 @@
$var_dump = htmlspecialchars($var_dump); $var_dump = htmlspecialchars($var_dump);
$var_dump = preg_replace('/(=&gt;)/', '<span style="color: #FF8C00;">$1</span>', $var_dump); $var_dump = preg_replace('/(=&gt;)/', '<span style="color: #ff8c00;">$1</span>', $var_dump);
ob_end_clean(); ob_end_clean();
@ -84,26 +93,54 @@
$fn_name = 'EVAL'; $fn_name = 'EVAL';
if (! $bg) if (! $bg)
{
$br = '2a5885';
$bg = '43648c'; $bg = '43648c';
}
else
{
$br = $bg;
}
$var_dump = ' $var_dump = '
<div style="border: 1px solid #'.$br.'; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;"> <style>
<div style="background:#'.$bg.'; color: #fff; margin: 0; padding: 5px;"> .debug_bg {
var_dump(<strong>' . trim($fn_name) . '</strong>) - ' . self::_trace() . margin: 20px;
'</div> border: 1px solid #d9d9d9;
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' background-color: #f1efef;
. $var_dump . border-radius: 5px;
'</pre> box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
font-family: "Consolas", Verdana, Arial;
font-size: 11px;
}
.debug_top {
color: #ffffff;
font-size: 15px;
font-weight: bold;
padding-left: 20px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75);
background-color: #' . $bg . ';
background-repeat: repeat-x;
border-bottom: 1px solid #ffffff;
}
.debug_box {
margin: 10px;
padding: 4px;
background-color: #efeded;
border: 1px solid #dedcdc;
}
</style>
<div class="debug_bg">
<div class="debug_top">
var_dump(<strong>' . trim($fn_name) . '</strong>)
</div>
'.self::_trace().'
<div class="debug_box">
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'
. $var_dump .
'</pre>
</div>
</div> </div>
'; ';
if (! $echo)
return $var_dump;
echo $var_dump; echo $var_dump;
if ($exit) if ($exit)
@ -115,27 +152,34 @@
* Функция для вывода переменной (для отладки) * Функция для вывода переменной (для отладки)
* *
* @param mixed $var любая переменная * @param mixed $var любая переменная
* @param bool $exit
* @param null $bg
* @param bool $echo
*
* @return null|string|string[]
*/ */
public static function _print($var, $exit = false, $bg = null) public static function _print($var, $exit = false, $bg = null, $echo = true)
{ {
$code = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$backtrace = $backtrace[0]; $backtrace = $backtrace[0];
if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'])) if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file']))
{ {
$file = preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match); preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match);
$file = $match[1]; $file = $match[1];
} }
$fh = fopen((isset($file) ? $file : $backtrace['file']), 'r'); $fh = fopen((isset($file)
? $file
: $backtrace['file']), 'r');
$line = 0; $line = 0;
while (++$line <= $backtrace['line']) while (++$line <= $backtrace['line'])
{
$code = fgets($fh); $code = fgets($fh);
}
fclose($fh); fclose($fh);
@ -160,26 +204,54 @@
$fn_name = 'EVAL'; $fn_name = 'EVAL';
if (! $bg) if (! $bg)
{
$br = '365899';
$bg = '4e5665'; $bg = '4e5665';
}
else
{
$br = $bg;
}
$var_dump = ' $var_dump = '
<div style="border: 1px solid #'.$br.'; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;"> <style>
<div style="background:#'.$bg.'; color: #fff; margin: 0; padding: 5px;"> .debug_bg {
print_r(<strong>' . trim($fn_name) . '</strong>) - ' . self::_trace() . margin: 20px;
'</div> border: 1px solid #d9d9d9;
<pre style="background:#f0f0f0; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' background-color: #f1efef;
. $var_dump . border-radius: 5px;
'</pre> box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.1);
font-family: Consolas, Verdana, Arial;
font-size: 11px;
}
.debug_top {
color: #ffffff;
font-size: 15px;
font-weight: bold;
padding-left: 20px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75);
background-color: #'.$bg.';
background-repeat: repeat-x;
border-bottom: 1px solid #ffffff;
}
.debug_box {
margin: 10px;
padding: 4px;
background-color: #efeded;
border: 1px solid #dedcdc;
}
</style>
<div class="debug_bg">
<div class="debug_top">
print_r(<strong>' . trim($fn_name) . '</strong>)
</div>
'.self::_trace().'
<div class="debug_box">
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'
. $var_dump .
'</pre>
</div>
</div> </div>
'; ';
if (! $echo)
return $var_dump;
echo $var_dump; echo $var_dump;
if ($exit) if ($exit)
@ -191,27 +263,34 @@
* Функция для вывода переменной (для экспорта) * Функция для вывода переменной (для экспорта)
* *
* @param mixed $var любая переменная * @param mixed $var любая переменная
* @param bool $exit
* @param null $bg
* @param bool $echo
*
* @return string
*/ */
public static function _exp($var, $exit = false, $bg = null) public static function _exp($var, $exit = false, $bg = null, $echo = true)
{ {
$code = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$backtrace = $backtrace[0]; $backtrace = $backtrace[0];
if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'])) if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file']))
{ {
$file = preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match); preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match);
$file = $match[1]; $file = $match[1];
} }
$fh = fopen((isset($file) ? $file : $backtrace['file']), 'r'); $fh = fopen((isset($file)
? $file
: $backtrace['file']), 'r');
$line = 0; $line = 0;
while (++$line <= $backtrace['line']) while (++$line <= $backtrace['line'])
{
$code = fgets($fh); $code = fgets($fh);
}
fclose($fh); fclose($fh);
@ -230,14 +309,7 @@
$fn_name = 'EVAL'; $fn_name = 'EVAL';
if (! $bg) if (! $bg)
{
$br = 'bbb';
$bg = 'ccc'; $bg = 'ccc';
}
else
{
$br = $bg;
}
$var_export = htmlspecialchars(ob_get_contents()); $var_export = htmlspecialchars(ob_get_contents());
@ -246,16 +318,51 @@
ob_end_clean(); ob_end_clean();
$var_dump = ' $var_dump = '
<div style="border: 1px solid #'.$br.'; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;"> <style>
<div style="background:#'.$bg.'; color: #000; margin: 0; padding: 5px;">var_export(<strong>' .debug_bg {
. trim($fn_name) . '</strong>) - ' . self::_trace() . margin: 20px;
'</div> border: 1px solid #d9d9d9;
<pre style="background:#f0f0f0; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' background-color: #f1efef;
border-radius: 5px;
box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.1);
font-family: Consolas, Verdana, Arial;
font-size: 11px;
}
.debug_top {
color: #ffffff;
font-size: 15px;
font-weight: bold;
padding-left: 20px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75);
background-color: #'.$bg.';
background-repeat: repeat-x;
border-bottom: 1px solid #ffffff;
}
.debug_box {
margin: 10px;
padding: 4px;
background-color: #efeded;
border: 1px solid #dedcdc;
}
</style>
<div class="debug_bg">
<div class="debug_top">
var_export(<strong>' . trim($fn_name) . '</strong>)
</div>
'.self::_trace().'
<div class="debug_box">
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'
. $var_export . . $var_export .
'</pre> '</pre>
</div>
</div> </div>
'; ';
if (! $echo)
return $var_dump;
echo $var_dump; echo $var_dump;
if ($exit) if ($exit)
@ -266,29 +373,35 @@
/** /**
* Функция для вывода переменной (для отладки) * Функция для вывода переменной (для отладки)
* *
* @param mixed $var любая переменная * @param mixed $var любая переменная
* @param bool $exit true - остановливает дальнейшее выполнение скрипта, false - продолжает выполнять скрипт * @param bool $exit true - остановливает дальнейшее выполнение скрипта, false - продолжает выполнять скрипт
* @param null $bg
* @param bool $echo
*
* @return false|string
*/ */
public static function _html($var, $exit = false) public static function _html($var, $exit = false, $bg = null, $echo = true)
{ {
$code = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$backtrace = $backtrace[0]; $backtrace = $backtrace[0];
if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'])) if (preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file']))
{ {
$file = preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match); preg_match('/([^\(]*)\((.*)\)/i', $backtrace['file'], $match);
$file = $match[1]; $file = $match[1];
} }
$fh = fopen((isset($file) ? $file : $backtrace['file']), 'r'); $fh = fopen((isset($file)
? $file
: $backtrace['file']), 'r');
$line = 0; $line = 0;
while (++$line <= $backtrace['line']) while (++$line <= $backtrace['line'])
{
$code = fgets($fh); $code = fgets($fh);
}
fclose($fh); fclose($fh);
@ -298,39 +411,87 @@
var_export($var); var_export($var);
$fn_name = !empty($name) if (! empty($name))
? $name[1] {
: 'EVAL'; $fn_name = explode(',', $name[1]);
$fn_name = array_shift($fn_name);
}
else
$fn_name = 'EVAL';
if (! $bg)
$bg = '43648c';
$var_dump = ob_get_contents(); $var_dump = ob_get_contents();
ob_end_clean(); ob_end_clean();
$var_dump = ' $var_dump = '
<div style="border: 1px solid #bbb; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;"> <style>
<div style="background:#ccc; color: #000; margin: 0; padding: 5px;">var_export(<strong>' .debug_bg {
. trim($fn_name) . '</strong>) - ' . self::_trace() . margin: 20px;
'</div> border: 1px solid #d9d9d9;
<pre style="background:#f0f0f0; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' background-color: #f1efef;
border-radius: 5px;
box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.1);
font-family: Consolas, Verdana, Arial;
border-radius: 3px;
font-size: 11px;
}
.debug_top {
color: #ffffff;
font-size: 15px;
font-weight: bold;
padding-left: 20px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75);
background-color: #'.$bg.';
background-repeat: repeat-x;
border-bottom: 1px solid #ffffff;
}
.debug_box {
margin: 10px;
padding: 4px;
background-color: #efeded;
border: 1px solid #dedcdc;
}
</style>
<div class="debug_bg">
<div class="debug_top">
var_export(<strong>' . trim($fn_name) . '</strong>)
</div>
'.self::_trace().'
<div class="debug_box">
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'
. htmlentities($var_dump, ENT_QUOTES) . . htmlentities($var_dump, ENT_QUOTES) .
'</pre> '</pre>
</div>
</div> </div>
'; ';
if (! $echo)
return $var_dump;
echo $var_dump; echo $var_dump;
if ($exit) exit; if ($exit)
exit;
} }
/** /**
* Функция для записи переменной в файл (для отладки) * Функция для записи переменной в файл (для отладки)
* *
* @param mixed $var любая переменная * @param mixed $var любая переменная
* @param bool $exit true - остановливает дальнейшее выполнение скрипта, false - продолжает выполнять скрипт * @param bool $exit true - остановливает дальнейшее выполнение скрипта, false - продолжает выполнять скрипт
* @param null $bg
* @param bool $append
*/ */
public static function _dump($var, $append = true, $exit = false, $bg = null) public static function _dump($var, $exit = false, $bg = null, $append = true)
{ {
$code = '';
$backtrace = debug_backtrace(); $backtrace = debug_backtrace();
$backtrace = $backtrace[0]; $backtrace = $backtrace[0];
@ -341,14 +502,14 @@
$file = $match[1]; $file = $match[1];
} }
$fh = fopen((isset($file) ? $file : $backtrace['file']), 'r'); $fh = fopen((isset($file)
? $file
: $backtrace['file']), 'r');
$line = 0; $line = 0;
while (++$line <= $backtrace['line']) while (++$line <= $backtrace['line'])
{
$code = fgets($fh); $code = fgets($fh);
}
fclose($fh); fclose($fh);
@ -387,13 +548,45 @@
} }
$var_dump = ' $var_dump = '
<div style="border: 1px solid #'.$br.'; margin: 5px 0; font-size: 11px; font-family: Consolas, Verdana, Arial; border-radius: 3px;"> <style>
<div style="background:#'.$bg.'; color: #fff; margin: 0; padding: 5px;"> .debug_bg {
<strong>' . date("j F Y, H:i:s") . '</strong> - var_dump(<strong>' . trim($fn_name) . '</strong>) - ' . self::_trace() . margin: 20px;
'</div> border: 1px solid #d9d9d9;
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">' background-color: #f1efef;
. $var_dump . border-radius: 5px;
'</pre> box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.1);
font-family: Consolas, Verdana, Arial;
font-size: 11px;
}
.debug_top {
color: #ffffff;
font-size: 15px;
font-weight: bold;
padding-left: 20px;
padding-top: 10px;
padding-bottom: 10px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75);
background-color: #'.$bg.';
background-repeat: repeat-x;
border-bottom: 1px solid #ffffff;
}
.debug_box {
margin: 10px;
padding: 4px;
background-color: #efeded;
border: 1px solid #dedcdc;
}
</style>
<div class="debug_bg">
<div class="debug_top">
var_dump(<strong>' . trim($fn_name) . '</strong>)
</div>
'.self::_trace().'
<div class="debug_box">
<pre style="background:#f5f5f5; color: #000; margin: 0; padding: 5px; border: 0; font-size: 11px; font-family: Consolas, Verdana, Arial;">'
. $var_dump .
'</pre>
</div>
</div> </div>
'; ';
@ -423,26 +616,22 @@
$file = $trace['file']; $file = $trace['file'];
$function = $trace['function']; //$function = $trace['function'];
$class = (isset($bt[2]['class']) $class = (isset($bt[2]['class'])
? $bt[2]['class'] ? $bt[2]['class']
: 'None'); : 'None');
if (isset($bt[2]['class'])) if (isset($bt[2]['class']))
{
$type = $bt[2]['type']; $type = $bt[2]['type'];
}
else else
{
$type = 'Unknow'; $type = 'Unknow';
}
$function = isset($bt[2]['function']) $function = isset($bt[2]['function'])
? $bt[2]['function'] ? $bt[2]['function']
: 'None'; : 'None';
return sprintf('Class: <strong>%s</strong> | Type: <strong>%s</strong> | Function: <strong>%s</strong> | File: <strong>%s</strong> line <strong>%s</strong>', $class, $type, $function, $file, $line); return sprintf('<div class="debug_box">Class: <strong>%s</strong> | Type: <strong>%s</strong> | Function: <strong>%s</strong></div><div class="debug_box">File: <strong>%s</strong> line <strong>%s</strong></div>', $class, $type, $function, $file, $line);
} }
@ -461,7 +650,8 @@
* Функция отвечает за окончание таймера * Функция отвечает за окончание таймера
* *
* @param string $name любая переменная (ключ массива) * @param string $name любая переменная (ключ массива)
* @return *
* @return string
*/ */
public static function endTime($name = '') public static function endTime($name = '')
{ {
@ -503,21 +693,13 @@
public static function formatSize($size) public static function formatSize($size)
{ {
if ($size >= 1073741824) if ($size >= 1073741824)
{
$size = round($size / 1073741824 * 100) / 100 . ' Gb'; $size = round($size / 1073741824 * 100) / 100 . ' Gb';
}
elseif ($size >= 1048576) elseif ($size >= 1048576)
{
$size = round($size / 1048576 * 100) / 100 . ' Mb'; $size = round($size / 1048576 * 100) / 100 . ' Mb';
}
elseif ($size >= 1024) elseif ($size >= 1024)
{
$size = round($size / 1024 * 100) / 100 . ' Kb'; $size = round($size / 1024 * 100) / 100 . ' Kb';
}
else else
{
$size = $size . ' b'; $size = $size . ' b';
}
return $size; return $size;
} }
@ -541,21 +723,24 @@
} }
/**
* @param $header
* @param $body
* @param $caller
* @param bool $exit
*/
public static function _errorSql ($header, $body, $caller, $exit = false) public static function _errorSql ($header, $body, $caller, $exit = false)
{ {
//
Debug::_echo(preg_replace('/(\s)+/s', ' ', $header));
Debug::_echo(DB::queryList($body));
Debug::_echo($caller);
if ($exit)
exit;
} }
/** /**
* Вывод статистики * Вывод статистики
*
* @param null $type
*
* @return int|null|string
*/ */
public static function getStatistic ($type = null) public static function getStatistic ($type = null)
{ {
@ -618,23 +803,26 @@
} }
/**
* @param string $type
*
* @return false|null|string|string[]
*/
public static function _stat_get($type = 'get') public static function _stat_get($type = 'get')
{ {
$var = '123123';
ob_start(); ob_start();
if ($type == 'get') if ($type == 'get')
var_dump($_GET); var_dump($_GET);
else if ($type == 'post') else if ($type == 'post')
var_dump($_POST); var_dump($_POST);
else if ($type == 'request') else if ($type == 'request')
var_dump($_REQUEST); var_dump($_REQUEST);
else if ($type == 'session') else if ($type == 'session')
var_dump($_SESSION); var_dump($_SESSION);
else if ($type == 'server') else if ($type == 'server')
var_dump($_SERVER); var_dump($_SERVER);
else if ($type == 'globals') else if ($type == 'globals')
var_dump($GLOBALS); var_dump($GLOBALS);
$stat = ob_get_contents(); $stat = ob_get_contents();
$stat = preg_replace('/=>(\s+|\s$)/', ' => ', $stat); $stat = preg_replace('/=>(\s+|\s$)/', ' => ', $stat);
$stat = htmlspecialchars($stat); $stat = htmlspecialchars($stat);
@ -645,7 +833,10 @@
return $stat; return $stat;
} }
//
/**
* @return string
*/
public static function displayInfo () public static function displayInfo ()
{ {
global $AVE_DB; global $AVE_DB;

30
class/class.meta.php

@ -14,17 +14,19 @@ class Meta
{ {
private $_keyword_count = 10; private $_keyword_count = 10;
public function __construct( $keyword_count = false ) public function __construct($keyword_count = false)
{ {
if( (int) $keyword_count ) $this->_keyword_count = $keyword_count; if ((int)$keyword_count)
$this->_keyword_count = $keyword_count;
} }
public function setKeywordCount( $keyword_count ) public function setKeywordCount($keyword_count)
{ {
if( (int) $keyword_count ) $this->_keyword_count = $keyword_count; if ((int)$keyword_count)
$this->_keyword_count = $keyword_count;
} }
public function generateMeta( $text ) public function generateMeta($text)
{ {
$newarr = array (); $newarr = array ();
@ -49,20 +51,24 @@ class Meta
$arr = explode( " ", $text ); $arr = explode( " ", $text );
foreach ( $arr as $word ) { foreach ($arr as $word)
if( mb_strlen( ($word) ) > 4 OR (mb_strtoupper($word)==$word) and mb_strlen( ($word) ) > 1) $newarr[] = $word; {
if (mb_strlen(($word)) > 4 OR (mb_strtoupper($word) == $word) and mb_strlen(($word)) > 1)
$newarr[] = $word;
} }
$arr = array_count_values( $newarr ); $arr = array_count_values($newarr);
arsort( $arr );
$arr = array_keys( $arr ); arsort($arr);
$total = count( $arr ); $arr = array_keys($arr);
// Не используется
// $total = count($arr);
$offset = 0; $offset = 0;
$arr = array_slice( $arr, $offset, $this->_keyword_count ); $arr = array_slice($arr, $offset, $this->_keyword_count);
$return['keywords'] = implode( ", ", $arr ); $return['keywords'] = implode( ", ", $arr );
$return['description'] = trim(mb_substr( trim($text), 0, 220 ),'.').'.'; $return['description'] = trim(mb_substr( trim($text), 0, 220 ),'.').'.';

5
class/class.modules.php

@ -404,6 +404,7 @@
ModuleSysName = '" . MODULE_PATH . "' ModuleSysName = '" . MODULE_PATH . "'
"); ");
} }
// Сохраняем системное сообщение в журнал // Сохраняем системное сообщение в журнал
reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')'); reportLog ($AVE_Template->get_config_vars('MODULES_ACTION_UPDATE') . ' (' . MODULE_PATH . ')');
@ -513,8 +514,8 @@
foreach ($files as $file) foreach ($files as $file)
{ {
if(substr($file, -1) == '/') if (substr($file, -1) == '/')
moduleRemove($file); $this->moduleRemove($file);
else else
unlink($file); unlink($file);
} }

246
class/class.session.php

@ -1,161 +1,155 @@
<?php <?php
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
class AVE_Session_DB
{
public $sess_lifetime;
/** /**
* Хост * AVE.cms
* *
* @var string * @package AVE.cms
*/ * @version 3.x
protected $db_host; * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
/**
* Имя пользователя
* *
* @var string * @license GPL v.2
*/ */
protected $db_user;
/** class AVE_Session_DB
* Пароль {
*
* @var string
*/
protected $db_pass;
/** public $sess_lifetime;
* Имя текущей БД.
* /**
* @var string * Хост
*/ *
protected $db_dbase; * @var string
*/
protected $db_host;
/**
* Имя пользователя
*
* @var string
*/
protected $db_user;
/**
* Пароль
*
* @var string
*/
protected $db_pass;
/**
* Имя текущей БД.
*
* @var string
*/
protected $db_dbase;
/**
* Префикс БД.
*
* @var string
*/
protected $db_prefix;
private $mysql_connect = null;
private $mysql_db = null;
/* Create a connection to a database */
function __construct()
{
// Подключаем конфигурационный файл с параметрами подключения
require (BASE_DIR . '/config/db.config.php');
/** $this->db_host = $config['dbhost'];
* Префикс БД. $this->db_user = $config['dbuser'];
* $this->db_pass = $config['dbpass'];
* @var string $this->db_dbase = $config['dbname'];
*/ $this->db_prefix = $config['dbpref'];
protected $db_prefix;
private $mysql_connect = null; $this->sess_lifetime = (defined('SESSION_LIFETIME') && is_numeric(SESSION_LIFETIME))
private $mysql_db = null; ? SESSION_LIFETIME
: (get_cfg_var("session.gc_maxlifetime") < 1440
? 1440
: get_cfg_var("session.gc_maxlifetime"));
/* Create a connection to a database */ if (! $this->mysql_connect = mysqli_connect ($this->db_host, $this->db_user, $this->db_pass))
function __construct() $this->error();
{
// Подключаем конфигурационный файл с параметрами подключения
require (BASE_DIR . '/config/db.config.php');
$this->db_host = $config['dbhost'];
$this->db_user = $config['dbuser'];
$this->db_pass = $config['dbpass'];
$this->db_dbase = $config['dbname'];
$this->db_prefix = $config['dbpref'];
$this->sess_lifetime = (defined('SESSION_LIFETIME') && is_numeric(SESSION_LIFETIME))
? SESSION_LIFETIME
: (get_cfg_var("session.gc_maxlifetime") < 1440
? 1440
: get_cfg_var("session.gc_maxlifetime"));
if (! $this->mysql_connect = mysqli_connect ($this->db_host, $this->db_user, $this->db_pass))
{
$this->error();
}
if (! $this->mysql_db = mysqli_select_db ($this->mysql_connect, $this->db_dbase)) if (! $this->mysql_db = mysqli_select_db ($this->mysql_connect, $this->db_dbase))
{ $this->error();
$this->error();
}
$this->mysql_connect->set_charset('utf8'); $this->mysql_connect->set_charset('utf8');
return true; return true;
} }
/* Open session */
function _open($path, $name)
{
return true;
}
/* Close session */ /* Open session */
function _close() function _open($path, $name)
{ {
@mysqli_query($this->mysql_connect, "DELETE FROM " . PREFIX . "_sessions WHERE expiry < '" . time() . "'"); return true;
}
if ($this->mysql_connect !== null)
@mysqli_close($this->mysql_connect);
return true; /* Close session */
} function _close()
{
@mysqli_query($this->mysql_connect, "DELETE FROM " . PREFIX . "_sessions WHERE expiry < '" . time() . "'");
/* Read session */ if ($this->mysql_connect !== null)
function _read($ses_id) @mysqli_close($this->mysql_connect);
{
$qid = @mysqli_query($this->mysql_connect, "SELECT value, Ip FROM " . PREFIX . "_sessions WHERE sesskey = '" . $ses_id . "' AND expiry > '" . time() . "'");
if ((list($value, $ip) = @mysqli_fetch_row($qid)) && $ip == $_SERVER['REMOTE_ADDR']) return true;
{
return $value;
} }
return '';
}
/* Write new data */ /* Read session */
function _write($ses_id, $data) function _read($ses_id)
{
if (! $qid = @mysqli_query($this->mysql_connect, "INSERT INTO ".PREFIX."_sessions VALUES ('".$ses_id."', ".(time()+$this->sess_lifetime).", '".addslashes($data)."', '".$_SERVER['REMOTE_ADDR']."', FROM_UNIXTIME(expiry, '%d.%m.%Y, %H:%i:%s'))"))
{ {
$qid = @mysqli_query($this->mysql_connect, "UPDATE ".PREFIX."_sessions SET expiry = ".(time()+$this->sess_lifetime).", expire_datum = FROM_UNIXTIME(expiry,'%d.%m.%Y, %H:%i:%s'), value = '".addslashes($data)."', Ip = '".$_SERVER['REMOTE_ADDR']."' WHERE sesskey = '".$ses_id."' AND expiry > '".time()."'"); $qid = @mysqli_query($this->mysql_connect, "SELECT value, Ip FROM " . PREFIX . "_sessions WHERE sesskey = '" . $ses_id . "' AND expiry > '" . time() . "'");
if ((list($value, $ip) = @mysqli_fetch_row($qid)) && $ip == $_SERVER['REMOTE_ADDR'])
return $value;
return '';
} }
return $qid;
}
/* Destroy session */ /* Write new data */
function _destroy($ses_id) function _write($ses_id, $data)
{ {
return @mysqli_query($this->mysql_connect, "DELETE FROM ".PREFIX."_sessions WHERE sesskey = '".$ses_id."'"); if (! $qid = @mysqli_query($this->mysql_connect, "INSERT INTO ".PREFIX."_sessions VALUES ('".$ses_id."', ".(time()+$this->sess_lifetime).", '".addslashes($data)."', '".$_SERVER['REMOTE_ADDR']."', FROM_UNIXTIME(expiry, '%d.%m.%Y, %H:%i:%s'))"))
} $qid = @mysqli_query($this->mysql_connect, "UPDATE ".PREFIX."_sessions SET expiry = ".(time()+$this->sess_lifetime).", expire_datum = FROM_UNIXTIME(expiry,'%d.%m.%Y, %H:%i:%s'), value = '".addslashes($data)."', Ip = '".$_SERVER['REMOTE_ADDR']."' WHERE sesskey = '".$ses_id."' AND expiry > '".time()."'");
/* Garbage collection, deletes old sessions */ return $qid;
function _gc($maxlifetime) }
{
$session_res = @mysqli_query($this->mysql_connect, "DELETE FROM ".PREFIX."_sessions WHERE expire < (UNIX_TIMESTAMP(NOW()) - " . (int)$maxlifetime . ")");
if (!$session_res) { /* Destroy session */
return false; function _destroy($ses_id)
{
return @mysqli_query($this->mysql_connect, "DELETE FROM ".PREFIX."_sessions WHERE sesskey = '".$ses_id."'");
} }
else
/* Garbage collection, deletes old sessions */
function _gc($maxlifetime)
{ {
return true; $session_res = @mysqli_query($this->mysql_connect, "DELETE FROM ".PREFIX."_sessions WHERE expire < (UNIX_TIMESTAMP(NOW()) - " . (int)$maxlifetime . ")");
if (! $session_res)
return false;
else
return true;
} }
}
function error() { function error() {
ob_start(); ob_start();
header('HTTP/1.1 503 Service Temporarily Unavailable'); header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 3600'); header('Retry-After: 3600');
header('X-Powered-By:'); header('X-Powered-By:');
display_notice("Error connect to MySQL."); display_notice("Error connect to MySQL.");
die; die;
}
} }
}
?> ?>

170
class/class.utm.php

@ -1,121 +1,119 @@
<?php <?php
/* /*
Версия от 06.03.2018г.
Версия от 06.03.2018г.
Как это работает:
Как это работает: 1) Пользователь зашел на сайт первый раз.
1) Пользователь зашел на сайт первый раз. 2) Если есть хотя бы один параметр - сохраняет cookies
2) Если есть хотя бы один параметр - сохраняет cookies 3) Если utm_history уже есть, то сохраняет данные в utm_last
3) Если utm_history уже есть, то сохраняет данные в utm_last 4) utm_last перезаписывается при каждом новом значении, а utm_history всегда остаётся неизменной (если был передан хотя бы один параметр)
4) utm_last перезаписывается при каждом новом значении, а utm_history всегда остаётся неизменной (если был передан хотя бы один параметр) 5) utm_source сохраняется всегда до закрытия браузера
5) utm_source сохраняется всегда до закрытия браузера */
class UTMCookie
*/
class UTMCookie
{
private $parameters = array('utm_source', 'utm_medium', 'utm_campaign');
private $utm_history = '';
private $utm_last = '';
private $utm_source = '';
//Проверка параметров: Если все присутствуют - true, иначе false
private function check_parameters()
{ {
//return true; //Сохранять всегда!
$return = false; private $parameters = array('utm_source', 'utm_medium', 'utm_campaign');
foreach ($this->parameters as $param) private $utm_history = '';
if (isset($_GET[$param]) && $_GET[$param] != '') private $utm_last = '';
$return = true; private $utm_source = '';
return $return; //Проверка параметров: Если все присутствуют - true, иначе false
} private function check_parameters()
{
//return true; //Сохранять всегда!
//Создаёт строку с параметрами вот такого вида: utm_source=test; utm_medium=none; utm_campaign=kompaniya1; $return = false;
private function create_parameters()
{
$content = '';
foreach($this->parameters as $param){
if (isset($_GET[$param]) && $_GET[$param] != '') foreach ($this->parameters as $param)
{ if (isset($_GET[$param]) && $_GET[$param] != '')
$content .= $param.'='.$_GET[$param].'; '; $return = true;
} return $return;
else
{
$content .= $param.'=none; ';
}
} }
return $content; //Создаёт строку с параметрами вот такого вида: utm_source=test; utm_medium=none; utm_campaign=kompaniya1;
} private function create_parameters()
//Сохраняет переданные параметры, если требуется
//Если utm_history присутствует, то сохраняет utm_last
public function save_parameters()
{
if (isset($_GET['utm_source']) && trim($_GET['utm_source']) != '')
{ {
setcookie('utm_source', $_GET['utm_source']); $content = '';
foreach($this->parameters as $param){
if (isset($_GET[$param]) && $_GET[$param] != '')
{
$content .= $param.'='.$_GET[$param].'; ';
}
else
{
$content .= $param.'=none; ';
}
}
$this->utm_source = $_GET['utm_source']; return $content;
} }
//$utm_history = ''; //Сохраняет переданные параметры, если требуется
//Если utm_history присутствует, то сохраняет utm_last
if (! isset($_COOKIE['utm_history']) || $_COOKIE['utm_history'] == '') public function save_parameters()
{ {
//Отсутствует utm_history if (isset($_GET['utm_source']) && trim($_GET['utm_source']) != '')
if($this->check_parameters() == true)
{ {
setcookie('utm_source', $_GET['utm_source']);
$utm_history = $this->create_parameters(); $this->utm_source = $_GET['utm_source'];
setcookie('utm_history', $utm_history, time()+15552000); //На 6 месяцев }
setcookie('utm_last', '');
//$utm_history = '';
if (! isset($_COOKIE['utm_history']) || $_COOKIE['utm_history'] == '')
{
//Отсутствует utm_history
if($this->check_parameters() == true)
{
$utm_history = $this->create_parameters();
setcookie('utm_history', $utm_history, time()+15552000); //На 6 месяцев
setcookie('utm_last', '');
$this->utm_history = $utm_history;
}
$this->utm_history = $utm_history;
} }
else
{
//utm_history присутствует
} $this->utm_history = $_COOKIE['utm_history'];
else
{
//utm_history присутствует
$this->utm_history = $_COOKIE['utm_history']; //Перезапишем utm_last, если есть данные для этого
if($this->check_parameters() == true){
//Перезапишем utm_last, если есть данные для этого $utm_last = $this->create_parameters();
if($this->check_parameters() == true){
$utm_last = $this->create_parameters(); if($utm_last != $_COOKIE['utm_history'])
setcookie('utm_last', $utm_last, time()+15552000); //На 6 месяцев
if($utm_last != $_COOKIE['utm_history']) $this->utm_last = $utm_last;
setcookie('utm_last', $utm_last, time()+15552000); //На 6 месяцев
$this->utm_last = $utm_last; }
} }
return true;
} }
return true; //Возвращает значение cookies
} public function get_value($name = '')
{
//Возвращает значение cookies $name = trim($name);
public function get_value($name = '')
{
$name = trim($name);
if ($name == '' || ! in_array($name, array('utm_history', 'utm_last', 'utm_source'))) if ($name == '' || ! in_array($name, array('utm_history', 'utm_last', 'utm_source')))
$name = 'utm_history'; $name = 'utm_history';
if (isset($this->$name) && $this->$name != '') if (isset($this->$name) && $this->$name != '')
return $this->$name; return $this->$name;
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : ''; return isset($_COOKIE[$name]) ? $_COOKIE[$name] : '';
}
} }
}
?> ?>

163
fields/checkbox_multi/field.php

@ -1,163 +0,0 @@
<?php
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2015 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
// Мульти чекбокс
function get_field_checkbox_multi($field_value, $action, $field_id=0, $tpl='', $tpl_empty=0, &$maxlength=null, $document_fields=array(), $rubric_id=0, $default=null, $_tpl=null)
{
global $AVE_Template;
$fld_dir = dirname(__FILE__) . '/';
$tpl_dir = $fld_dir . 'tpl/';
$lang_file = $fld_dir . 'lang/' . (defined('ACP') ? $_SESSION['admin_language'] : $_SESSION['user_language']) . '.txt';
$AVE_Template->config_load($lang_file, 'lang');
$AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
$AVE_Template->config_load($lang_file, 'admin');
$res = array();
switch ($action)
{
case 'edit':
$default_items = explode(',', $default);
$default_items = array_diff($default_items, array(''));
$field_value_array = explode('|', $field_value);
$field_value_array = array_values(array_diff($field_value_array, array('')));
$AVE_Template->assign('items', $default_items);
$AVE_Template->assign('used', $field_value_array);
$AVE_Template->assign('doc_id', (isset($_REQUEST['Id']) ? (int)$_REQUEST['Id'] : 0));
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $field_value);
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin', $_tpl);
return $AVE_Template->fetch($tpl_file);
break;
case 'doc':
$default_items = explode(',', $default);
$items = explode('|', $field_value);
$items = array_diff($items, array(''));
if (! empty($items))
{
foreach($items as $item)
{
if ($item)
{
if ($tpl_empty)
{
$item = $default_items[(int)$item-1];
}
else
{
$field_param = explode('|', $item);
$item = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i',
function($data) use($field_param, $default_items)
{
return $default_items[$field_param[(int)$data[1]]-1];
},
$tpl
);
}
}
$res[] = $item;
}
}
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc', $_tpl);
if ($tpl_empty && $tpl_file)
{
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $res);
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('default', $default_items);
return $AVE_Template->fetch($tpl_file);
}
return (! empty($res))
? implode(PHP_EOL, $res)
: $tpl;
break;
case 'req':
$default_items = explode(',', $default);
$items = explode('|', $field_value);
$items = array_diff($items, array(''));
if (! empty($items))
{
foreach($items as $item)
{
if ($item)
{
if ($tpl_empty)
{
$item = $default_items[(int)$item-1];
}
else
{
$field_param = explode('|', $item);
$item = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i',
function($data) use($field_param, $default_items)
{
return $default_items[$field_param[(int)$data[1]]-1];
},
$tpl
);
}
}
$res[] = $item;
}
}
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'req', $_tpl);
if ($tpl_empty && $tpl_file)
{
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $res);
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('default', $default_items);
return $AVE_Template->fetch($tpl_file);
}
return (! empty($res))
? implode(PHP_EOL, $res)
: $tpl;
break;
case 'name':
return $AVE_Template->get_config_vars('name');
break;
}
return ($res ? $res : $field_value);
}
?>

163
fields/multi_checkbox/field.php

@ -0,0 +1,163 @@
<?
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2015 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
// Мульти чекбокс
function get_field_multi_checkbox($field_value, $action, $field_id=0, $tpl='', $tpl_empty=0, &$maxlength=null, $document_fields=array(), $rubric_id=0, $default=null)
{
global $AVE_Template;
$fld_dir = dirname(__FILE__) . '/';
$tpl_dir = $fld_dir . 'tpl/';
$lang_file = $fld_dir . 'lang/' . (defined('ACP') ? $_SESSION['admin_language'] : $_SESSION['user_language']) . '.txt';
$AVE_Template->config_load($lang_file, 'lang');
$AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
$AVE_Template->config_load($lang_file, 'admin');
$res = array();
switch ($action)
{
case 'edit':
$default_items = explode(',', $default);
$default_items = array_diff($default_items, array(''));
$field_value_array = explode('|', $field_value);
$field_value_array = array_values(array_diff($field_value_array, array('')));
$AVE_Template->assign('items', $default_items);
$AVE_Template->assign('used', $field_value_array);
$AVE_Template->assign('doc_id', (isset($_REQUEST['Id']) ? (int)$_REQUEST['Id'] : 0));
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $field_value);
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin');
return $AVE_Template->fetch($tpl_file);
break;
case 'doc':
$default_items = explode(',', $default);
$items = explode('|', $field_value);
$items = array_diff($items, array(''));
if (! empty($items))
{
foreach($items as $item)
{
if ($item)
{
if ($tpl_empty)
{
$item = $default_items[(int)$item-1];
}
else
{
$field_param = explode('|', $item);
$item = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i',
function($data) use($field_param, $default_items)
{
return $default_items[$field_param[(int)$data[1]]-1];
},
$tpl
);
}
}
$res[] = $item;
}
}
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc');
if ($tpl_empty && $tpl_file)
{
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $res);
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('default', $default_items);
return $AVE_Template->fetch($tpl_file);
}
return (! empty($res))
? implode(PHP_EOL, $res)
: $tpl;
break;
case 'req':
$default_items = explode(',', $default);
$items = explode('|', $field_value);
$items = array_diff($items, array(''));
if (! empty($items))
{
foreach($items as $item)
{
if ($item)
{
if ($tpl_empty)
{
$item = $default_items[(int)$item-1];
}
else
{
$field_param = explode('|', $item);
$item = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i',
function($data) use($field_param, $default_items)
{
return $default_items[$field_param[(int)$data[1]]-1];
},
$tpl
);
}
}
$res[] = $item;
}
}
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'req');
if ($tpl_empty && $tpl_file)
{
$AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $res);
$AVE_Template->assign('rubric_id', $rubric_id);
$AVE_Template->assign('default', $default_items);
return $AVE_Template->fetch($tpl_file);
}
return (! empty($res))
? implode(PHP_EOL, $res)
: $tpl;
break;
case 'name':
return $AVE_Template->get_config_vars('name');
break;
}
return ($res ? $res : $field_value);
}
?>

0
fields/checkbox_multi/lang/bg.txt → fields/multi_checkbox/lang/bg.txt

0
fields/checkbox_multi/lang/cz.txt → fields/multi_checkbox/lang/cz.txt

0
fields/checkbox_multi/lang/en.txt → fields/multi_checkbox/lang/en.txt

0
fields/checkbox_multi/lang/pl.txt → fields/multi_checkbox/lang/pl.txt

0
fields/checkbox_multi/lang/ru.txt → fields/multi_checkbox/lang/ru.txt

0
fields/checkbox_multi/lang/ua.txt → fields/multi_checkbox/lang/ua.txt

0
fields/checkbox_multi/tpl/field-doc.tpl → fields/multi_checkbox/tpl/field-doc.tpl

0
fields/checkbox_multi/tpl/field-req.tpl → fields/multi_checkbox/tpl/field-req.tpl

0
fields/checkbox_multi/tpl/field.tpl → fields/multi_checkbox/tpl/field.tpl

463
fields/tags/field.php

@ -1,234 +1,231 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
* @version 3.x * @version 3.x
* @filesource * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
* *
* @license GPL v.2 * @license GPL v.2
*/ */
// Tags // Tags
function get_field_tags ($field_value, $action, $field_id = 0, $tpl = '', $tpl_empty = 0, &$maxlength = null, $document_fields = array(), $rubric_id = 0, $default = null, $_tpl = null) function get_field_tags ($field_value, $action, $field_id = 0, $tpl = '', $tpl_empty = 0, &$maxlength = null, $document_fields = array(), $rubric_id = 0, $default = null, $_tpl = null)
{ {
global $AVE_DB, $AVE_Template; global $AVE_DB, $AVE_Template;
$fld_dir = dirname(__FILE__) . '/'; $fld_dir = dirname(__FILE__) . '/';
$tpl_dir = $fld_dir . 'tpl/'; $tpl_dir = $fld_dir . 'tpl/';
$fld_name = basename($fld_dir); $fld_name = basename($fld_dir);
$rubric_id = $rubric_id > 0 $rubric_id = $rubric_id > 0
? $rubric_id ? $rubric_id
: $_REQUEST['rubric_id'] : $_REQUEST['rubric_id']
? (int)$_REQUEST['rubric_id'] ? (int)$_REQUEST['rubric_id']
: $AVE_DB->Query("SELECT rubric_id FROM ".PREFIX."_documents WHERE Id = '".$_REQUEST['Id']."'")->GetCell(); : $AVE_DB->Query("SELECT rubric_id FROM ".PREFIX."_documents WHERE Id = '".$_REQUEST['Id']."'")->GetCell();
$lang_file = $fld_dir . 'lang/' . (defined('ACP') $lang_file = $fld_dir . 'lang/' . (defined('ACP')
? $_SESSION['admin_language'] ? $_SESSION['admin_language']
: $_SESSION['user_language']) . '.txt'; : $_SESSION['user_language']) . '.txt';
$AVE_Template->config_load($lang_file, 'lang'); $AVE_Template->config_load($lang_file, 'lang');
$AVE_Template->assign('config_vars', $AVE_Template->get_config_vars()); $AVE_Template->assign('config_vars', $AVE_Template->get_config_vars());
$AVE_Template->config_load($lang_file, 'admin'); $AVE_Template->config_load($lang_file, 'admin');
switch ($action) switch ($action)
{ {
case 'edit': case 'edit':
$sql = " $sql = "
SELECT DISTINCT SELECT DISTINCT
tag tag
FROM FROM
".PREFIX."_document_tags ".PREFIX."_document_tags
WHERE WHERE
rubric_id = '".$rubric_id."' rubric_id = '".$rubric_id."'
ORDER BY tag ASC ORDER BY tag ASC
"; ";
$query = $AVE_DB->Query($sql); $query = $AVE_DB->Query($sql);
$field_tags = array(); $field_tags = array();
while ($row = $query->GetCell()) while ($row = $query->GetCell())
array_push($field_tags, $row); array_push($field_tags, $row);
$field_value = explode('|', $field_value); $field_value = explode('|', $field_value);
$field_value = array_diff($field_value, array('')); $field_value = array_diff($field_value, array(''));
$total = count($field_tags); $total = count($field_tags);
$field_points = array(ceil($total/4), 2*ceil($total/4), 3*ceil($total/4)); $field_points = array(ceil($total/4), 2*ceil($total/4), 3*ceil($total/4));
$AVE_Template->assign('field_points', $field_points); $AVE_Template->assign('field_points', $field_points);
$AVE_Template->assign('field_tags', $field_tags); $AVE_Template->assign('field_tags', $field_tags);
$AVE_Template->assign('field_dir', $fld_name); $AVE_Template->assign('field_dir', $fld_name);
$AVE_Template->assign('field_id', $field_id); $AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_value', $field_value); $AVE_Template->assign('field_value', $field_value);
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin', $_tpl); $tpl_file = get_field_tpl($tpl_dir, $field_id, 'admin', $_tpl);
return $AVE_Template->fetch($tpl_file); return $AVE_Template->fetch($tpl_file);
break; break;
case 'doc': case 'doc':
$AVE_Template->config_load($lang_file, 'public'); $AVE_Template->config_load($lang_file, 'public');
if ($tpl_empty) if ($tpl_empty)
{ {
$field_value = explode('|', $field_value); $field_value = explode('|', $field_value);
$field_value = array_diff($field_value, array('')); $field_value = array_diff($field_value, array(''));
$field_value = array_values($field_value); $field_value = array_values($field_value);
} }
else else
{ {
$field_param = explode('|', $field_value); $field_param = explode('|', $field_value);
$field_param = array_diff($field_param, array('')); $field_param = array_diff($field_param, array(''));
$field_param = array_values($field_param); $field_param = array_values($field_param);
$field_value = preg_replace_callback( $field_value = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i', '/\[tag:parametr:(\d+)\]/i',
function ($data) use ($field_param) function ($data) use ($field_param)
{ {
return $field_param[(int)$data[1]]; return $field_param[(int)$data[1]];
}, },
$tpl $tpl
); );
} }
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc', $_tpl); $tpl_file = get_field_tpl($tpl_dir, $field_id, 'doc', $_tpl);
if ($tpl_empty && $tpl_file) if ($tpl_empty && $tpl_file)
{ {
$AVE_Template->assign('field_id', $field_id); $AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_default', $default); $AVE_Template->assign('field_default', $default);
$AVE_Template->assign('field_value', $field_value); $AVE_Template->assign('field_value', $field_value);
return $AVE_Template->fetch($tpl_file); return $AVE_Template->fetch($tpl_file);
} }
return $field_value; return $field_value;
break; break;
case 'req': case 'req':
$AVE_Template->config_load($lang_file, 'public'); $AVE_Template->config_load($lang_file, 'public');
if ($tpl_empty) if ($tpl_empty)
{ {
$field_value = explode('|', $field_value); $field_value = explode('|', $field_value);
$field_value = array_diff($field_value, array('')); $field_value = array_diff($field_value, array(''));
$field_value = array_values($field_value); $field_value = array_values($field_value);
} }
else else
{ {
$field_param = explode('|', $field_value); $field_param = explode('|', $field_value);
$field_param = array_diff($field_param, array('')); $field_param = array_diff($field_param, array(''));
$field_param = array_values($field_param); $field_param = array_values($field_param);
$field_value = preg_replace_callback( $field_value = preg_replace_callback(
'/\[tag:parametr:(\d+)\]/i', '/\[tag:parametr:(\d+)\]/i',
function($data) use($field_param) function($data) use($field_param)
{ {
return $field_param[(int)$data[1]]; return $field_param[(int)$data[1]];
}, },
$tpl $tpl
); );
} }
$tpl_file = get_field_tpl($tpl_dir, $field_id, 'req', $_tpl); $tpl_file = get_field_tpl($tpl_dir, $field_id, 'req', $_tpl);
if ($tpl_empty && $tpl_file) if ($tpl_empty && $tpl_file)
{ {
$AVE_Template->assign('field_id', $field_id); $AVE_Template->assign('field_id', $field_id);
$AVE_Template->assign('field_default', $default); $AVE_Template->assign('field_default', $default);
$AVE_Template->assign('field_value', $field_value); $AVE_Template->assign('field_value', $field_value);
return $AVE_Template->fetch($tpl_file); return $AVE_Template->fetch($tpl_file);
} }
return $field_value; return $field_value;
break; break;
case 'save': case 'save':
// Регистрируем хук // Регистрируем хук
Hooks::register('DocumentAfterSave', 'afterTagsSave', 10); Hooks::register('DocumentAfterSave', 'afterTagsSave', 10);
$field_value = tagsValue($field_value); $field_value = tagsValue($field_value);
if (! empty($field_value)) if (! empty($field_value))
$field_value = '|' . implode('|', $field_value) . '|'; $field_value = '|' . implode('|', $field_value) . '|';
return $field_value; return $field_value;
case 'name': case 'name':
return $AVE_Template->get_config_vars('name'); return $AVE_Template->get_config_vars('name');
default: default:
return $field_value; return $field_value;
} }
} }
if (! function_exists('tagsValue')) if (! function_exists('tagsValue'))
{ {
function tagsValue ($field_value) function tagsValue ($field_value)
{ {
// Если есть выделенные теги // Если есть выделенные теги
if (! empty($field_value['tags'])) if (! empty($field_value['tags']))
$tags = $field_value['tags']; $tags = $field_value['tags'];
else else
$tags = array(); $tags = array();
unset ($tags['other']); unset ($tags['other']);
// Если есть теги через зяпятую // Если есть теги через зяпятую
if (! empty($field_value['tags']['other'])) if (! empty($field_value['tags']['other']))
{ {
$tags_new = explode(',', $field_value['tags']['other']); $tags_new = explode(',', $field_value['tags']['other']);
$tags_new = array_map('trim', $tags_new); $tags_new = array_map('trim', $tags_new);
} }
else else
$tags_new = array(); $tags_new = array();
// Совмещаем массивы // Совмещаем массивы
$tags = array_merge($tags, $tags_new); $tags = array_merge($tags, $tags_new);
// Делаем уникальные значения // Делаем уникальные значения
$field_value = array_unique($tags); $field_value = array_unique($tags);
if (empty($field_value)) return $field_value;
$field_value = ''; }
}
return $field_value;
} if (! function_exists('afterTagsSave'))
} {
function afterTagsSave ($data)
if (! function_exists('afterTagsSave')) {
{ global $AVE_Document;
function afterTagsSave ($data)
{ if (! $AVE_Document)
global $AVE_Document; {
require_once BASE_DIR . '/class/class.docs.php';
if (! $AVE_Document)
{ $AVE_Document = new AVE_Document();
require_once BASE_DIR . '/class/class.docs.php'; }
$AVE_Document = new AVE_Document(); foreach ($data['data']['feld'] AS $_k => $_v)
} {
if (array_key_exists('tags', $_v))
foreach ($data['data']['feld'] AS $_k => $_v) {
{ $tags = tagsValue($_v);
if (array_key_exists('tags', $_v))
{ if (! empty($tags))
$tags = tagsValue($_v); {
$tags = implode(',', $tags);
if (! empty($tags)) $AVE_Document->saveTags($data['document_id'], $data['rubric_id'], $tags);
{ }
$tags = implode(',', $tags); }
$AVE_Document->saveTags($data['document_id'], $data['rubric_id'], $tags); }
} }
} }
}
}
}
?> ?>

6
functions/func.block.php

@ -15,10 +15,12 @@
* Обработка тега блока * Обработка тега блока
* *
* @param int $id идентификатор системного блока * @param int $id идентификатор системного блока
*
* @return bool|mixed|null|string|string[]
*/ */
function parse_block($id) function parse_block($id)
{ {
global $AVE_DB, $AVE_Core; global $AVE_DB;
if (is_array($id)) if (is_array($id))
$id = $id[1]; $id = $id[1];
@ -97,5 +99,7 @@
return $return; return $return;
} }
return false;
} }
?> ?>

6
functions/func.breadcrumbs.php

@ -210,13 +210,9 @@
$bread_crumb .= sprintf($bread_self_box, $current->document_breadcrum_title); $bread_crumb .= sprintf($bread_self_box, $current->document_breadcrum_title);
if (! $noprint) if (! $noprint)
{
$crumbs[$curent_document] = sprintf($bread_box, $bread_crumb); $crumbs[$curent_document] = sprintf($bread_box, $bread_crumb);
}
else else
{ $crumbs[$curent_document] = '';
$crumbs[$curent_document] = '';
}
unset($bread_crumb); unset($bread_crumb);

104
functions/func.common.php

@ -22,6 +22,10 @@
/** /**
* Функция загрузки файлов с удаленного сервера через CURL * Функция загрузки файлов с удаленного сервера через CURL
* как альтернатива для file_get_conents * как альтернатива для file_get_conents
*
* @param $sourceFileName
*
* @return mixed
*/ */
function CURL_file_get_contents($sourceFileName) function CURL_file_get_contents($sourceFileName)
{ {
@ -32,6 +36,7 @@
$st = curl_exec($ch); $st = curl_exec($ch);
curl_close($ch); curl_close($ch);
return ($st); return ($st);
} }
@ -131,17 +136,20 @@
* @internal param int $id идентификатор запроса * @internal param int $id идентификатор запроса
* @return string * @return string
*/ */
function eval2var($expression) if (! function_exists("eval2var"))
{ {
global $AVE_DB, $AVE_Core, $AVE_Template; function eval2var($expression)
{
global $AVE_DB, $AVE_Core, $AVE_Template;
ob_start(); ob_start();
eval($expression); eval($expression);
$content = ob_get_clean(); $content = ob_get_clean();
return $content; return $content;
}
} }
@ -510,6 +518,13 @@
/** /**
* Вывод статистики * Вывод статистики
*
* @param int $t
* @param int $m
* @param int $q
* @param int $l
*
* @return string
*/ */
function get_statistic($t=0, $m=0, $q=0, $l=0) function get_statistic($t=0, $m=0, $q=0, $l=0)
{ {
@ -538,6 +553,11 @@
/** /**
* Комментарии в SMARTY * Комментарии в SMARTY
*
* @param $tpl_source
* @param $smarty
*
* @return string
*/ */
function add_template_comment($tpl_source, &$smarty) function add_template_comment($tpl_source, &$smarty)
{ {
@ -549,11 +569,11 @@
* Получения списка стран * Получения списка стран
* *
* @param int $status статус стран входящих в список * @param int $status статус стран входящих в список
* <ul> * <ul>
* <li>1 - активные страны</li> * <li>1 - активные страны</li>
* <li>0 - неактивные страны</li> * <li>0 - неактивные страны</li>
* </ul> * </ul>
* если не указано возвращает список стран без учета статуса * если не указано возвращает список стран без учета статуса
* *
* @return array * @return array
*/ */
@ -612,10 +632,10 @@
closedir($handle); closedir($handle);
} }
$return = array( //$return = array(
'files' => $files, // 'files' => $files,
'thumbs' => $thumbs // 'thumbs' => $thumbs
); //);
return $files; return $files;
} }
@ -630,6 +650,8 @@
{ {
$dir = BASE_DIR . "/" . $path; $dir = BASE_DIR . "/" . $path;
$files = array();
if ($handle = opendir($dir)) if ($handle = opendir($dir))
{ {
while (false !== ($file = readdir($handle))) while (false !== ($file = readdir($handle)))
@ -645,6 +667,7 @@
} }
closedir($handle); closedir($handle);
} }
return $files; return $files;
} }
@ -685,13 +708,15 @@
/** /**
* Функция записывает в указанную папку .htaccess с содержанием "Deny from all" * Функция записывает в указанную папку .htaccess с содержанием "Deny from all"
* *
* @param $dir
*/ */
function write_htaccess_deny($dir) function write_htaccess_deny($dir)
{ {
$file = $dir . '/.htaccess'; $file = $dir . '/.htaccess';
if(! file_exists($file))
if (! file_exists($file))
{ {
if(! is_dir($dir)) if (! is_dir($dir))
@mkdir($dir); @mkdir($dir);
@file_put_contents($dir . '/.htaccess','Deny from all'); @file_put_contents($dir . '/.htaccess','Deny from all');
@ -751,7 +776,7 @@
$object = (array)$object; $object = (array)$object;
if ($object === array()) if ($object === array())
return; return $object;
foreach($object as $key => &$value) foreach($object as $key => &$value)
{ {
@ -771,15 +796,15 @@
* msort() can be used to sort a rowset like array on one or more * msort() can be used to sort a rowset like array on one or more
* 'headers' (keys in the 2th array). * 'headers' (keys in the 2th array).
* *
* @param array $array The array to sort. * @param array $array The array to sort.
* @param string|array $key The index(es) to sort the array on. * @param string|array $key The index(es) to sort the array on.
* @param int $sort_flags The optional parameter to modify the sorting * @param int $sort_flags The optional parameter to modify the sorting
* @param string $sort_way The optional parameter to modify the sorting as DESC or ASC * @param int $sort_way The optional parameter to modify the sorting as DESC or ASC
* behavior. This parameter does not work when * behavior. This parameter does not work when
* supplying an array in the $key parameter. * supplying an array in the $key parameter.
* *
* @return array The sorted array. * @return array The sorted array.
*/ */
function msort($array, $key, $sort_flags = SORT_REGULAR, $sort_way = SORT_ASC) function msort($array, $key, $sort_flags = SORT_REGULAR, $sort_way = SORT_ASC)
{ {
if (is_array($array) && count($array) > 0) if (is_array($array) && count($array) > 0)
@ -792,7 +817,7 @@
{ {
$sort_key = ''; $sort_key = '';
if (!is_array($key)) if ( !is_array($key))
{ {
$sort_key = $v[$key]; $sort_key = $v[$key];
} }
@ -852,7 +877,6 @@
* *
* @param string $string * @param string $string
* @param $limit * @param $limit
* @return string
*/ */
function findautor($string, $limit) function findautor($string, $limit)
{ {
@ -878,6 +902,7 @@
); );
$users = array(); $users = array();
while ($row = $sql->FetchRow()) while ($row = $sql->FetchRow())
{ {
$ava=getAvatar($row->Id,40); $ava=getAvatar($row->Id,40);
@ -890,6 +915,7 @@
'avatar'=>($ava ? $ava : ABS_PATH.'admin/templates/images/user.png') 'avatar'=>($ava ? $ava : ABS_PATH.'admin/templates/images/user.png')
); );
} }
echo json_encode($users); echo json_encode($users);
} }
@ -926,7 +952,6 @@
/** /**
* Функция поиска тегов * Функция поиска тегов
* *
* @param string $string - запрос
* @return string * @return string
*/ */
function searchTags() function searchTags()
@ -942,12 +967,10 @@
$tags = array(); $tags = array();
$ii = 0; //$ii = 0;
while ($row = $sql->GetCell()) while ($row = $sql->GetCell())
{
$tags[]['value'] = $row; $tags[]['value'] = $row;
}
echo json_encode($tags); echo json_encode($tags);
exit; exit;
@ -1002,6 +1025,8 @@
/** /**
* Создание cookie * Создание cookie
*
* @param string $cookie_domain
*/ */
function set_cookie_domain($cookie_domain = '') function set_cookie_domain($cookie_domain = '')
{ {
@ -1039,7 +1064,7 @@
/** /**
* Функция проверяет наличие Ajax запроса * Функция проверяет наличие Ajax запроса
* *
* @return bool true|false - Ajax * @return bool
*/ */
function isAjax() function isAjax()
{ {
@ -1050,6 +1075,8 @@
/** /**
* Функция делает html в 1 строчку, удаляет лишние пробелы, комментарии и т.д. * Функция делает html в 1 строчку, удаляет лишние пробелы, комментарии и т.д.
* *
* @param $data
*
* @return string * @return string
*/ */
function compress_htlm($data) function compress_htlm($data)
@ -1077,7 +1104,8 @@
/** /**
* Функция делает компрессию данных * Функция делает компрессию данных
* *
* @return string * @param $data
*
*/ */
function output_compress($data) function output_compress($data)
{ {
@ -1132,15 +1160,21 @@
* Функция создает короткий URL документа для редиректа * Функция создает короткий URL документа для редиректа
* После выполения функции нужно очистить кеш данного документа * После выполения функции нужно очистить кеш данного документа
* *
* @return * @param int $length
* @param $doc_id
*
* @return bool
*/ */
function gen_short_link ($length = 1, $doc_id) function gen_short_link ($length, $doc_id)
{ {
global $AVE_DB; global $AVE_DB;
if (! is_numeric($doc_id)) if (! is_numeric($doc_id))
return false; return false;
if (! $length)
$length = 1;
// Проврека на существование редиректа для данного документа // Проврека на существование редиректа для данного документа
$check_doc = $AVE_DB->Query(" $check_doc = $AVE_DB->Query("
SELECT SELECT

4
functions/func.documents.php

@ -79,7 +79,7 @@
* @param int $doc_id - номер id документа * @param int $doc_id - номер id документа
* @param string $key - параметр документа * @param string $key - параметр документа
* *
* @return string * @return string | bool | array
*/ */
function get_document ($doc_id , $key ='') function get_document ($doc_id , $key ='')
{ {
@ -114,7 +114,7 @@
* *
* @param int $doc_id - номер id документа * @param int $doc_id - номер id документа
* *
* @return object * @return object | bool
*/ */
function getDocument ($doc_id) function getDocument ($doc_id)
{ {

36
functions/func.fields.php

@ -104,6 +104,8 @@
/** /**
* Возвращаем тип поля * Возвращаем тип поля
* *
* @param string $type
*
* @return mixed * @return mixed
*/ */
function get_field_type ($type = '') function get_field_type ($type = '')
@ -129,14 +131,10 @@
$id = substr($v, strlen('get_field_')); $id = substr($v, strlen('get_field_'));
if ($name != false && is_string($name)) if ($name != false && is_string($name))
$fields[] = array('id' => $id,'name' => (isset($fields_vars[$name]) $fields[] = array('id' => $id, 'name' => $name);
? $fields_vars[$name]
: $name));
if (! empty($type) && $id == $type) if (! empty($type) && $id == $type)
$field = array('id' => $id,'name' => (isset($fields_vars[$name]) $field = array('id' => $id, 'name' => $name);
? $fields_vars[$name]
: $name));
} }
else else
continue; continue;
@ -165,7 +163,7 @@
if (isset($alias_field_id[$id])) if (isset($alias_field_id[$id]))
return $alias_field_id[$id]; return $alias_field_id[$id];
$alias_field_id[$id] = $AVE_DB->Query("SELECT rubric_field_alias FROM " . PREFIX . "_rubric_fields WHERE Id=".intval($id))->GetCell(); $alias_field_id[$id] = $AVE_DB->Query("SELECT rubric_field_alias FROM " . PREFIX . "_rubric_fields WHERE Id=" . intval($id))->GetCell();
return $alias_field_id[$id]; return $alias_field_id[$id];
} }
@ -193,10 +191,10 @@
FROM FROM
" . PREFIX . "_rubric_fields " . PREFIX . "_rubric_fields
WHERE WHERE
(rubric_field_alias = '".addslashes($alias)."' (rubric_field_alias = '" . addslashes($alias) . "'
OR Id = '".intval($alias)."') OR Id = '" . intval($alias) . "')
AND AND
rubric_id = ".intval($rubric_id) rubric_id = " . intval($rubric_id)
; ;
$alias_field_id[$rubric_id][$alias] = $AVE_DB->Query($sql)->GetCell(); $alias_field_id[$rubric_id][$alias] = $AVE_DB->Query($sql)->GetCell();
@ -208,7 +206,6 @@
/** /**
* Возвращаем * Возвращаем
* *
* @param $rubric_id
* @param $id * @param $id
* *
* @return string * @return string
@ -286,9 +283,11 @@
* @param int $field_id идентификатор поля * @param int $field_id идентификатор поля
* @param int $document_id * @param int $document_id
* *
* @param null $_tpl
*
* @return string * @return string
*/ */
function document_get_field($field_id, $document_id = null, $_tpl = null) function document_get_field($field_id, $document_id = null, $_tpl = null, $maxlength = null)
{ {
global $AVE_Core; global $AVE_Core;
@ -409,7 +408,7 @@
*/ */
function get_document_fields($document_id, $values = null) function get_document_fields($document_id, $values = null)
{ {
global $AVE_DB, $request_documents, $AVE_Core; global $AVE_DB, $AVE_Core; //$request_documents
static $document_fields = array(); static $document_fields = array();
@ -485,12 +484,10 @@
$row['tpl_req_empty'] = (trim($row['rubric_field_template_request']) == ''); $row['tpl_req_empty'] = (trim($row['rubric_field_template_request']) == '');
$row['tpl_field_empty'] = (trim($row['rubric_field_template']) == ''); $row['tpl_field_empty'] = (trim($row['rubric_field_template']) == '');
$row['field_value']=(string)$row['field_value'].(string)$row['field_value_more']; $row['field_value'] = (string)$row['field_value'] . (string)$row['field_value_more'];
if($values) if ($values)
{
$row['field_value']=(isset($values[$row['rubric_field_id']]) ? $values[$row['rubric_field_id']] : $row['field_value']); $row['field_value']=(isset($values[$row['rubric_field_id']]) ? $values[$row['rubric_field_id']] : $row['field_value']);
}
if ($row['field_value'] === '') if ($row['field_value'] === '')
{ {
@ -731,9 +728,8 @@
/** /**
* Возвращает наименование поля документа по номеру * Возвращает наименование поля документа по номеру
* *
* @param int $field_id ([tag:fld:X]) - номер поля * @param int $field_id ([tag:fld:X]) - номер поля
* @param int $doc_id * @param int $doc_id
* @param int $parametr ([tag:parametr:X]) - часть поля
* *
* @return string * @return string
*/ */

1421
functions/func.helpers.php

File diff suppressed because it is too large Load Diff

6
functions/func.login.php

@ -89,7 +89,7 @@
last_visit = '" . $time . "', last_visit = '" . $time . "',
password = '" . $hash . "', password = '" . $hash . "',
salt = '" . $salt . "', salt = '" . $salt . "',
user_ip = '" . $u_ip . "' user_ip = '" . (int)$u_ip . "'
WHERE WHERE
Id = '" . $row->Id . "' Id = '" . $row->Id . "'
"); ");
@ -129,7 +129,7 @@
" . PREFIX . "_users_session " . PREFIX . "_users_session
(`user_id`,`hash`,`ip`,`agent`,`last_activ`) (`user_id`,`hash`,`ip`,`agent`,`last_activ`)
values values
('" . $row->Id . "','" . addslashes($auth) . "','" . $u_ip . "','" . addslashes($_SERVER['HTTP_USER_AGENT']) . "','" . time() . "') ('" . $row->Id . "','" . addslashes($auth) . "','" . (int)$u_ip . "','" . addslashes($_SERVER['HTTP_USER_AGENT']) . "','" . time() . "')
"; ";
$AVE_DB->Query($sql); $AVE_DB->Query($sql);
@ -293,7 +293,7 @@
" . PREFIX . "_users_session " . PREFIX . "_users_session
SET SET
last_activ = '" . time() . "', last_activ = '" . time() . "',
ip = '" . ip2long($_SERVER['REMOTE_ADDR']) . "' ip = '" . (int)ip2long($_SERVER['REMOTE_ADDR']) . "'
WHERE WHERE
Id = '" . $row->Id . "' Id = '" . $row->Id . "'
"); ");

390
functions/func.mail.php

@ -1,250 +1,252 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
* @version 3.x * @version 3.x
* @filesource * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
* *
* @license GPL v.2 * @license GPL v.2
*/ */
/** /**
* Отправка e-Mail * Отправка e-Mail
* *
* @param string $to - email получателя * @param string $to - email получателя
* @param string $body - текст сообщения * @param string $body - текст сообщения
* @param string $subject - тема сообщения * @param string $subject - тема сообщения
* @param string $from_email - e-mail отправителя * @param string $from_email - e-mail отправителя
* @param string $from_name - имя отправителя * @param string $from_name - имя отправителя
* @param string $type - содержимое (html или text) * @param string $type - содержимое (html или text)
* @param array $attach - пути файлов вложений * @param array $attach - пути файлов вложений
* @param bool $saveattach - сохранять вложения после отправки в ATTACH_DIR? * @param bool $saveattach - сохранять вложения после отправки в ATTACH_DIR?
* @param bool $signature - добавлять подпись из общих настроек? * @param bool $signature - добавлять подпись из общих настроек?
*/ */
if ( ! function_exists('send_mail')) if (! function_exists('send_mail'))
{
function send_mail($to='', $body='', $subject='', $from_email='', $from_name='', $type='text', $attach=array(), $saveattach=true, $signature=true)
{ {
require_once BASE_DIR . '/lib/SwiftMailer/swift_required.php'; function send_mail($to='', $body='', $subject='', $from_email='', $from_name='', $type='text', $attach=array(), $saveattach=true, $signature=true)
{
require_once BASE_DIR . '/lib/SwiftMailer/swift_required.php';
unset($transport, $message, $mailer); unset($transport, $message, $mailer);
$to = str_nospace($to); $to = str_nospace($to);
$from_email = str_nospace($from_email); $from_email = str_nospace($from_email);
// Определяем тип письма // Определяем тип письма
$type = ((strtolower($type) == 'html' || strtolower($type) == 'text/html') ? 'text/html' : 'text/plain'); $type = ((strtolower($type) == 'html' || strtolower($type) == 'text/html') ? 'text/html' : 'text/plain');
// Добавляем подпись, если просили // Добавляем подпись, если просили
if ($signature) if ($signature)
{
if ($type == 'text/html')
{
$signature = '<br><br>' . nl2br(get_settings('mail_signature'));
}
else
{ {
$signature = "\r\n\r\n" . get_settings('mail_signature'); if ($type == 'text/html')
{
$signature = '<br><br>' . nl2br(get_settings('mail_signature'));
}
else
{
$signature = "\r\n\r\n" . get_settings('mail_signature');
}
} }
} else $signature = '';
else $signature = '';
// Составляем тело письма // Составляем тело письма
$body = stripslashes($body) . $signature; $body = stripslashes($body) . $signature;
if ($type == 'text/html') if ($type == 'text/html')
{ {
$body = str_replace(array("\t","\r","\n"),'',$body); $body = str_replace(array("\t","\r","\n"),'',$body);
$body = str_replace(array(' ','> <'),array(' ','><'),$body); $body = str_replace(array(' ','> <'),array(' ','><'),$body);
} }
// Формируем письмо // Формируем письмо
$message = Swift_Message::newInstance($subject) $message = Swift_Message::newInstance($subject)
-> setFrom(array($from_email => $from_name)) -> setFrom(array($from_email => $from_name))
-> setTo($to) -> setTo($to)
-> setContentType($type) -> setContentType($type)
-> setBody($body) -> setBody($body)
-> setMaxLineLength((int)get_settings('mail_word_wrap')); -> setMaxLineLength((int)get_settings('mail_word_wrap'));
// Прикрепляем вложения // Прикрепляем вложения
if ($attach) if ($attach)
{
foreach ($attach as $attach_file)
{ {
$message -> attach(Swift_Attachment::fromPath(trim($attach_file))); foreach ($attach as $attach_file)
{
$message -> attach(Swift_Attachment::fromPath(trim($attach_file)));
}
} }
}
// Выбираем метод отправки и формируем транспорт // Выбираем метод отправки и формируем транспорт
switch (get_settings('mail_type')) switch (get_settings('mail_type'))
{ {
default: default:
case 'mail': case 'mail':
$transport = Swift_MailTransport::newInstance(); $transport = Swift_MailTransport::newInstance();
break; break;
case 'smtp': case 'smtp':
$transport = Swift_SmtpTransport::newInstance(stripslashes(get_settings('mail_host')), (int)get_settings('mail_port')); $transport = Swift_SmtpTransport::newInstance(stripslashes(get_settings('mail_host')), (int)get_settings('mail_port'));
// Добавляем шифрование // Добавляем шифрование
$smtp_encrypt = get_settings('mail_smtp_encrypt'); $smtp_encrypt = get_settings('mail_smtp_encrypt');
if($smtp_encrypt) if($smtp_encrypt)
$transport $transport
->setEncryption(strtolower(stripslashes($smtp_encrypt))); ->setEncryption(strtolower(stripslashes($smtp_encrypt)));
// Имя пользователя/пароль // Имя пользователя/пароль
$smtp_user = get_settings('mail_smtp_login'); $smtp_user = get_settings('mail_smtp_login');
$smtp_pass = get_settings('mail_smtp_pass'); $smtp_pass = get_settings('mail_smtp_pass');
if($smtp_user) if($smtp_user)
$transport $transport
->setUsername(stripslashes($smtp_user)) ->setUsername(stripslashes($smtp_user))
->setPassword(stripslashes($smtp_pass)); ->setPassword(stripslashes($smtp_pass));
break; break;
case 'sendmail': case 'sendmail':
$transport = Swift_SendmailTransport::newInstance(get_settings('mail_sendmail_path')); $transport = Swift_SendmailTransport::newInstance(get_settings('mail_sendmail_path'));
break; break;
} }
// Сохраняем вложения в ATTACH_DIR, если просили // Сохраняем вложения в ATTACH_DIR, если просили
if ($attach && $saveattach) if ($attach && $saveattach)
{
$attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path)
{ {
if ($file_path && file_exists($file_path)) $attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path)
{ {
$file_name = basename($file_path); if ($file_path && file_exists($file_path))
$file_name = str_replace(' ','',mb_strtolower(trim($file_name)));
if (file_exists($attach_dir . $file_name))
{
$file_name = rand(1000, 9999) . '_' . $file_name;
}
$file_path_new = $attach_dir . $file_name;
if (!@move_uploaded_file($file_path,$file_path_new))
{ {
copy($file_path,$file_path_new); $file_name = basename($file_path);
$file_name = str_replace(' ','',mb_strtolower(trim($file_name)));
if (file_exists($attach_dir . $file_name))
{
$file_name = rand(1000, 9999) . '_' . $file_name;
}
$file_path_new = $attach_dir . $file_name;
if (!@move_uploaded_file($file_path,$file_path_new))
{
copy($file_path,$file_path_new);
}
} }
} }
} }
}
// Отправляем письмо // Отправляем письмо
/** @var $transport TYPE_NAME */ /** @var $transport TYPE_NAME */
$mailer = Swift_Mailer::newInstance($transport); $mailer = Swift_Mailer::newInstance($transport);
if (!@$mailer -> send($message, $failures)) if (!@$mailer -> send($message, $failures))
{ {
reportLog('Не удалось отправить письма следующим адресатам: ' . implode(',',$failures)); reportLog('Не удалось отправить письма следующим адресатам: ' . implode(',',$failures));
return $failures; return $failures;
} }
}
} }
}
if ( ! function_exists('safe_mailto')) if ( ! function_exists('safe_mailto'))
{
function safe_mailto($email, $title = '', $attributes = '')
{ {
$title = (string) $title; function safe_mailto($email, $title = '', $attributes = '')
if ($title == "")
{ {
$title = $email; $title = (string) $title;
}
for ($i = 0; $i < 16; $i++) if ($title == "")
{ {
$x[] = substr('<a href="mailto:', $i, 1); $title = $email;
} }
for ($i = 0; $i < strlen($email); $i++) for ($i = 0; $i < 16; $i++)
{ {
$x[] = "|".ord(substr($email, $i, 1)); $x[] = substr('<a href="mailto:', $i, 1);
} }
$x[] = '"'; for ($i = 0; $i < strlen($email); $i++)
{
$x[] = "|".ord(substr($email, $i, 1));
}
if ($attributes != '') $x[] = '"';
{
if (is_array($attributes)) if ($attributes != '')
{ {
foreach ($attributes as $key => $val) if (is_array($attributes))
{ {
$x[] = ' '.$key.'="'; foreach ($attributes as $key => $val)
for ($i = 0; $i < strlen($val); $i++)
{ {
$x[] = "|".ord(substr($val, $i, 1)); $x[] = ' '.$key.'="';
for ($i = 0; $i < strlen($val); $i++)
{
$x[] = "|".ord(substr($val, $i, 1));
}
$x[] = '"';
} }
$x[] = '"';
} }
} else
else
{
for ($i = 0; $i < strlen($attributes); $i++)
{ {
$x[] = substr($attributes, $i, 1); for ($i = 0; $i < strlen($attributes); $i++)
{
$x[] = substr($attributes, $i, 1);
}
} }
} }
}
$x[] = '>'; $x[] = '>';
$temp = array(); $temp = array();
for ($i = 0; $i < strlen($title); $i++) for ($i = 0; $i < strlen($title); $i++)
{
$ordinal = ord($title[$i]);
if ($ordinal < 128)
{ {
$x[] = "|".$ordinal; $ordinal = ord($title[$i]);
}
else if ($ordinal < 128)
{
if (count($temp) == 0)
{ {
$count = ($ordinal < 224) ? 2 : 3; $x[] = "|".$ordinal;
} }
else
$temp[] = $ordinal;
if (count($temp) == $count)
{ {
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64); if (count($temp) == 0)
$x[] = "|".$number; {
$count = 1; $count = ($ordinal < 224) ? 2 : 3;
$temp = array(); }
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$x[] = "|".$number;
$count = 1;
$temp = array();
}
} }
} }
}
$x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
$x = array_reverse($x); $x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
ob_start();
$x = array_reverse($x);
?><script type="text/javascript"> ob_start();
//<![CDATA[
var l=new Array(); ?><script type="text/javascript">
<?php //<![CDATA[
$i = 0; var l=new Array();
foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?> <?php
$i = 0;
for (var i = l.length-1; i >= 0; i=i-1){ foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?>
if (l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else document.write(unescape(l[i]));} for (var i = l.length-1; i >= 0; i=i-1){
//]]> if
</script><?php (l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else
$buffer = ob_get_contents(); document.write(unescape(l[i]));}
ob_end_clean(); //]]>
return $buffer; </script><?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
} }
}
?> ?>

119
functions/func.modulglobals.php

@ -1,71 +1,72 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
* @version 3.x * @version 3.x
* @filesource * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
* *
* @license GPL v.2 * @license GPL v.2
*/ */
/** /**
* Функция формирует глобальный массив $mod с элементами: * Функция формирует глобальный массив $mod с элементами:
* <pre> * <pre>
* tpl_dir путь к папке с шаблонами модуля * tpl_dir путь к папке с шаблонами модуля
* theme_folder имя папки с файлами дизайна * theme_folder имя папки с файлами дизайна
* config_vars массив с языковыми переменными модуля * config_vars массив с языковыми переменными модуля
* </pre> * </pre>
* Формирует и передаёт в шаблонизатор: * Формирует и передаёт в шаблонизатор:
* <pre> * <pre>
* $tpl_dir путь к папке с шаблонами модуля * $tpl_dir путь к папке с шаблонами модуля
* $mod_dir имя папки с модулями * $mod_dir имя папки с модулями
* $config_vars массив с языковыми переменными модуля * $config_vars массив с языковыми переменными модуля
* </pre> * </pre>
* Регистрирует в шаблонизаторе функцию in_array * Регистрирует в шаблонизаторе функцию in_array
* *
* @param string $modulepath имя папки модуля * @param string $modulepath имя папки модуля
* @param string $lang_section секция языкового файла * @param string $lang_section секция языкового файла
*/ */
function set_module_globals($modulepath, $lang_section = false) function set_module_globals($modulepath, $lang_section = false)
{ {
global $mod, $AVE_Template; global $mod, $AVE_Template;
$tpl_dir = BASE_DIR . '/modules/' . $modulepath . '/templates/'; $tpl_dir = BASE_DIR . '/modules/' . $modulepath . '/templates/';
$lang_file = BASE_DIR . '/modules/' . $modulepath . '/lang/' . $_SESSION['user_language'] . '.txt'; $lang_file = BASE_DIR . '/modules/' . $modulepath . '/lang/' . $_SESSION['user_language'] . '.txt';
if (!file_exists($lang_file)) if (!file_exists($lang_file))
{ {
$lang_file = BASE_DIR . '/modules/' . $modulepath . '/lang/ru.txt'; $lang_file = BASE_DIR . '/modules/' . $modulepath . '/lang/ru.txt';
} }
if (!file_exists($lang_file)) if (!file_exists($lang_file))
{ {
display_notice('Ошибка! Отсутствует языковой файл. Пожалуйста, проверьте язык, установленный по умолчанию, в файле '.ABS_PATH.'inc/config.php'); display_notice('Ошибка! Отсутствует языковой файл. Пожалуйста, проверьте язык, установленный по умолчанию, в файле '.ABS_PATH.'inc/config.php');
exit; exit;
} }
if ($lang_section === false) if ($lang_section === false)
{ {
$AVE_Template->config_load($lang_file); $AVE_Template->config_load($lang_file);
} }
else else
{ {
$AVE_Template->config_load($lang_file, $lang_section); $AVE_Template->config_load($lang_file, $lang_section);
} }
$config_vars = $AVE_Template->get_config_vars();
$AVE_Template->assign('tpl_dir', $tpl_dir); $config_vars = $AVE_Template->get_config_vars();
$AVE_Template->assign('mod_dir', BASE_DIR . '/modules');
$AVE_Template->assign('config_vars', $config_vars);
$mod['tpl_dir'] = $tpl_dir; $AVE_Template->assign('tpl_dir', $tpl_dir);
$mod['theme_folder'] = defined('THEME_FOLDER') ? THEME_FOLDER : DEFAULT_THEME_FOLDER; $AVE_Template->assign('mod_dir', BASE_DIR . '/modules');
$mod['config_vars'] = $config_vars; $AVE_Template->assign('config_vars', $config_vars);
$AVE_Template->register_function('in_array', 'in_array'); $mod['tpl_dir'] = $tpl_dir;
} $mod['theme_folder'] = defined('THEME_FOLDER') ? THEME_FOLDER : DEFAULT_THEME_FOLDER;
$mod['config_vars'] = $config_vars;
$AVE_Template->register_function('in_array', 'in_array');
}
?> ?>

2
functions/func.navigation.php

@ -75,7 +75,7 @@
if (! $navi_menu) if (! $navi_menu)
{ {
echo 'Menu ', $navi_id, ' not found!'; echo 'Menu ', $navi_id, ' not found!';
return; return '';
} }
// выставляем гостевую группу по дефолту // выставляем гостевую группу по дефолту

230
functions/func.pagination.php

@ -1,141 +1,141 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
* @version 3.x * @version 3.x
* @filesource * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
* *
* @license GPL v.2 * @license GPL v.2
*/ */
/** /**
* Текущая страница * Текущая страница
* *
* @param string $type тип постраничной навигации, * @param string $type тип постраничной навигации,
* допустимые значения: page, apage, artpage * допустимые значения: page, apage, artpage
* @return int номер текущей страницы * @return int номер текущей страницы
*/ */
function get_current_page($type = 'page') function get_current_page($type = 'page')
{
if (!in_array($type, array('page', 'apage', 'artpage'))) return 1;
$page = (isset($_REQUEST[$type]) && is_numeric($_REQUEST[$type])) ? $_REQUEST[$type] : 1;
return (int)$page;
}
/**
* Постраничная навигация для запросов и модулей
*
* @param int $total_pages количество страниц в документе
* @param string $type тип постраничной навигации,
* допустимые значения: page, apage, artpage
* @param string $template_label шаблон метки навигации
* @param string $navi_box контейнер постраничной навигации %s
* @return string HTML-код постраничной навигации
*/
function get_pagination($total_pages, $type, $template_label, $navi_box = '')
{
$nav = '';
if (!in_array($type, array('page', 'apage', 'artpage'))) $type = 'page';
$curent_page = get_current_page($type);
if ($curent_page == 1) $pages = array ($curent_page, $curent_page+1, $curent_page+2, $curent_page+3, $curent_page+4);
elseif ($curent_page == 2) $pages = array ($curent_page-1, $curent_page, $curent_page+1, $curent_page+2, $curent_page+3);
elseif ($curent_page+1 == $total_pages) $pages = array ($curent_page-3, $curent_page-2, $curent_page-1, $curent_page, $curent_page+1);
elseif ($curent_page == $total_pages) $pages = array ($curent_page-4, $curent_page-3, $curent_page-2, $curent_page-1, $curent_page);
else $pages = array ($curent_page-2, $curent_page-1, $curent_page, $curent_page+1, $curent_page+2);
$pages = array_unique($pages);
$link_box = trim(get_settings('link_box')); // Контенйнер для ссылок %s
$separator_box = trim(get_settings('separator_box')); // Контенйнер для метки о наличии страниц кроме видимых %s
$total_box = trim(get_settings('total_box')); // Контенйнер для Страница ХХХ из ХХХ %s
$active_box = trim(get_settings('active_box')); // Контенйнер для активного элемента %s
$total_label = trim(get_settings('total_label')); // Текст перед номерами страниц %d
$start_label = trim(get_settings('start_label')); // Текст ссылки "Первая"
$end_label = trim(get_settings('end_label')); // Текст ссылки "Последняя"
$separator_label = trim(get_settings('separator_label')); // Текст метки о наличии страниц кроме видимых
$next_label = trim(get_settings('next_label')); // Текст ссылки "Следующая"
$prev_label = trim(get_settings('prev_label')); // Текст ссылки "Предыдущая"
// Первая
if ($total_pages > 5 && $curent_page > 3)
{ {
$first = str_replace('data-pagination="{s}"', 'data-pagination="1"', $template_label); if (!in_array($type, array('page', 'apage', 'artpage'))) return 1;
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $start_label, str_replace(array('&amp;'. $type .'={s}', '&' . $type .'={s}', '/' . $type . '-{s}'), '', $first))); $page = (isset($_REQUEST[$type]) && is_numeric($_REQUEST[$type])) ? $_REQUEST[$type] : 1;
if ($separator_label != '')
$nav .= sprintf($separator_box, $separator_label);
}
// Предыдущая return (int)$page;
if ($curent_page > 1)
{
if ($curent_page - 1 == 1)
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $prev_label, str_replace(array('&amp;'. $type .'={s}', '&' . $type .'={s}', '/' . $type . '-{s}'), '', $template_label)));
else
$nav .= sprintf($link_box, str_replace('{t}', $prev_label, str_replace('{s}', ($curent_page - 1), $template_label)));
} }
foreach($pages as $val) /**
* Постраничная навигация для запросов и модулей
*
* @param int $total_pages количество страниц в документе
* @param string $type тип постраничной навигации,
* допустимые значения: page, apage, artpage
* @param string $template_label шаблон метки навигации
* @param string $navi_box контейнер постраничной навигации %s
* @return string HTML-код постраничной навигации
*/
function get_pagination($total_pages, $type, $template_label, $navi_box = '')
{ {
if ($val >= 1 && $val <= $total_pages) $nav = '';
if (!in_array($type, array('page', 'apage', 'artpage'))) $type = 'page';
$curent_page = get_current_page($type);
if ($curent_page == 1) $pages = array ($curent_page, $curent_page+1, $curent_page+2, $curent_page+3, $curent_page+4);
elseif ($curent_page == 2) $pages = array ($curent_page-1, $curent_page, $curent_page+1, $curent_page+2, $curent_page+3);
elseif ($curent_page+1 == $total_pages) $pages = array ($curent_page-3, $curent_page-2, $curent_page-1, $curent_page, $curent_page+1);
elseif ($curent_page == $total_pages) $pages = array ($curent_page-4, $curent_page-3, $curent_page-2, $curent_page-1, $curent_page);
else $pages = array ($curent_page-2, $curent_page-1, $curent_page, $curent_page+1, $curent_page+2);
$pages = array_unique($pages);
$link_box = trim(get_settings('link_box')); // Контенйнер для ссылок %s
$separator_box = trim(get_settings('separator_box')); // Контенйнер для метки о наличии страниц кроме видимых %s
$total_box = trim(get_settings('total_box')); // Контенйнер для Страница ХХХ из ХХХ %s
$active_box = trim(get_settings('active_box')); // Контенйнер для активного элемента %s
$total_label = trim(get_settings('total_label')); // Текст перед номерами страниц %d
$start_label = trim(get_settings('start_label')); // Текст ссылки "Первая"
$end_label = trim(get_settings('end_label')); // Текст ссылки "Последняя"
$separator_label = trim(get_settings('separator_label')); // Текст метки о наличии страниц кроме видимых
$next_label = trim(get_settings('next_label')); // Текст ссылки "Следующая"
$prev_label = trim(get_settings('prev_label')); // Текст ссылки "Предыдущая"
// Первая
if ($total_pages > 5 && $curent_page > 3)
{ {
if ($curent_page == $val) $first = str_replace('data-pagination="{s}"', 'data-pagination="1"', $template_label);
{
// Текущий номер страницы (активная страница) $nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $start_label, str_replace(array('&amp;'. $type .'={s}', '&' . $type .'={s}', '/' . $type . '-{s}'), '', $first)));
$nav .= sprintf($link_box, sprintf($active_box, str_replace(array('{s}', '{t}'), $val, $curent_page))); if ($separator_label != '')
} $nav .= sprintf($separator_box, $separator_label);
}
// Предыдущая
if ($curent_page > 1)
{
if ($curent_page - 1 == 1)
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $prev_label, str_replace(array('&amp;'. $type .'={s}', '&' . $type .'={s}', '/' . $type . '-{s}'), '', $template_label)));
else else
$nav .= sprintf($link_box, str_replace('{t}', $prev_label, str_replace('{s}', ($curent_page - 1), $template_label)));
}
foreach($pages as $val)
{
if ($val >= 1 && $val <= $total_pages)
{ {
if ($val == 1) if ($curent_page == $val)
{ {
// Страница номер 1 // Текущий номер страницы (активная страница)
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $val, str_replace(array('&amp;'.$type.'={s}','&'.$type.'={s}','/'.$type.'-{s}'), '', $template_label))); $nav .= sprintf($link_box, sprintf($active_box, str_replace(array('{s}', '{t}'), $val, $curent_page)));
} }
else else
{ {
// Остальные неактивные номера страниц if ($val == 1)
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $val, $template_label)); {
// Страница номер 1
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $val, str_replace(array('&amp;'.$type.'={s}','&'.$type.'={s}','/'.$type.'-{s}'), '', $template_label)));
}
else
{
// Остальные неактивные номера страниц
$nav .= sprintf($link_box, str_replace(array('{s}', '{t}'), $val, $template_label));
}
} }
} }
} }
}
// Следующая // Следующая
if ($curent_page < $total_pages) if ($curent_page < $total_pages)
{ {
$nav .= sprintf($link_box, str_replace('{t}', $next_label, str_replace('{s}', ($curent_page + 1), $template_label))); $nav .= sprintf($link_box, str_replace('{t}', $next_label, str_replace('{s}', ($curent_page + 1), $template_label)));
} }
// Последняя // Последняя
if ($total_pages > 5 && ($curent_page < $total_pages-2)) if ($total_pages > 5 && ($curent_page < $total_pages-2))
{ {
if ($separator_label != '') if ($separator_label != '')
$nav .= sprintf($separator_box, $separator_label); $nav .= sprintf($separator_box, $separator_label);
$nav .= sprintf($link_box, str_replace('{t}', $end_label, str_replace('{s}', $total_pages, $template_label))); $nav .= sprintf($link_box, str_replace('{t}', $end_label, str_replace('{s}', $total_pages, $template_label)));
} }
// Страница ХХХ из ХХХ // Страница ХХХ из ХХХ
if ($nav != '') if ($nav != '')
{ {
if ($total_label != '') if ($total_label != '')
$nav = sprintf($total_box, sprintf($total_label, $curent_page, $total_pages)) . $nav; $nav = sprintf($total_box, sprintf($total_label, $curent_page, $total_pages)) . $nav;
// Оборачиваем в общий контейнер // Оборачиваем в общий контейнер
if ($navi_box != '') if ($navi_box != '')
$nav = sprintf($navi_box, $nav); $nav = sprintf($navi_box, $nav);
} }
return $nav; return $nav;
} }
?> ?>

197
functions/func.parserequest.php

@ -11,6 +11,14 @@
* @license GPL v.2 * @license GPL v.2
*/ */
/**
* Достаем настройки запроса
*
* @param $id
*
* @return string
*/
function request_get_settings($id) function request_get_settings($id)
{ {
global $AVE_DB; global $AVE_DB;
@ -40,8 +48,10 @@
* Обработка условий запроса. * Обработка условий запроса.
* Возвращает строку условий в SQL-формате * Возвращает строку условий в SQL-формате
* *
* @param int $id идентификатор запроса * @param int $id идентификатор запроса
* @return string * @param bool $update_db
*
* @return array
*/ */
function request_get_condition_sql_string($id, $update_db = false) function request_get_condition_sql_string($id, $update_db = false)
{ {
@ -101,7 +111,7 @@
// значение для условия // значение для условия
$val = trim($row_ak->condition_value); $val = trim($row_ak->condition_value);
// если это поле используется для выпадающего списка или пустое значение для условия, пропускаем // если это поле используется для выпадающего списка или пустое значение для условия, пропускаем
if (isset($_POST['req_' . $id]) && isset($_POST['req_' . $id][$fid]) || $val==='') if (isset($_POST['req_' . $id]) && isset($_POST['req_' . $id][$fid]) || $val === '')
continue; continue;
// И / ИЛИ // И / ИЛИ
if (! isset($join) && $row_ak->condition_join) if (! isset($join) && $row_ak->condition_join)
@ -122,7 +132,9 @@
")->GetCell(); ")->GetCell();
} }
$fv = $numeric[$fid] ? "t$fid.field_number_value" : "UPPER(t$fid.field_value)"; $fv = $numeric[$fid]
? "t$fid.field_number_value"
: "UPPER(t$fid.field_value)";
// подставляем название таблицы в свободные условия // подставляем название таблицы в свободные условия
$val = addcslashes(str_ireplace(array('[field]','[numeric_field]'),$fv,$val),"'"); $val = addcslashes(str_ireplace(array('[field]','[numeric_field]'),$fv,$val),"'");
@ -130,7 +142,7 @@
// формируем выбор таблицы // формируем выбор таблицы
// первый раз евалом проходим значение и запоминаем это в переменной $v[$i] // первый раз евалом проходим значение и запоминаем это в переменной $v[$i]
// как только таблица выбрана, фиксируем это в $t[$fid], чтобы не выбирать по несколько раз одни и те же таблицы // как только таблица выбрана, фиксируем это в $t[$fid], чтобы не выбирать по несколько раз одни и те же таблицы
$from[] = "<?php \$v[$i] = trim(eval2var(' ?>$val<? ')); \$t = array(); if (\$v[$i]>'' && !isset(\$t[$fid])) {echo \"%%PREFIX%%_document_fields AS t$fid,\"; \$t[$fid]=1;}?>"; $from[] = "<?php \$v[$i] = trim(eval2var(' ?>$val<?php ')); \$t = array(); if (\$v[$i]>'' && !isset(\$t[$fid])) {echo \"%%PREFIX%%_document_fields AS t$fid,\"; \$t[$fid]=1;} ?>";
// обрабатываем условия // обрабатываем условия
switch ($type) switch ($type)
@ -161,8 +173,8 @@
case 'IN=': $where[] = "<?=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv IN (\$v[$i]))) $join\" : ''?>"; break; case 'IN=': $where[] = "<?=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv IN (\$v[$i]))) $join\" : ''?>"; break;
case 'NOTIN=': $where[] = "<?=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT IN (\$v[$i]))) $join\" : ''?>"; break; case 'NOTIN=': $where[] = "<?=(\$v[$i]>'' && \$v[$i]{0}!=',') ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv NOT IN (\$v[$i]))) $join\" : ''?>"; break;
case 'ANY': $where[] = "<?=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv=ANY(\$v[$i]))) $join\" : ''?>"; break; case 'ANY': $where[] = "<?php echo \$v[$i] > '' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND $fv=ANY(\$v[$i]))) $join\" : ''; ?>"; break;
case 'FRE': $where[] = "<?=\$v[$i]>'' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND (\$v[$i]))) $join\" : ''?>"; break; case 'FRE': $where[] = "<?php echo \$v[$i] > '' ? \"(t$fid.document_id = a.id AND (t$fid.rubric_field_id = '$fid' AND (\$v[$i]))) $join\" : ''; ?>"; break;
} }
$i++; $i++;
@ -177,14 +189,14 @@
$from = (isset($from_dd) ? array_merge($from, $from_dd) : $from); $from = (isset($from_dd) ? array_merge($from, $from_dd) : $from);
$from = implode(' ', $from); $from = implode(' ', $from);
$where_dd = (isset($where_dd) ? ' AND ' : '') . implode(' AND ', $where_dd); $where_dd = (isset($where_dd) ? ' AND ' : '') . implode(' AND ', $where_dd);
$where = implode(' ', $where) . " <?php \$a = array(); echo (!array_sum(\$a) || '$join'=='AND') ? '1=1' : '1=0'?>"; $where = implode(' ', $where) . " <?php \$a = array(); echo (!array_sum(\$a) || '$join'=='AND') ? '1=1' : '1=0'; ?>";
$retval = array('from'=>$from,'where'=> $where.$where_dd); $retval = array('from' => $from, 'where' => $where . $where_dd);
} }
else else
{ {
$from = implode(' ', $from); $from = implode(' ', $from);
$where = implode(' ', $where) . " <?php \$a = array(); echo (!array_sum(\$a) || '$join'=='AND') ? '1=1' : '1=0'?>"; $where = implode(' ', $where) . " <?php \$a = array(); echo (!array_sum(\$a) || '$join'=='AND') ? '1=1' : '1=0'; ?>";
$retval = array('from'=>$from,'where'=> $where); $retval = array('from' => $from, 'where' => $where);
} }
} }
@ -207,14 +219,19 @@
} }
/* /**
* Функция принимает строку, и возвращает * Функция принимает строку, и возвращает
* адрес первого изображения, которую найдет * адрес первого изображения, которую найдет
*/ *
* @param $data
*
* @return string
*/
function getImgSrc($data) function getImgSrc($data)
{ {
preg_match_all("/(<img )(.+?)( \/)?(>)/u", $data, $images); $_req_exp = '/(<img )(.+?)( \/)?(>)/u';
preg_match_all($_req_exp, $data, $images);
$host = $images[2][0]; $host = $images[2][0];
@ -232,23 +249,22 @@
preg_match('/(.+)' . THUMBNAIL_DIR . '\/(.+)-.\d+x\d+(\..+)/u', $host, $matches); preg_match('/(.+)' . THUMBNAIL_DIR . '\/(.+)-.\d+x\d+(\..+)/u', $host, $matches);
if (isset($matches[1])) if (isset($matches[1]))
{
return $matches[1] . $matches[2] . $matches[3]; return $matches[1] . $matches[2] . $matches[3];
}
else else
{ return $host;
return $host;
}
} }
} }
/** /**
* Функция обработки тэгов полей с использованием шаблонов * Функция обработки тэгов полей с использованием шаблонов
* в соответствии с типом поля * в соответствии с типом поля
* *
* @param int $rubric_id идентификатор рубрики * @param $field_id
* @param int $document_id идентификатор документа * @param int $document_id идентификатор документа
* @param int $maxlength максимальное количество символов обрабатываемого поля * @param string $maxlength максимальное количество символов обрабатываемого поля
* @param int $rubric_id идентификатор рубрики
*
* @return string * @return string
*/ */
function request_get_document_field($field_id, $document_id, $maxlength = '', $rubric_id = 0) function request_get_document_field($field_id, $document_id, $maxlength = '', $rubric_id = 0)
@ -373,8 +389,8 @@
{ {
$tparams_id = $row->Id . md5($tparams); // Создаем уникальный id для каждого набора параметров $tparams_id = $row->Id . md5($tparams); // Создаем уникальный id для каждого набора параметров
$params_of_teaser[$tparams_id] = array(); // Для отмены лишних ворнингов $params_of_teaser[$tparams_id] = array(); // Для отмены лишних ворнингов
$tparams = trim($tparams,'[]:'); // Удаляем: слева ':[', справа ']' $tparams = trim($tparams,'[]:'); // Удаляем: слева ':[', справа ']'
$params_of_teaser[$tparams_id] = explode('|',$tparams); // Заносим параметры в массив уникального id $params_of_teaser[$tparams_id] = explode('|',$tparams); // Заносим параметры в массив уникального id
} }
$sql = " $sql = "
@ -440,41 +456,36 @@
$item = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $item); $item = preg_replace_callback('/\[tag:sysblock:([A-Za-z0-9-_]{1,20}+)\]/', 'parse_sysblock', $item);
// Парсим элементы полей // Парсим элементы полей
$item = preg_replace_callback( $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/',
'/\[tag:rfld:([a-zA-Z0-9-_]+)\]\[([0-9]+)]\[([0-9]+)]/', function ($m) use ($row)
create_function( {
'$m', return get_field_element($m[1], $m[2], $m[3], (int)$row->Id);
'return get_field_element($m[1], $m[2], $m[3], ' . $row->Id . ');' },
), $item);
$item
);
// Парсим теги полей // Парсим теги полей
$item = preg_replace_callback( $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/',
'/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/', function ($m) use ($row)
create_function( {
'$m', return request_get_document_field($m[1], (int)$row->Id, $m[2], (int)$row->rubric_id);
'return request_get_document_field($m[1], ' . $row->Id . ', $m[2], ' . (int)$row->rubric_id . ');' },
), $item);
$item
);
// Повторно парсим теги полей // Повторно парсим теги полей
$item = preg_replace_callback( $item = preg_replace_callback('/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/',
'/\[tag:rfld:([a-zA-Z0-9-_]+)]\[(more|esc|img|strip|[0-9-]+)]/', function ($m) use ($row)
create_function( {
'$m', return request_get_document_field($m[1], (int)$row->Id, $m[2], (int)$row->rubric_id);
'return request_get_document_field($m[1], ' . $row->Id . ', $m[2], ' . (int)$row->rubric_id . ');' },
), $item);
$item
);
// Возвращаем поле документа из БД (document_***) // Возвращаем поле документа из БД (document_***)
$item = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u', $item = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
function ($match) use ($row) function ($m) use ($row)
{ {
return isset($row->{$match[1]}) return isset($row->{$m[1]})
? $row->{$match[1]} ? $row->{$m[1]}
: null; : null;
}, },
$item $item
@ -483,11 +494,11 @@
// Если пришел вызов на активацию языковых файлов // Если пришел вызов на активацию языковых файлов
$item = preg_replace_callback( $item = preg_replace_callback(
'/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u', '/\[tag:langfile:([a-zA-Z0-9-_]+)\]/u',
function ($match) function ($m)
{ {
global $AVE_Template; global $AVE_Template;
return $AVE_Template->get_config_vars($match[1]); return $AVE_Template->get_config_vars($m[1]);
}, },
$item $item
); );
@ -502,14 +513,12 @@
. '/', $item); . '/', $item);
// Watermarks // Watermarks
$item = preg_replace_callback( $item = preg_replace_callback('/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/',
'/\[tag:watermark:(.+?):([a-zA-Z]+):([0-9]+)\]/', function ($m)
create_function( {
'$m', watermarks($m[1], $m[2], $m[3]);
'watermarks($m[1], $m[2], $m[3]);' },
), $item);
$item
);
// Удаляем ошибочные теги полей документа и языковые, в шаблоне рубрики // Удаляем ошибочные теги полей документа и языковые, в шаблоне рубрики
$item = preg_replace('/\[tag:doc:\d*\]/', '', $item); $item = preg_replace('/\[tag:doc:\d*\]/', '', $item);
@ -522,14 +531,12 @@
if ($tparams != '') if ($tparams != '')
{ {
// Заменяем tparam в тизере // Заменяем tparam в тизере
$item = preg_replace_callback( $item = preg_replace_callback('/\[tparam:([0-9]+)\]/',
'/\[tparam:([0-9]+)\]/', function ($m) use ($tparams_id)
create_function( {
'$m', return f_params_of_teaser($tparams_id, $m[1]);
'return f_params_of_teaser('.$tparams_id.', $m[1]);' },
), $item);
$item
);
} }
else else
{ {
@ -560,28 +567,25 @@
$item = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $row->document_published)), $item); $item = str_replace('[tag:docdate]', pretty_date(strftime(DATE_FORMAT, $row->document_published)), $item);
$item = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $row->document_published)), $item); $item = str_replace('[tag:doctime]', pretty_date(strftime(TIME_FORMAT, $row->document_published)), $item);
$item = str_replace('[tag:humandate]', human_date($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-. \/]+)\]/', $item = preg_replace_callback('/\[tag:date:([a-zA-Z0-9-. \/]+)\]/',
create_function('$m','return translate_date(date($m[1], '.$row->document_published.')); function ($m) use ($row)
'), {
$item return translate_date(date($m[1], $row->document_published));
); },
$item);
if (preg_match('/\[tag:docauthor]/u', $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:docauthor]', get_username_by_id($row->document_author_id), $item);
}
$item = str_replace('[tag:docauthorid]', $row->document_author_id, $item); $item = str_replace('[tag:docauthorid]', $row->document_author_id, $item);
$item = preg_replace_callback( $item = preg_replace_callback('/\[tag:docauthoravatar:(\d+)\]/',
'/\[tag:docauthoravatar:(\d+)\]/', function ($m) use ($row)
create_function( {
'$m', return getAvatar(intval($row->document_author_id), $m[1]);
'return getAvatar('.intval($row->document_author_id).', $m[1]);' },
), $item);
$item
);
if (isset($use_cache) && $use_cache == 1) if (isset($use_cache) && $use_cache == 1)
{ {
@ -610,7 +614,9 @@
* Возвращает список документов удовлетворяющих параметрам запроса * Возвращает список документов удовлетворяющих параметрам запроса
* оформленный с использованием шаблона * оформленный с использованием шаблона
* *
* @param int $id идентификатор запроса * @param int $id идентификатор запроса
* @param array $params
*
* @return string * @return string
*/ */
function request_parse($id, $params = array()) function request_parse($id, $params = array())
@ -677,7 +683,7 @@
$sort = strtolower($sort); $sort = strtolower($sort);
// Добавляем условие в SQL // Добавляем условие в SQL
$request_join[$fid] = "<? if (preg_match('t[]'))?><?=(! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>"; $request_join[$fid] = "<?php if (preg_match('t[]'))?><?=(! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
// Если в сортировке указано ASC иначе DESC // Если в сортировке указано ASC иначе DESC
$asc_desc = strpos(strtolower($sort),'asc') !== false $asc_desc = strpos(strtolower($sort),'asc') !== false
@ -695,6 +701,7 @@
? 'ASC' ? 'ASC'
: 'DESC'; : 'DESC';
// ToDo - ХЗ что это
$request_order[$param] = "$fid " . $asc_desc; $request_order[$param] = "$fid " . $asc_desc;
} }
} }
@ -705,7 +712,7 @@
$fid = (int)$request->request_order_by_nat; $fid = (int)$request->request_order_by_nat;
// Добавляем с учётом переменной $t из условий, чтобы не выбирать те же таблиы заново - это оптимизирует время // Добавляем с учётом переменной $t из условий, чтобы не выбирать те же таблиы заново - это оптимизирует время
$request_join[$fid] = "<?= (! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>"; $request_join[$fid] = "<?php echo (! isset(\$t[$fid])) ? \"LEFT JOIN " . PREFIX . "_document_fields AS t$fid ON (t$fid.document_id = a.Id AND t$fid.rubric_field_id='$fid')\" : ''?>";
$request_order['field-' . $fid] = "t$fid.field_value " . $request->request_asc_desc; $request_order['field-' . $fid] = "t$fid.field_value " . $request->request_asc_desc;
$request_order_fields[] = $fid; $request_order_fields[] = $fid;
@ -899,8 +906,6 @@
if (isset($params['RETURN_SQL']) && $params['RETURN_SQL'] == 1) if (isset($params['RETURN_SQL']) && $params['RETURN_SQL'] == 1)
return $AVE_DB->GetFoundRows(); return $AVE_DB->GetFoundRows();
$num_items = 0;
// Если есть вывод пагинации, то выполняем запрос на получение кол-ва элементов // Если есть вывод пагинации, то выполняем запрос на получение кол-ва элементов
if ($request->request_show_pagination == 1 || (isset($params['SHOW']) && $params['SHOW'] == 1)) 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); $num_items = $AVE_DB->NumAllRows($sql_request, (int)$request->request_cache_lifetime, 'rqs_' . $id);
@ -1043,8 +1048,6 @@
$request_changed = $request->request_changed; $request_changed = $request->request_changed;
$request_changed_elements = $request->request_changed_elements; $request_changed_elements = $request->request_changed_elements;
$item = '';
foreach ($rows as $row) foreach ($rows as $row)
{ {
$x++; $x++;
@ -1053,7 +1056,7 @@
$req_item_num = $item_num; $req_item_num = $item_num;
$item = showrequestelement($row, $request->request_template_item); $item = showrequestelement($row, $request->request_template_item);
$item = '<'.'?php $item_num='.var_export($item_num,1).'; $last_item='.var_export($last_item,1).'?'.'>'.$item; $item = '<'.'?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 = '<'.'?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_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_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_last]', '<'.'?php if(isset($last_item) && $last_item) { ?'.'>', $item);
@ -1124,7 +1127,7 @@
//-- Возвращаем параметр документа из БД //-- Возвращаем параметр документа из БД
$main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u', $main_template = preg_replace_callback('/\[tag:doc:([a-zA-Z0-9-_]+)\]/u',
function ($match) function ($match) use ($row)
{ {
return isset($row->{$match[1]}) return isset($row->{$match[1]})
? $row->{$match[1]} ? $row->{$match[1]}

8
functions/func.sysblock.php

@ -15,17 +15,19 @@
* Обработка тега системного блока * Обработка тега системного блока
* *
* @param int $id идентификатор системного блока * @param int $id идентификатор системного блока
*
* @return bool|mixed|null|string|string[]
*/ */
function parse_sysblock($id) function parse_sysblock($id)
{ {
global $AVE_DB, $AVE_Core; global $AVE_DB;
if (is_array($id)) if (is_array($id))
$id = $id[1]; $id = $id[1];
Debug::startTime('SYSBLOCK_' . $id); Debug::startTime('SYSBLOCK_' . $id);
$eval_sysblock = false; // $eval_sysblock = false;
if ($id != '') if ($id != '')
{ {
@ -101,5 +103,7 @@
return $return; return $return;
} }
return false;
} }
?> ?>

6
functions/func.thumbnails.php

@ -24,6 +24,8 @@
| <li>size - размер миниатюры</li> | <li>size - размер миниатюры</li>
| </ul> | </ul>
| |
| make_thumbnail(array('link' => URL, 'size' => SIZE));
|
| @return string | @return string
*/ */
function make_thumbnail ($params) function make_thumbnail ($params)
@ -42,15 +44,13 @@
if (! is_dir(dirname($path))) if (! is_dir(dirname($path)))
mkdir(dirname($path), 0777, true); mkdir(dirname($path), 0777, true);
mkdir($path, 0777); mkdir($path, 0777, true);
} }
$link = ABS_PATH . UPLOAD_DIR . '/ext/' . substr($md5, 0, 4) . '/' . $md5 . '.jpg'; $link = ABS_PATH . UPLOAD_DIR . '/ext/' . substr($md5, 0, 4) . '/' . $md5 . '.jpg';
if (! file_exists(BASE_DIR . $link)) if (! file_exists(BASE_DIR . $link))
{
file_put_contents(BASE_DIR . $link . '.tmp', $params['link']); file_put_contents(BASE_DIR . $link . '.tmp', $params['link']);
}
$params['link'] = $link; $params['link'] = $link;
} }

412
functions/func.users.php

@ -1,240 +1,246 @@
<?php <?php
/** /**
* AVE.cms * AVE.cms
* *
* @package AVE.cms * @package AVE.cms
* @version 3.x * @version 3.x
* @filesource * @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru * @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
* *
* @license GPL v.2 * @license GPL v.2
*/ */
/** /**
* Возвращаем аватар по пользователю * Возвращаем аватар по пользователю
* *
* @param int $id Ид пользователя- если не придет то текущий пользователь * @param int $id Ид пользователя- если не придет то текущий пользователь
* @param int $size размер картинки по краю * @param int $size размер картинки по краю
* @param string $prefix * @param string $prefix
* @return string путь до файла с превью * @return string путь до файла с превью
*/ */
function getAvatar($id = null, $size = 58, $prefix = "") function getAvatar($id = null, $size = 58, $prefix = '')
{ {
global $AVE_DB; global $AVE_DB;
static $result=array();
static $result = array();
if ($id === null) $id = $_SESSION['user_id'];
if ($id === null)
if(!isset($result[$id])){ $id = $_SESSION['user_id'];
$user=get_user_rec_by_id($id);
$ava = ABS_PATH. UPLOAD_DIR .'/avatars/'.(($prefix==="")?"":$prefix).md5($user->user_name); if (! isset($result[$id]))
$ava = (file_exists(BASE_DIR.$ava.'.jpg') ? $ava.'.jpg' : (file_exists(BASE_DIR.$ava.'.png') ? $ava.'.png' : (file_exists(BASE_DIR.$ava.'.gif') ? $ava.'.gif' : ''))); {
$result[$id]=$ava; $user = get_user_rec_by_id($id);
$ava = ABS_PATH . UPLOAD_DIR . '/avatars/' . (($prefix === '') ? '' : $prefix) . md5($user->user_name);
$ava = (file_exists(BASE_DIR.$ava.'.jpg') ? $ava.'.jpg' : (file_exists(BASE_DIR . $ava . '.png') ? $ava . '.png' : (file_exists(BASE_DIR.$ava.'.gif') ? $ava.'.gif' : '')));
$result[$id] = $ava;
}
$ava = $result[$id];
$src = (file_exists(BASE_DIR . $ava)
? make_thumbnail(array('link' => $ava,'size' => 'c' . $size . 'x' . $size))
: make_thumbnail(array('link' => $AVE_DB->Query("SELECT default_avatar FROM " . PREFIX . "_user_groups WHERE user_group=" . (int)$user->user_group)->GetCell(), 'size' => 'c' . $size . 'x' . $size))
);
return $src;
} }
$ava=$result[$id];
$src = (file_exists(BASE_DIR.$ava) ? /**
make_thumbnail(array('link' => $ava,'size' => 'c' . $size . 'x' . $size)): * Устанавливаем аватар пользователю
make_thumbnail(array('link' => $AVE_DB->Query("SELECT default_avatar FROM " . PREFIX . "_user_groups WHERE user_group=" . (int)$user->user_group)->GetCell(), 'size' => 'c' . $size . 'x' . $size)) *
); * @param int $id Ид пользователя
* @param string $avatar путь до картинки которая будет аватаром
* @return bool установился аватар или нет
*/
function SetAvatar($id, $avatar)
{
if ($id === null) $id = $_SESSION['user_id'];
return $src; $user = get_user_rec_by_id($id);
}
$file_ext = pathinfo($avatar, PATHINFO_EXTENSION);
/** if (! file_exists($avatar))
* Устанавливаем аватар пользователю return false;
*
* @param int $id Ид пользователя
* @param string $avatar путь до картинки которая будет аватаром
* @return bool установился аватар или нет
*/
function SetAvatar($id, $avatar)
{
if ($id === null) $id = $_SESSION['user_id'];
$user = get_user_rec_by_id($id); $new_ava = BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . md5($user->user_name) . '.' . strtolower($file_ext);
$file_ext = pathinfo($avatar, PATHINFO_EXTENSION); foreach (glob(BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . md5($user->user_name) . '.*') AS $filename)
@unlink($filename);
if (! file_exists($avatar)) //Чистим превьюшки
return false; foreach (glob(BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . THUMBNAIL_DIR . '/' . md5($user->user_name) . '*.*') AS $filename)
@unlink($filename);
$new_ava = BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . md5($user->user_name) . '.' . strtolower($file_ext); @file_put_contents($new_ava, file_get_contents($avatar));
@unlink($avatar);
foreach (glob(BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . md5($user->user_name) . '.*') as $filename) return true;
{
@unlink($filename);
}
//Чистим превьюшки
foreach (glob(BASE_DIR . '/' . UPLOAD_DIR . '/avatars/' . THUMBNAIL_DIR . '/' . md5($user->user_name) . '*.*') as $filename)
{
@unlink($filename);
} }
@file_put_contents($new_ava, file_get_contents($avatar));
@unlink($avatar); /**
* Формирование строки имени пользователя
return true; * При наличии всех параметров пытается сформировать строку <b>Имя Фамилия</b>
} * Если задать $short=1 - формирует короткую форму <b>И. Фамилия</b>
* Когда отсутствует информация о Имени или Фамилии пытается сформировать
* строку на основе имеющихся данных, а если данных нет вообще - выводит
/** * имя анонимного пользователя которое задается в основных настройках системы.
* Формирование строки имени пользователя *
* При наличии всех параметров пытается сформировать строку <b>Имя Фамилия</b> * @todo добавить параметр 'anonymous' в настройки
* Если задать $short=1 - формирует короткую форму <b>И. Фамилия</b> *
* Когда отсутствует информация о Имени или Фамилии пытается сформировать * @param string $login логин пользователя
* строку на основе имеющихся данных, а если данных нет вообще - выводит * @param string $first_name имя пользователя
* имя анонимного пользователя которое задается в основных настройках системы. * @param string $last_name фамилия пользователя
* * @param int $short {0|1} признак формирования короткой формы
* @todo добавить параметр 'anonymous' в настройки * @return string
* */
* @param string $login логин пользователя function get_username($login = '', $first_name = '', $last_name = '', $short = 1)
* @param string $first_name имя пользователя
* @param string $last_name фамилия пользователя
* @param int $short {0|1} признак формирования короткой формы
* @return string
*/
function get_username($login = '', $first_name = '', $last_name = '', $short = 1)
{
if ($first_name != '' && $last_name != '')
{
if ($short == 1) $first_name = mb_substr($first_name, 0, 1, 'utf-8') . '.';
return ucfirst_utf8(mb_strtolower($first_name)) . ' ' . ucfirst_utf8(mb_strtolower($last_name));
return ucfirst_utf8(mb_strtolower($login));
}
elseif ($first_name != '' && $last_name == '')
{ {
return ucfirst_utf8(mb_strtolower($first_name)); if ($first_name != '' && $last_name != '')
{
if ($short == 1)
$first_name = mb_substr($first_name, 0, 1, 'utf-8') . '.';
return ucfirst_utf8(mb_strtolower($first_name)) . ' ' . ucfirst_utf8(mb_strtolower($last_name));
}
elseif ($first_name != '' && $last_name == '')
{
return ucfirst_utf8(mb_strtolower($first_name));
}
elseif ($first_name == '' && $last_name != '')
{
return ucfirst_utf8(mb_strtolower($last_name));
}
elseif ($login != '')
{
return ucfirst_utf8(mb_strtolower($login));
}
return 'Anonymous';
} }
elseif ($first_name == '' && $last_name != '')
/**
* Возвращает запись для пользователя по идентификатору
* не делает лишних запросов
*
* @param int $id - идентификатор пользователя
* @return object
*/
function get_user_rec_by_id($id)
{ {
return ucfirst_utf8(mb_strtolower($last_name)); global $AVE_DB;
static $users = array();
if (! isset($users[$id]))
{
$row = $AVE_DB->Query("
SELECT
*
FROM " . PREFIX . "_users
WHERE Id = '" . (int)$id . "'
")->FetchRow();
$users[$id] = $row;
}
return $users[$id];
} }
elseif ($login != '')
/**
* Возвращает параметры группы пользователей по идентификатору
* не делает лишних запросов
*
* @param int $id - идентификатор группы
* @return object
*/
function get_usergroup_rec_by_id($id)
{ {
return ucfirst_utf8(mb_strtolower($login)); global $AVE_DB;
static $usergroups = array();
if (! isset($usergroups[$id]))
{
$row = $AVE_DB->Query("
SELECT
*
FROM " . PREFIX . "_user_groups
WHERE user_group = '" . (int)$id . "'
")->FetchRow();
$usergroups[$id] = $row;
}
return $usergroups[$id];
} }
return 'Anonymous';
}
/**
* Возвращает login пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @return string
*/
function get_userlogin_by_id($id)
{
$rec = get_user_rec_by_id($id);
/** return $rec->user_name;
* Возвращает запись для пользователя по идентификатору }
* не делает лишних запросов
*
* @param int $id - идентификатор пользователя
* @return object
*/
function get_user_rec_by_id($id){
global $AVE_DB;
static $users = array();
if (!isset($users[$id])) /**
* Возвращает имя группы пользователя по его идентификатору
*
* @param int $id - идентификатор группы пользователя
* @return string
*/
function get_usergroup_by_id($id)
{ {
$row = $AVE_DB->Query(" $rec = get_usergroup_rec_by_id($id);
SELECT
* return $rec->user_group_name;
FROM " . PREFIX . "_users
WHERE Id = '" . (int)$id . "'
")->FetchRow();
$users[$id] = $row;
} }
return $users[$id];
}
/**
* Возвращает email пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @return string
*/
function get_useremail_by_id($id)
{
$rec = get_user_rec_by_id($id);
/** return $rec->email;
* Возвращает параметры группы пользователей по идентификатору }
* не делает лишних запросов
*
* @param int $id - идентификатор группы
* @return object
*/
function get_usergroup_rec_by_id($id){
global $AVE_DB;
static $usergroups = array();
if (!isset($usergroups[$id])) /**
* Возвращает имя пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @param int $param - Сокрашать имя (1 - да, 0 - нет)
*
* @return string
*/
function get_username_by_id($id, $param = 1)
{ {
$row = $AVE_DB->Query(" $row = get_user_rec_by_id($id);
SELECT $row = (! empty($row))
* ? get_username($row->user_name, $row->firstname, $row->lastname, $param)
FROM " . PREFIX . "_user_groups : get_username();
WHERE user_group = '" . (int)$id . "'
")->FetchRow(); return $row;
$usergroups[$id] = $row;
} }
return $usergroups[$id];
}
/**
* Возвращает login пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @return string
*/
function get_userlogin_by_id($id)
{
$rec = get_user_rec_by_id($id);
return $rec->user_name;
}
/**
* Возвращает имя группы пользователя по его идентификатору
*
* @param int $id - идентификатор группы пользователя
* @return string
*/
function get_usergroup_by_id($id)
{
$rec = get_usergroup_rec_by_id($id);
return $rec->user_group_name;
}
/**
* Возвращает email пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @return string
*/
function get_useremail_by_id($id)
{
$rec = get_user_rec_by_id($id);
return $rec->email;
}
/**
* Возвращает имя пользователя по его идентификатору
*
* @param int $id - идентификатор пользователя
* @param int $param - Сокрашать имя (1 - да, 0 - нет)
*
* @return string
*/
function get_username_by_id($id, $param = 1)
{
$row = get_user_rec_by_id($id);
$row = !empty($row) ? get_username($row->user_name, $row->firstname, $row->lastname, $param) : get_username();
return $row;
}
?> ?>

4
functions/func.watermarks.php

@ -56,8 +56,6 @@
*/ */
function watermarks ($file, $position='center', $transparency=100) function watermarks ($file, $position='center', $transparency=100)
{ {
global $AVE_DB;
if (! defined('WATERMARKS_DIR') || ! defined('WATERMARKS_FILE')) if (! defined('WATERMARKS_DIR') || ! defined('WATERMARKS_FILE'))
return $file; return $file;
@ -187,7 +185,7 @@
if ($watermark->_img['main']['type'] == 2) if ($watermark->_img['main']['type'] == 2)
{ {
$image = getimagesize("$imagePath/$imageName", $info); // $image = getimagesize("$imagePath/$imageName", $info); Not used
if (! isset($info['APP13'])) if (! isset($info['APP13']))
{ {

12
inc/init.php

@ -63,16 +63,16 @@
* @param array $array обрабатываемый массив * @param array $array обрабатываемый массив
* @return array обработанный массив * @return array обработанный массив
*/ */
function add_slashes($array=array()) function add_slashes($array = array())
{ {
@reset($array); @reset($array);
while (list($key, $val) = @each($array)) foreach ($array AS $_k => $_v)
{ {
if (is_string($val)) if (is_string($_v))
$array[$key] = addslashes($val); $array[$_k] = addslashes($_v);
elseif (is_array($val)) elseif (is_array($_v))
$array[$key] = add_slashes($val); $array[$_k] = add_slashes($_v);
} }
return $array; return $array;

1
install/data_base.sql

@ -310,6 +310,7 @@ INSERT INTO `%%PRFX%%_settings` VALUES
'%d %B %Y, %H:%M', '%d %B %Y, %H:%M',
'RU', 'RU',
'0', '0',
'0',
'<div class=\"hidden_box\">\n Содержимое скрыто.\n</div>' '<div class=\"hidden_box\">\n Содержимое скрыто.\n</div>'
);#inst# );#inst#

Loading…
Cancel
Save