<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

define('_IN_JOHNCMS', 1);

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';

$headmod = 'shoutbox';
require('../system/bootstrap.php');

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\EnvironmentInterface $env */
$env = $container->get(Johncms\Api\EnvironmentInterface::class);

/** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);

/** @var Zend\I18n\Translator\Translator $translator */
$translator = $container->get(Zend\I18n\Translator\Translator::class);
$translator->addTranslationFilePattern('gettext', __DIR__ . '/locale', '/%s/default.mo');

if (isset($_SESSION['ref'])) {
    unset($_SESSION['ref']);
}

// Проверяем права доступа в Админ-Клуб
if (isset($_SESSION['sa']) && $systemUser->rights < 1) {
    unset($_SESSION['sa']);
}

// Задаем заголовки страницы
$textl = isset($_SESSION['sa']) ? _t('Admin Club') : _t('ShoutBox');
require('../system/head.php');

if (!$config['mod_shout'] && $systemUser->rights < 7) {
echo '<div class="orange"><p>shoutbox is closed..!!</p></div>';
require('../system/end.php');
exit;
}
switch ($act) {
case 'delpost':
// Удаление отдельного поста
if ($systemUser->rights >= 6 && $id) {
if (isset($_GET['yes'])) {
$db->exec('DELETE FROM `shout` WHERE `id` = ' . $id);
header("Location: index.php");
} else {
echo '<div class="mainblok"><div class="phdr"><a href="index.php"><b>' . _t('ShoutBox') . '</b></a> | ' . _t('Delete message') . '</div>' . 
'<div class="rmenu"><p>' . _t('Do you really want to delete?') . '?<br>' . 
'<a href="index.php?act=delpost&amp;id=' . $id . '&amp;yes">' . _t('Delete') . '</a> | ' . 
'<a href="index.php">' . _t('Cancel') . '</a></p></div></div>';
}
}
break;

case 'say':
$admset = isset($_SESSION['sa']) ? 1 : 0;
$name = isset($_POST['name']) ? $tools->checkin(mb_substr(trim($_POST['name']), 0, 25)) : '';
$msg = isset($_POST['msg']) ? $bbcode->adepeter(mb_substr(trim($_POST['msg']), 0, 5000)) : '';
$trans = isset($_POST['msgtrans']) ? 1 : 0;
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$from = $systemUser->id ? $systemUser->name : $name;
if ($trans)
$msg = $tools->trans($msg);
$error = [];
$flood = FALSE;
if (!isset($_POST['token']) || !isset($_SESSION['token']) || $_POST['token'] != $_SESSION['token']) {
$error[] = _t('Wrong data');
}
if (!$systemUser->isValid() && empty($name))
$error[] = _t('Empty name');
if (empty($msg))
$error[] = _t('Message is empty');
if ($systemUser->ban['1'] || $systemUser->ban['13'])
$error[] = _t('Access forbidden');
if ($systemUser->isValid()) {
$flood = $tools->antiflood();
} else {
$req = $db->query("SELECT `time` FROM `shout` WHERE `ip` = '" . $env->getIp() . "' AND `browser` = " . $db->quote($env->getUserAgent()) . " AND `time` > '" . (time() - 60) . "'");
if ($req->rowCount()) {
$res = $req->fetch();
$flood = time() - $res['time'];
}
}
if ($flood) {
$error = sprintf(_t('You cannot add the message so often. Please, wait %d seconds.'), $flood);
}
if (!$error) {
include('bot.php');
include('slave.php');
$req = $db->query("SELECT * FROM `shout` WHERE `user_id` = '$systemUser->id' ORDER BY `time` DESC");
$res = $req->fetch();
if ($res['text'] == $msg) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
}
if (!$error) {
$db->prepare("INSERT INTO `shout` SET
`adm` = ?,
`time` = ?,
`user_id` = ?,
`name` = ?,
`text` = ?,
`ip` = ?,
`browser` = ?,
`otvet` = ''
")->execute([
$admset,
time(),
$systemUser->id,
$from,
$msg,
$env->getIp(),
$env->getUserAgent(),
]);
if ($systemUser->isValid()) {
$postshout = $systemUser['postshout'] + 1;
$balans = $systemUser['balans'] + 5;
$db->exec("UPDATE `users` SET `postshout` = '$postshout', `balans` = '$balans', `lastpost` = '" . time() . "' WHERE `id` = '$systemUser->id'");
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
} else {
echo $tools->displayError($error, '<a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">' . _t('back') . '</a>');
}
break;

case 'otvet':
// Добавление "ответа Админа"
if ($systemUser->rights >= 6 && $id) {
if (isset($_POST['submit']) && isset($_POST['token']) && isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
$reply = isset($_POST['otv']) ? mb_substr(trim($_POST['otv']), 0, 5000) : '';
$db->exec("UPDATE `shout` SET
`admin` = '" . $systemUser->name . "',
`otvet` = " . $db->quote($reply) . ",
`otime` = '" . time() . "'
WHERE `id` = '$id'
");
header("location: index.php");
} else {
echo '<div class="mainblok"><div class="phdr"><a href="index.php"><b>' . _t('Guestbook') . '</b></a> | ' . _t('Reply') . '</div>';
$req = $db->query("SELECT * FROM `shout` WHERE `id` = '$id'");
$res = $req->fetch();
$token = mt_rand(1000, 100000);
$_SESSION['token'] = $token; 

echo '<div class="menu">' . '<div class="quote"><b>' . $res['name'] . '</b>' . '<br />' . $tools->checkout($res['text']) . '</div>' .	'<form name="form" action="index.php?act=otvet&amp;id=' . $id . '" method="post">' . '<p><h3>' . _t('Reply') . '</h3>' . $bbcode->buttons('form', 'otv') . '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="otv">' . $tools->checkout($res['otvet']) . '</textarea></p>' . '<p><input type="submit" name="submit" value="' . _t('Reply') . '"/></p>' . '<input type="hidden" name="token" value="' . $token . '"/>' . '</form></div>' . 
'<div class="phdr"><a href="index.php">' . _t('Back') . '</a></div></div>';
}
}
break;

case 'edit':
if ($systemUser->rights >= 6 && $id) {
if (isset($_POST['submit'])
 && isset($_POST['token'])
 && isset($_SESSION['token'])
 && $_POST['token'] == $_SESSION['token']) {
$req = $db->query("SELECT `edit_count` FROM `shout` WHERE `id`='$id'");
$res = mysql_fetch_array($req);
$edit_count = $res['edit_count'] + 1;
$msg = isset($_POST['msg']) ? mb_substr(trim($_POST['msg']), 0, 5000) : '';
$db->prepare('
UPDATE `guest` SET 
`text` = ?,
`edit_who` = ?,
`edit_time` = ?,
`edit_count` = ?
WHERE `id` = ?
')->execute([
$msg,
$systemUser->name,
time(),
$edit_count,
$id,
]);
header("location: index.php");
} else {
$token = mt_rand(1000, 100000);
$_SESSION['token'] = $token;
$req = $db->query("SELECT * FROM `shout` WHERE `id` = '$id'");
$res = $req->fetch();
$text = htmlentities($res['text'], ENT_QUOTES, 'UTF-8');
echo '<div class="mainblok"><div class="phdr"><a href="index.php"><b>' . _t('Shoutbox') . '</b></a> &bull; ' . _t('Edit') . '</div>' .
'<div class="menu">' .
'<form action="index.php?act=edit&amp;id=' . $id . '" method="post">' .
'<div><b>' . _t('Author') . ':</b> ' . $res['name'] . '</div>';
echo $bbcode->buttons('form', 'msg');
echo '<div><textarea rows="' . $systemUser->getConfig()->fieldHeight . '" cols="17" name="msg">' . $text . '</textarea></div>' .
 '<p><input type="submit" name="submit" value="' . _t('Save') . '"/></p>' .
 '<input type="hidden" name="token" value="' . $token . '"/>' .
 '</form></div>' .
 '<div class="phdr"><a href="../help/index.php?act=tags">' . _t('BBcode') . '</a> &bull; <a href="../help/index.php?act=smileys">' . _t('Smileys') . '</a><br>' .
 '<a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">' . $lng['back'] . '</a></div></div>';
}
}
break;

case 'clean':
if ($systemUser->rights >= 7) {
if (isset($_POST['submit'])) {
$adm = isset($_SESSION['sa']) ? 1 : 0;
$cl = isset($_POST['cl']) ? intval($_POST['cl']) : '';
switch ($cl) {
case '1':
// Чистим сообщения, старше 1 дня
$db->exec("DELETE FROM `shout` WHERE `adm`='$adm' AND `time` < '" . (time() - 86400) . "'");
echo '<p>' . _t('All messages older than 1 day were deleted') . '</p>';
break;

case '2':
// Проводим полную очистку
$db->exec("DELETE FROM `shout` WHERE `adm`='$adm'");
echo '<p>' . _t('Full clearing is finished') . '</p>';
break;
default :
// Чистим сообщения, старше 1 недели
$db->exec("DELETE FROM `shout` WHERE `adm`='$adm' AND `time`<='" . (time() - 604800) . "';");
echo '<p>' . _t('All messages older than 1 week were deleted') . '</p>';
}

$db->query("OPTIMIZE TABLE `shout`");
echo '<p><a href="index.php">' . _t('ShoutBox') . '</a></p>';
} else {
// Запрос параметров очистки
echo '<div class="mainblok"><div class="phdr"><a href="index.php"><b>' . _t('ShoutBox') . '</b></a> | ' . _t('Clear') . '</div>' . 
'<div class="menu">' . 
'<form id="clean" method="post" action="index.php?act=clean">' . 
'<p><h3>' . _t('Clearing parameters') . '</h3>' . 
'<input type="radio" name="cl" value="0" checked="checked" />' . _t('Older than 1 week') . '<br />' . 
'<input type="radio" name="cl" value="1" />' . _t('Older than 1 day') . '<br />' . 
'<input type="radio" name="cl" value="2" />' . _t('Clear all') . '</p>' . 
'<p><input type="submit" name="submit" value="' . _t('Clear') . '" /></p>' . 
'</form></div>' . 
'<div class="phdr"><a href="index.php">' . _t('Cancel') . '</a></div></div>'; 
} 
}
break;

case 'sa':
if ($rights >= 1) {
if (isset($_GET['do']) && $_GET['do'] == 'set') {
$_SESSION['sa'] = 1;
} else {
unset($_SESSION['sa']);
}
}

default:
if (!$config['mod_shout'])
echo '<div class="orange">Shoutbox is closed..!!</div>';
echo '<div class="mainblok"><div class="phdr"><table width="100%" cellpadding="0" cellspacing="0"><tr><td align="left" valign=""><img src="/images/shout.png" width="16" height="16" alt=""/><a href="/shoutbox/index.php">&#160;<b>Shoutbox</b></a></td><td width="auto" align="right" valign="">';
if ($systemUser->rights >= 3) {
echo '<a href="/shoutbox/botpanel.php">Spambot</a>&#160;&bull;&#160;<a href="/shoutbox/slavepanel.php">CatboT</a>&#160;';
} else {
#FOR MEMBERS ONLY
}
echo '</td></tr></table></div>';
if ($systemUser->rights > 0) {
$menu = array();
$menu[] = isset($_SESSION['sa']) ? '<a href="index.php?act=sa">' . _t('Shoutbox') . '</a>' : '<b>' . _t('Shout') . '</b>';
$menu[] = isset($_SESSION['sa']) ? '<b>' . _t('Admin club') . '</b>' : '<a href="index.php?act=sa&amp;do=set">' . _t('Admin club') . '</a>';
if ($systemUser->rights >= 7)
$menu[] = '<a href="index.php?act=clean">' . _t('Clear') . '</a>';
echo '<div class="topmenu">' . implode(' | ', array_filter($menu)) . '</div>';
}
if ($systemUser->isValid() || $config['mod_shout'] == 2) {
$token = mt_rand(1000, 100000);
$_SESSION['token'] = $token;
if (!$systemUser->isValid()) {
echo '<div class="gmenu">' . _t('Access to guest is Forbidden') . '</div>';
}
elseif ($systemUser->ban['1'] || $systemUser->ban['13']) {
echo '<div class="gmenu"><font color="red"><b>You are banned..!!</b></font><br/><img src="../images/prvs.gif"/> We are sorry..<br>You are not allowed to post in shout..!!<br/>' . _t('banned') . '&#160;<a href="' . $config['homeurl'] . '/users/profile.php?act=ban">' . _t('View Reason') . '</a></div>';
} else {
echo '<div class="gmenu"><form name="form" action="index.php?act=say" method="post">';
echo $bbcode->buttons('form', 'msg');
echo '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="msg"></textarea><br/>';
echo'<input type="hidden" name="token" value="' . $token . '"/>' .
 '<input type="submit" name="submit" value="' . _t('Send') . '"/></form></div>';
}
if (isset($_SESSION['sa']) && $systemUser->rights >= "1") {
$req = $db->query("SELECT COUNT(*) FROM `shout` WHERE `adm`='1'");
} else {
$req = $db->query("SELECT COUNT(*) FROM `shout` WHERE `adm`='0'");
}
$total = $db->query("SELECT COUNT(*) FROM `shout` WHERE `adm`='" . (isset($_SESSION['sa']) ? 1 : 0) . "'")->fetchColumn();
echo '<div class="phdr"><center><a href="../help/index.php?act=forum">Rules</a> &bull; <a href="../help/index.php?act=tags">Bbcode</a> &bull; <a href="../help/index.php?act=smilies">Smileys</a></center></div>';
if ($total > $kmess) echo '<div class="topmenu">' . $tools->displayPagination('index.php?', $start, $total, $kmess) . '</div>';
echo '</div>';
if ($total) {
if (isset($_SESSION['sa']) && $systemUser->rights >= "1") {
echo '<div class="rmenu"><b>' . _t('Admin club') . '</b></div>';
$req = $db->query("SELECT `shout`.*, `shout`.`id` AS `sid`, `users`.`rights`, `users`.`lastdate`, `users`.`sex`, `users`.`status`, `users`.`datereg`, `users`.`id`
 FROM `shout` LEFT JOIN `users` ON `shout`.`user_id` = `users`.`id`
 WHERE `shout`.`adm`='1' ORDER BY `time` DESC LIMIT $start, $kmess");
} else {
$req = $db->query("SELECT `shout`.*, `shout`.`id` AS `sid`, `users`.`rights`, `users`.`lastdate`, `users`.`sex`, `users`.`status`, `users`.`datereg`, `users`.`id`
 FROM `shout` LEFT JOIN `users` ON `shout`.`user_id` = `users`.`id`
 WHERE `shout`.`adm`='0' ORDER BY `time` DESC LIMIT $start, $kmess");
}
$i = 0;
while (($res = $req->fetch()) !== FALSE) {
$text = '';
echo $i % 2 ? '<div class="mainblok">' : '<div class="mainblok">';
if (!$res['id']) {
$req_g = $db->query("SELECT `lastdate` FROM `cms_sessions` WHERE `session_id` = '" . md5($res['ip'] . $res['browser']) . "' LIMIT 1");
$res_g = $req_g->fetch();
$res['lastdate'] = $res_g['lastdate'];
}
if ($res['user_id']) {
$post = $bbcode->adepeter($post);
$post = $tools->cleanString($tools->checkout($res['text'], 1, 1));
$post = $tools->smilies($post, $res['rights'] >= 1 ? 1 : 0);
}
if ($res['edit_count']) {
$post .= '<br/>Edited by <span class="red"><b>' . $res['edit_who'] . '</b></span>';
}
if (!empty($res['otvet'])) {
$otvet = $tools->checkout($res['otvet'], 1, 1);
$otvet = $tools->smilies($otvet, 1);
$post .= '<div><span class="red"><b>' . $res['admin'] . '</b></span><font color="#3399ff">:</font>&nbsp;' . $otvet . '</div>';
}
if ($systemUser->rights >= 6) {
$subtext = '<div align="left"><a href="index.php?act=otvet&amp;id=' . $res['sid'] . '">' . _t('Reply') . '</a>' .
($systemUser->rights >= $res['rights'] ? ' &bull; <a href="index.php?act=edit&amp;id=' . $res['sid'] . '">' . _t('Edit') . '</a> &bull; <a href="index.php?act=delpost&amp;id=' . $res['sid'] . '">' . _t('Delete') . '</a></div>' : '');
} else {
$subtext = '';
}
# Display members
echo '<div class="phdr"><img src="../images/file.png" align="top" alt=""/>&nbsp;';
echo $tools->updateTime($res['time']);
echo '</div>';
# Display members avatar
echo '<div class="newsx"><table width="100%" cellspacing="0" cellpadding="0"><tr><td width="38px" align="left" valign="top">';
if (file_exists(('../files/users/avatar/' . $res['user_id'] . '.png'))) { 
echo '<img src="../files/users/avatar/' . $res['user_id'] . '.png" width="36" height="auto" alt="' . $user['name'] . '" />&nbsp;';
} else { 
echo '<img src="../images/empty.gif" width="36" height="auto" alt="' . $user['name'] . '" />&nbsp;';
}
echo '</td><td width="auto" align="left" valign="top">';
# User rights
$rank = array(
0 => '<font color="orange">',
1 => '<font color="#3399ff">',
2 => '<font color="#3399ff">',
3 => '<font color="#3399ff">',
4 => '<font color="#3399ff">',
5 => '<font color="#3399ff">',
6 => '<font color="#3399ff">',
7 => '<font color="green">',
9 => '<font color="#cc0000">'
);
# Display members nickname with label
if ($res['user_id']) {
echo $res['datereg'] > time() - 86400 ? '+' : '';
echo '<a href="' . $config['homeurl'] . '/users/profile.php?user=' . $res['user_id'] . '">' . $rank[$res['rights']] . '<b>' . $res['name'] . '</b></a></font>';
echo (time() > $res['lastdate'] + 300 ? '<span class="red">&nbsp;<img src="/images/offline.gif" width="8" height="10" alt="off"/></span>' : '<span class="green">&nbsp;<img src="/images/online.gif" width="8" height="10" alt="on"/></span>');
}
# Display user ranks
$user_rights = array(
0 => '<img src="/images/member.png" width="100" height="24" alt="" align="middle"/>',
3 => '<img src="/images/moderator.png" width="100" height="24" alt="" align="middle"/>',
6 => '<img src="/images/moderator.png" width="100" height="24" alt="" align="middle"/>',
7 => '<img src="/images/admin.png" width="100" height="24" alt="" align="middle"/>',
9 => '<img src="/images/owner.png" width="100" height="24" alt="" align="middle"/>'
);
echo '<div class="status">' . $user_rights[$res['rights']] . '</div>';
echo '</td></tr></table></div>';
echo '<div class="textx">';
echo $text;
echo $post;
echo $subtext;
echo '</div></div>';
++$i;
}
echo '</div>';
} else { 
echo '<div class="rmenu">Shoutbox is empty</div>';
}
# Display total guest and member post and next page on bottom
echo '<div class="mainblok"><div class="phdr"><a name="down" id="down"></a><a href="#up"><img src="../images/up.png" alt="up" width="20px" height="10px" border="0"/></a>&nbsp;&nbsp;' . _t('Total') . ' shout: ' . $total . '</div>';
if ($total > $kmess) {
echo '<div class="topmenu" align="right">' . $tools->displayPagination('index.php?', $start, $total, $kmess) . '<br>' .
'<form action="index.php" method="get"><input type="text" name="page" size="2"/>' .
'<input type="submit" value="' . _t('Go to') . ' &gt;&gt;"/></form></div>';
}
echo '</div>';
break;
}
}
require('../system/end.php');
?>