Files
poll/class/poll.php
2026-03-29 18:38:12 +05:00

1072 lines
32 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
class Poll
{
/**
* СВОЙСТВА
*/
var $_adminlimit = 5;
var $_limit = 5;
var $_commentwords = 1000;
var $_antispam = 0;
/**
* ВНУТРЕННИЕ МЕТОДЫ
*/
function _pollLinkRewrite($string)
{
return (REWRITE_MODE) ? PollRewrite($string) : $string;
}
/**
* ВНЕШНИЕ МЕТОДЫ
*/
/**
* Методы публичной части
*/
/**
* Отображение опроса (вывод тегами)
*
* @param string $tpl_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
* @param int $pid идентификатор опроса
*/
function pollShow($tpl_dir, $lang_file, $pid)
{
global $AVE_DB, $AVE_Template;
// if (isset($_REQUEST['module']) && $_REQUEST['module'] == 'poll') return;
$AVE_Template->config_load($lang_file, 'showpoll');
$row = $AVE_DB->Query("
SELECT
poll.*,
SUM(itm.poll_item_hits) AS sumhits
FROM
" . PREFIX . "_module_poll AS poll
LEFT JOIN
" . PREFIX . "_module_poll_items AS itm
ON poll_id = poll.id
WHERE
poll.id = '" . $pid . "' AND
poll.poll_title != '' AND
poll.poll_status = '1' AND
poll.poll_start < '" . time() . "'
GROUP BY poll.id
")->FetchRow();
if (!$row) return;
$poll_groups_id = empty($row->poll_groups_id) ? array() : explode(',', $row->poll_groups_id);
$poll_users_id = empty($row->poll_users_id) ? array() : explode(',', $row->poll_users_id);
$poll_users_ip = empty($row->poll_users_ip) ? array() : explode(',', $row->poll_users_ip);
$current_user_ip = empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR'];
if (@in_array($current_user_ip, $poll_users_ip) ||
@in_array($_SESSION['user_id'], $poll_users_id) ||
(isset($_COOKIE['poll_' . $pid]) && $_COOKIE['poll_' . $pid] == '1') )
{
$row->message = $AVE_Template->get_config_vars('POLL_ALREADY_POLL');
}
elseif (!(@in_array(UGROUP, $poll_groups_id)))
{
$row->message = $AVE_Template->get_config_vars('POLL_NO_PERMISSION');
}
elseif ($row->poll_end < time())
{
$row->message = $AVE_Template->get_config_vars('POLL_EXPIRED');
}
$items = array();
$sql = $AVE_DB->Query("
SELECT
*,
" . ($row->sumhits > 0 ? 'ROUND(poll_item_hits*100/' . $row->sumhits . ')' : 0) . " AS sum
FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $pid . "'
ORDER BY poll_item_position ASC
");
while ($row_items = $sql->FetchRow())
{
array_push($items, $row_items);
}
$AVE_Template->assign('formaction', 'index.php?module=poll&amp;action=vote&amp;pid=' . $pid);
$AVE_Template->assign('formaction_result', $this->_pollLinkRewrite('index.php?module=poll&amp;action=result&amp;pid=' . $pid));
$AVE_Template->assign('formaction_archive', $this->_pollLinkRewrite('index.php?module=poll&amp;action=archive'));
$AVE_Template->assign('poll', $row);
$AVE_Template->assign('items', $items);
if (isset($row->message))
{
$AVE_Template->display($tpl_dir . 'poll_nav_result.tpl');
}
else
{
$AVE_Template->display($tpl_dir . 'poll_nav.tpl');
}
}
/**
* Учет результатов опроса
*
* @param int $pid идентификатор опроса
*/
function pollVote($pid)
{
global $AVE_DB;
$pid = (int)$pid;
$row = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll
WHERE id = '" . $pid . "'
")->FetchRow();
if (!$row) return;
// Проверяем: если дата окончания установлена и она уже прошла
if ($row->poll_end > 0 && $row->poll_end < time())
{
// перенаправляем на страницу результатов, ничего не записывая в базу
header('Location: ' . $this->_pollLinkRewrite('index.php?module=poll&action=result&pid=' . $pid));
exit;
}
$poll_groups_id = empty($row->poll_groups_id) ? array() : explode(',', $row->poll_groups_id);
$poll_users_id = empty($row->poll_users_id) ? array() : explode(',', $row->poll_users_id);
$poll_users_ip = empty($row->poll_users_ip) ? array() : explode(',', $row->poll_users_ip);
$current_user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
// убрал &amp; из ссылки редиректа
$back = $this->_pollLinkRewrite('index.php?module=poll&action=result&pid=' . $pid);
// Проверка прав группы
if (!in_array(UGROUP, $poll_groups_id))
{
header('Location: ' . $back);
exit;
}
// Проверка: голосовал ли уже
$already_voted = false;
if (in_array($current_user_ip, $poll_users_ip)) $already_voted = true;
if (isset($_SESSION['user_id']) && in_array($_SESSION['user_id'], $poll_users_id)) $already_voted = true;
if (isset($_COOKIE['poll_' . $pid]) && $_COOKIE['poll_' . $pid] == '1') $already_voted = true;
if ($already_voted)
{
header('Location: ' . $back);
exit;
}
// Устанавливаем куку
setcookie('poll_' . $pid, '1', time() + 3600 * 3600, '/');
$p_item = (int)($_POST['p_item'] ?? 0);
if ($p_item > 0)
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll_items
SET poll_item_hits = poll_item_hits + 1
WHERE id = '" . $p_item . "'
");
// Обновляем список проголосовавших (IP и ID)
$sql_user_update = "";
if (UGROUP != 2 && isset($_SESSION['user_id'])) {
$sql_user_update = ", poll_users_id = CONCAT_WS(',', poll_users_id, '" . (int)$_SESSION['user_id'] . "')";
}
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll
SET
poll_users_ip = CONCAT_WS(',', poll_users_ip, '" . addslashes($current_user_ip) . "')
$sql_user_update
WHERE
id = '" . $pid . "'
");
}
// редирект
header('Location: ' . $back);
exit;
}
/**
* Подробная информация и статистика опроса, комментарии пользователей
*
* @param string $tpl_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
* @param int $pid идентификатор опроса
*/
function pollResultShow($tpl_dir, $lang_file, $pid)
{
global $AVE_DB, $AVE_Template;
if (empty($pid) && isset($_GET['pid'])) $pid = (int)$_GET['pid'];
if (empty($pid) && isset($_SERVER['REQUEST_URI'])) {
if (preg_match('/poll-(\d+)/', $_SERVER['REQUEST_URI'], $matches)) {
$pid = (int)$matches[1];
}
}
$pid = (int)$pid;
$AVE_Template->config_load($lang_file, 'showresult');
$AVE_Template->assign('comment_title', '');
$AVE_Template->assign('comment_text', '');
$AVE_Template->assign('errors', array());
// Обработка нового комментария
if (isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'new')
{
$errors = $this->pollCommentNew($pid);
if (empty($errors))
{
$redirect_url = 'index.php?module=poll&action=result&pid=' . $pid;
header('Location:' . $this->_pollLinkRewrite($redirect_url));
exit;
}
$AVE_Template->assign('errors', $errors);
}
// Основной запрос данных опроса
$poll = $AVE_DB->Query("
SELECT
poll.*,
SUM(itm.poll_item_hits) AS votes
FROM
" . PREFIX . "_module_poll AS poll
LEFT JOIN
" . PREFIX . "_module_poll_items AS itm
ON itm.poll_id = poll.id
WHERE
poll.id = '" . $pid . "' AND
poll.poll_title != '' AND
poll.poll_status = '1' AND
poll.poll_start < '" . time() . "'
GROUP BY poll.id
")->FetchRow();
if (!$poll) return;
// Варианты ответов
$items = array();
$votes_total = (int)$poll->votes;
$sql = $AVE_DB->Query("
SELECT
*,
" . ($votes_total > 0 ? 'ROUND(poll_item_hits*100/' . $votes_total . ')' : 0) . " AS sum
FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $pid . "'
ORDER BY poll_item_position ASC
");
while ($row_items = $sql->FetchRow())
{
$items[] = $row_items;
}
// Комментарии
$comments = array();
if ($poll->poll_can_comment == 1)
{
$sql = $AVE_DB->Query("
SELECT
cmnt.*,
IFNULL(usr.firstname, '') AS firstname,
IFNULL(usr.lastname, '" . addslashes($AVE_Template->get_config_vars('POLL_GUEST')) . "') AS lastname
FROM
" . PREFIX . "_module_poll_comments AS cmnt
LEFT JOIN
" . PREFIX . "_users AS usr
ON usr.Id = cmnt.poll_comment_author_id
WHERE poll_id = '" . $pid . "'
ORDER BY poll_comment_time DESC
");
while ($row_comments = $sql->FetchRow())
{
$comments[] = $row_comments;
}
$poll->count_comments = $sql->NumRows();
}
// Проверка прав и кук
$poll_users_id = empty($poll->poll_users_id) ? array() : explode(',', $poll->poll_users_id);
$poll_users_ip = empty($poll->poll_users_ip) ? array() : explode(',', $poll->poll_users_ip);
$current_user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
$current_user_ip = $_SERVER['REMOTE_ADDR'] ?? '';
$is_vote = 1;
if (in_array($current_user_ip, $poll_users_ip) ||
($current_user_id > 0 && in_array($current_user_id, $poll_users_id)) ||
(isset($_COOKIE['poll_' . $pid]) && $_COOKIE['poll_' . $pid] == '1'))
{
$is_vote = 0;
}
$rights = 0;
$groups_names = array();
if (!empty($poll->poll_groups_id))
{
// фильтр ID групп (только цифры и запятые)
$safe_groups = preg_replace('/[^0-9,]/', '', $poll->poll_groups_id);
$sql = $AVE_DB->Query("
SELECT user_group, user_group_name
FROM " . PREFIX . "_user_groups
WHERE user_group IN(" . $safe_groups . ")
");
while ($row_g = $sql->FetchRow())
{
if (UGROUP == $row_g->user_group) $rights = 1;
$groups_names[] = $row_g->user_group_name;
}
}
// Наполнение объекта для шаблона
$is_expired = ($poll->poll_end > 0 && $poll->poll_end < time()) ? 1 : 0;
$poll->can_vote = ($is_vote == 1 && $rights == 1 && $is_expired == 0) ? 1 : 0;
$poll->is_expired = $is_expired;
$poll->groups = implode(', ', $groups_names);
$poll->can_comment = ($poll->poll_status == 1 && $poll->poll_can_comment == 1 && $rights == 1) ? 1 : 0;
$poll->anti_spam = ($poll->poll_anti_spam == 1 && function_exists('imagettftext')) ? 1 : 0;
$poll->comment_max_chars = (int)$this->_commentwords;
$poll->items = $items;
$poll->comments = $comments;
// Ссылки
$poll->formaction = 'index.php?module=poll&action=vote&pid=' . $pid;
$poll->link_result = $this->_pollLinkRewrite('index.php?module=poll&action=result&pid=' . $pid);
$AVE_Template->assign('poll', $poll);
if (!defined('MODULE_SITE')) define('MODULE_SITE', $AVE_Template->get_config_vars('POLL_PAGE_TITLE_PREFIX') . $poll->poll_title);
if (!defined('MODULE_CONTENT')) define('MODULE_CONTENT', $AVE_Template->fetch($tpl_dir . 'result.tpl'));
}
/**
* Список завершенных и действующих опросов
*
* @param string $tpl_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
*/
function pollArchiveShow($tpl_dir, $lang_file)
{
global $AVE_DB, $AVE_Template;
// Добавляем инициализацию для Smarty, чтобы убрать Warning в шаблоне
$req_order = isset($_REQUEST['order']) ? $_REQUEST['order'] : '';
$req_by = isset($_REQUEST['by']) ? $_REQUEST['by'] : '';
if (empty($req_order))
{
$order = 'poll_title';
}
else
{
switch ($req_order)
{
case 'title':
$order = 'poll_title';
break;
case 'start':
$order = 'poll_start';
break;
case 'end':
$order = 'poll_end';
break;
case 'votes':
$order = 'votes';
break;
default:
$order = 'poll_title';
break;
}
}
if ($req_by == 'desc')
{
$order .= ' DESC';
}
else
{
$order .= ' ASC';
}
$items = array();
$sql = $AVE_DB->Query("
SELECT
poll.id,
poll.poll_title,
poll.poll_start,
poll.poll_end,
SUM(itm.poll_item_hits) AS votes
FROM
" . PREFIX . "_module_poll AS poll
LEFT JOIN
" . PREFIX . "_module_poll_items AS itm
ON itm.poll_id = poll.id
WHERE
poll.poll_title != '' AND
poll.poll_status = '1' AND
poll.poll_start < '" . (int)time() . "'
GROUP BY poll.id
ORDER BY " . $order
);
while ($row = $sql->FetchRow())
{
$row->plink = $this->_pollLinkRewrite('index.php?module=poll&action=result&pid=' . (int)$row->id);
array_push($items, $row);
}
$AVE_Template->assign('items', $items);
$AVE_Template->assign('order', $req_order);
$AVE_Template->assign('by', $req_by);
$AVE_Template->config_load($lang_file, 'showarchive');
if (!defined('MODULE_SITE')) define('MODULE_SITE', $AVE_Template->get_config_vars('POLL_ARCHIVE_TITLE'));
if (!defined('MODULE_CONTENT')) define('MODULE_CONTENT', $AVE_Template->fetch($tpl_dir . 'archive.tpl'));
}
/**
* Метод отображения комментариев
*
* @param string $tpl_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
* @param ini $pid идентификатор опроса
* @param string $theme
* @param string $errors
* @param string $text
* @param string $title
*/
function pollCommentShow($tpl_dir, $lang_file, $pid, $theme, $errors='', $text='', $title='')
{
global $AVE_DB, $AVE_Template;
$AVE_Template->config_load($lang_file, 'displayform');
$row = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll
WHERE id = '" . $pid . "'
LIMIT 1
")->FetchRow();
$groups = explode(',', $row->poll_groups_id);
if ($row->poll_status == 1 && $row->poll_can_comment == 1 && in_array(UGROUP, $groups))
{
$AVE_Template->assign('cancomment', 1);
}
$AVE_Template->assign('max_chars', $this->_commentwords);
if (isset($row->poll_anti_spam) && $row->poll_anti_spam == 1 && function_exists('imagettftext') && function_exists('imagejpeg'))
{
$AVE_Template->assign('anti_spam', 1);
}
if (!empty($errors)) $AVE_Template->assign('errors', $errors);
$AVE_Template->assign('theme_folder', $theme);
$AVE_Template->assign('title', $title);
$AVE_Template->assign('text', $text);
$AVE_Template->display($tpl_dir . 'poll_form.tpl');
}
/**
* Метод создания нового комментария (UTF-8 Only)
*
* @param int $pid идентификатор опроса
*/
function pollCommentNew($pid)
{
global $AVE_DB, $AVE_Template;
$errors = array();
$pid = (int)$pid;
$poll_settings = $AVE_DB->Query("
SELECT poll_anti_spam, poll_groups_id
FROM " . PREFIX . "_module_poll
WHERE id = '" . $pid . "'
AND poll_status = '1'
AND poll_can_comment = '1'
LIMIT 1
")->FetchRow();
if (!$poll_settings) {
$errors[] = $AVE_Template->get_config_vars('POLL_ERROR_PERM');
// Если это AJAX, отдаем ошибку сразу
if (isset($_REQUEST['ajax'])) { @ob_clean(); die('###ERR###' . end($errors)); }
return $errors;
}
$comment_title = isset($_POST['comment_title']) ? trim(addslashes($_POST['comment_title'])) : '';
$comment_text = isset($_POST['comment_text']) ? trim(addslashes($_POST['comment_text'])) : '';
$max_len = (int)$this->_commentwords;
$text = (mb_strlen($comment_text) > $max_len)
? mb_substr($comment_text, 0, $max_len) . '...'
: $comment_text;
if (mb_strlen($text) < 5) $errors[] = $AVE_Template->get_config_vars('POLL_ENTER_TEXT');
if (empty($comment_title)) $errors[] = $AVE_Template->get_config_vars('POLL_ENTER_TITLE');
if ($poll_settings->poll_anti_spam == 1 && function_exists('imagettftext'))
{
$session_captcha = $_SESSION['captcha_keystring'] ?? '';
$post_captcha = $_POST['securecode'] ?? '';
if (empty($post_captcha) || $session_captcha !== $post_captcha)
{
$errors[] = $AVE_Template->get_config_vars('POLL_ENTER_CODE_ERR');
}
if (empty($errors)) {
unset($_SESSION['captcha_keystring']);
}
}
if (empty($errors))
{
$allowed_groups = explode(',', $poll_settings->poll_groups_id);
if (in_array(UGROUP, $allowed_groups))
{
$author_id = (int)($_SESSION['user_id'] ?? 0);
$author_ip = addslashes($_SERVER['REMOTE_ADDR'] ?? '');
$AVE_DB->Query("
INSERT INTO " . PREFIX . "_module_poll_comments
SET
poll_id = '" . $pid . "',
poll_comment_time = '" . time() . "',
poll_comment_author_id = '" . $author_id . "',
poll_comment_author_ip = '" . $author_ip . "',
poll_comment_title = '" . $comment_title . "',
poll_comment_text = '" . $text . "'
");
if (isset($_REQUEST['ajax'])) { @ob_clean(); die('###OK###'); }
return array();
}
else
{
$errors[] = $AVE_Template->get_config_vars('POLL_ERROR_PERM');
}
}
// Если мы здесь и это AJAX — значит есть ошибки. Выплевываем их.
if (isset($_REQUEST['ajax'])) {
@ob_clean();
die('###ERR###' . implode('<br>', $errors));
}
return $errors;
}
/**
* Методы административной части
*****************************************************************************************************************************************************/
/**
* Метод вывода списка опросов
*
* @param string $adm_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
*/
function pollList($adm_dir, $lang_file)
{
global $AVE_DB, $AVE_Template;
$AVE_Template->config_load($lang_file, 'showpolls');
$num = $AVE_DB->Query("SELECT COUNT(*) FROM " . PREFIX . "_module_poll")->GetCell();
$limit = $this->_adminlimit;
$pages = ceil($num / $limit);
$start = get_current_page() * $limit - $limit;
$items = array();
$sql = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll
LIMIT " . $start . "," . $limit
);
while ($row = $sql->FetchRow())
{
$row_hits = $AVE_DB->Query("
SELECT SUM(poll_item_hits)
FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $row->id . "'
GROUP BY poll_id
")->GetCell();
$row->sum_hits = floor($row_hits);
$row->comments = $AVE_DB->Query("
SELECT COUNT(*)
FROM " . PREFIX . "_module_poll_comments
WHERE poll_id = '" . $row->id . "'
")->GetCell();
array_push($items, $row);
}
if ($num > $limit)
{
$page_nav = " <a class=\"pnav\" href=\"index.php?do=modules&action=modedit&mod=poll&moduleaction=1&cp=" . SESSION . "&page={s}\">{t}</a> ";
$page_nav = get_pagination($pages, 'page', $page_nav);
$AVE_Template->assign('page_nav', $page_nav);
}
$AVE_Template->assign('items', $items);
$AVE_Template->assign('content', $AVE_Template->fetch($adm_dir . 'admin_forms.tpl'));
}
/**
* Метод создания нового опроса
*
* @param string $adm_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
*/
function pollNew($adm_dir, $lang_file)
{
global $AVE_DB, $AVE_Template;
$AVE_Template->config_load($lang_file, 'newpolls');
switch ($_REQUEST['sub'])
{
case '':
$groups = array();
$sql = $AVE_DB->Query("
SELECT
user_group AS id,
user_group_name AS name
FROM " . PREFIX . "_user_groups
");
while ($row = $sql->FetchRow())
{
$groups[$row->id] = $row->name;
}
$AVE_Template->assign('published', time());
$AVE_Template->assign('expire', mktime(date("H"), date("i"), 0, date("m"), date("d"), date("Y") + 10));
$AVE_Template->assign('groups', $groups);
$AVE_Template->assign('selected', array_keys($groups));
$AVE_Template->assign('start', time());
$AVE_Template->assign('end', time());
$AVE_Template->assign('adm_dir', $adm_dir);
$AVE_Template->assign('formaction', 'index.php?do=modules&action=modedit&mod=poll&moduleaction=new&sub=save&cp=' . SESSION);
$AVE_Template->assign('content', $AVE_Template->fetch($adm_dir . 'admin_fields.tpl'));
break;
case 'save':
$_REQUEST['poll_published'] = $this->_mktime($_REQUEST['poll_published']);
$_REQUEST['poll_expire'] = $this->_mktime($_REQUEST['poll_expire']);
$_REQUEST['poll_status'] = (!empty($_REQUEST['poll_status'])) ? (int)$_REQUEST['poll_status'] : '0';
$_REQUEST['poll_can_comment'] = (!empty($_REQUEST['poll_can_comment'])) ? (int)$_REQUEST['poll_can_comment'] : '0';
$_REQUEST['poll_anti_spam'] = (!empty($_REQUEST['poll_anti_spam'])) ? (int)$_REQUEST['poll_anti_spam'] : '0';
$AVE_DB->Query("
INSERT
INTO " . PREFIX . "_module_poll
SET
id = '',
poll_title = '" . addslashes($_REQUEST['poll_name']) . "',
poll_status = '" . $_REQUEST['poll_status'] . "',
poll_groups_id = '" . @implode(',', $_REQUEST['groups']) . "',
poll_users_id = '0',
poll_users_ip = '0',
poll_can_comment = '" . $_REQUEST['poll_can_comment'] . "',
poll_anti_spam = '" . $_REQUEST['poll_anti_spam'] . "',
poll_start = '" . $_REQUEST['poll_published'] . "',
poll_end = '" . $_REQUEST['poll_expire'] . "'
");
$iid = $AVE_DB->InsertId();
// ШТАТНОЕ ЧПУ
$AVE_DB->Query("INSERT INTO " . PREFIX . "_modules_aliases
(module_name, module_action, module_link, module_url, module_admin)
VALUES
('poll', 'result', 'index.php?module=poll&action=result&pid={$iid}', 'poll-{$iid}', '0'),
('poll', 'form', 'index.php?module=poll&action=form&pop=1&pid={$iid}', 'pollcomment-{$iid}', '0')
");
reportLog($_SESSION['user_name'] . ' - Добавил новый опрос (' . addslashes($_REQUEST['poll_name']) . ')');
header('Location:index.php?do=modules&action=modedit&mod=poll&moduleaction=edit&id=' . $iid . '&cp=' . SESSION);
exit;
}
}
/**
* Метод записи вариантов ответа нового опроса
*
* @param int $pid идентификатор опроса
*/
function pollNewItemSave($pid)
{
global $AVE_DB;
if (!empty($_POST['item_title']))
{
$position = (int)$AVE_DB->Query("
SELECT MAX(poll_item_position)
FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $pid . "'
")->GetCell() + 1;
$AVE_DB->Query("
INSERT
INTO " . PREFIX . "_module_poll_items
SET
id = '',
poll_id = '" . $pid . "',
poll_item_title = '" . $_REQUEST['item_title'] . "',
poll_item_hits = '" . $_REQUEST['poll_item_hits'] . "',
poll_item_color = '" . $_REQUEST['line_color'] . "',
poll_item_position = '" . $position . "'
");
}
reportLog($_SESSION['user_name'] . ' - Добавил новый вариант ответа (' . ($_REQUEST['item_title']) . ') для опроса', 2, 2);
header('Location:index.php?do=modules&action=modedit&mod=poll&moduleaction=edit&id=' . $pid . '&cp=' . SESSION);
exit;
}
/**
* Метод редактирования опроса
*
* @param string $adm_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
* @param int $pid идентификатор опроса
*/
function pollEdit($adm_dir, $lang_file, $pid)
{
global $AVE_DB, $AVE_Template;
$AVE_Template->config_load($lang_file, 'editpolls');
switch ($_REQUEST['sub'])
{
case '':
$items = array();
$sql = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $pid . "'
ORDER BY poll_item_position ASC
");
while ($row = $sql->FetchRow())
{
array_push($items, $row);
}
$groups = array();
$sql = $AVE_DB->Query("
SELECT
user_group AS id,
user_group_name AS name
FROM " . PREFIX . "_user_groups
");
while ($row = $sql->FetchRow())
{
$groups[$row->id] = $row->name;
}
$row = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll
WHERE id = '" . $pid . "'
")->FetchRow();
$AVE_Template->assign('groups', $groups);
$AVE_Template->assign('selected', explode(',', $row->poll_groups_id));
$AVE_Template->assign('row', $row);
$AVE_Template->assign('items', $items);
$AVE_Template->assign('adm_dir', $adm_dir);
$AVE_Template->assign('start', $row->poll_start);
$AVE_Template->assign('end', $row->poll_end);
$AVE_Template->assign('formaction', 'index.php?do=modules&action=modedit&mod=poll&moduleaction=save&cp=' . SESSION . '&id=' . $pid);
$AVE_Template->assign('content', $AVE_Template->fetch($adm_dir . 'admin_fields.tpl'));
break;
case 'sortable':
foreach ($_REQUEST['sort'] as $position => $items_id)
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll_items
SET
poll_item_position = '" . (int)$position . "'
WHERE
id = '" . (int)$items_id . "'
");
}
exit;
}
}
/**
* Метод записи изменений в опросе
*
* @param int $pid идентификатор опроса
*/
function pollSave($pid)
{
global $AVE_DB;
// Обработка основных полей опроса с экранированием и проверкой на существование
$poll_name = isset($_REQUEST['poll_name']) ? addslashes($_REQUEST['poll_name']) : '';
$poll_status = (int)($_REQUEST['poll_status'] ?? 0);
$poll_can_comment = (int)($_REQUEST['poll_can_comment'] ?? 0);
// НАША КАПЧА
$poll_anti_spam = (int)($_REQUEST['poll_anti_spam'] ?? 0);
$poll_published = $_REQUEST['poll_published'] ?? '';
$poll_expire = $_REQUEST['poll_expire'] ?? '';
// Обработка групп (приведение к массиву и склейка)
$groups = isset($_REQUEST['groups']) ? (array)$_REQUEST['groups'] : [];
$groups_list = addslashes(@implode(',', $groups));
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll
SET
poll_title = '" . $poll_name . "',
poll_status = '" . $poll_status . "',
poll_can_comment = '" . $poll_can_comment . "',
poll_anti_spam = '" . $poll_anti_spam . "',
poll_start = '" . $this->_mktime($poll_published) . "',
poll_end = '" . $this->_mktime($poll_expire) . "',
poll_groups_id = '" . $groups_list . "'
WHERE
id = '" . (int)$pid . "'
");
// Удаление отмеченных вариантов
if (!empty($_POST['del']) && is_array($_POST['del']))
{
foreach ($_POST['del'] as $id => $field)
{
$AVE_DB->Query("
DELETE
FROM " . PREFIX . "_module_poll_items
WHERE id = '" . (int)$id . "'
");
}
}
// Обновление существующих вариантов ответов
if (!empty($_POST['item_title']) && is_array($_POST['item_title']))
{
foreach ($_POST['item_title'] as $id => $field)
{
if (!empty($field))
{
$item_title = addslashes($field);
$item_hits = (int)($_POST['poll_item_hits'][$id] ?? 0);
$item_color = addslashes($_POST['line_color'][$id] ?? '');
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll_items
SET
poll_item_title = '" . $item_title . "',
poll_item_hits = '" . $item_hits . "',
poll_item_color = '" . $item_color . "'
WHERE
id = '" . (int)$id . "'
");
}
}
}
// ШТАТНОЕ ЧПУ
$AVE_DB->Query("INSERT IGNORE INTO " . PREFIX . "_modules_aliases
(module_name, module_action, module_link, module_url, module_admin)
VALUES
('poll', 'result', 'index.php?module=poll&action=result&pid=" . (int)$pid . "', 'poll-" . (int)$pid . "', '0'),
('poll', 'form', 'index.php?module=poll&action=form&pop=1&pid=" . (int)$pid . "', 'pollcomment-" . (int)$pid . "', '0')
");
reportLog($_SESSION['user_name'] . ' - Сохранил изменения в опросе (ID: ' . (int)$pid . ')');
header('Location:index.php?do=modules&action=modedit&mod=poll&moduleaction=edit&id=' . (int)$pid . '&cp=' . SESSION);
exit;
}
/**
* Метод удаления опроса
*
* @param int $pid идентификатор опроса
*/
function pollDelete($pid)
{
global $AVE_DB;
$pid = (int)$pid;
// Удаляем все ЧПУ-ссылки опроса
$AVE_DB->Query("
DELETE FROM " . PREFIX . "_modules_aliases
WHERE module_name = 'poll'
AND module_link IN (
'index.php?module=poll&action=result&pid=" . $pid . "',
'index.php?module=poll&action=form&pop=1&pid=" . $pid . "'
)
");
// Удаляем сам опрос
$AVE_DB->Query("
DELETE FROM " . PREFIX . "_module_poll
WHERE id = '" . $pid . "'
");
// Удаляем варианты ответов
$AVE_DB->Query("
DELETE FROM " . PREFIX . "_module_poll_items
WHERE poll_id = '" . $pid . "'
");
// Удаляем комментарии к опросу
$AVE_DB->Query("
DELETE FROM " . PREFIX . "_module_poll_comments
WHERE poll_id = '" . $pid . "'
");
reportLog($_SESSION['user_name'] . ' - удалил опрос (' . $pid . ')', 2, 2);
header('Location:index.php?do=modules&action=modedit&mod=poll&moduleaction=1&cp=' . SESSION);
exit;
}
/**
* Метод управления комментариями к опросам
*
* @param string $tpl_dir путь к папке с шаблонами модуля
* @param string $lang_file путь к языковому файлу модуля
* @param int $pid идентификатор опроса
*/
function pollCommentEdit($adm_dir, $lang_file, $pid)
{
global $AVE_DB, $AVE_Template;
$AVE_Template->config_load($lang_file, 'showcomments');
switch ($_REQUEST['sub'])
{
case '':
$items = array();
$sql = $AVE_DB->Query("
SELECT *
FROM " . PREFIX . "_module_poll_comments
WHERE poll_id = '" . $pid . "'
");
while ($row = $sql->FetchRow())
{
$row->poll_comment_author = get_username_by_id($row->poll_comment_author_id);
array_push($items, $row);
}
$AVE_Template->assign('items', $items);
$AVE_Template->assign('adm_dir', $adm_dir);
$AVE_Template->assign('content', $AVE_Template->fetch($adm_dir . 'admin_comments.tpl'));
break;
case 'save':
if (!empty($_POST['del']))
{
foreach ($_POST['del'] as $id => $val)
{
$AVE_DB->Query("
DELETE
FROM " . PREFIX . "_module_poll_comments
WHERE id = '" . $id . "'
");
}
}
foreach ($_POST['comment_text'] as $id => $comment)
{
if (!empty($comment))
{
$AVE_DB->Query("
UPDATE " . PREFIX . "_module_poll_comments
SET
poll_comment_title = '" . $_POST['comment_title'][$id] . "',
poll_comment_text = '" . $comment . "'
WHERE
id = '" . $id . "'
");
}
}
header('Location:index.php?do=modules&action=modedit&mod=poll&moduleaction=comments&id=' . $pid . '&cp=' . SESSION);
exit;
}
}
/**
* Формирование метки времени по данным полученным из строки даты и времени
*
* @param string $data строка вида "дд.мм.гггг чч:мм"
* @return int timestamp
*/
function _mktime($data = '')
{
if (empty($data)) return time();
$data = explode(" ", $data);
// Инициализируем массив
$stamp = ['day' => [], 'time' => []];
$stamp['day'] = explode(".", $data[0]);
$stamp['time'] = isset($data[1]) ? explode(":", $data[1]) : [0, 0];
if (!empty($stamp['day']) && count($stamp['day']) == 3)
{
$timestamp = mktime(
(int)($stamp['time'][0] ?? 0),
(int)($stamp['time'][1] ?? 0),
0,
(int)$stamp['day'][1], // месяц
(int)$stamp['day'][0], // день
(int)$stamp['day'][2] // год
);
}
else
{
$timestamp = time();
}
return $timestamp;
}
}
?>