<?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);

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

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

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

$textl = _t('Quick Topic');
require('../system/head.php');
echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Create thread</b></div>';
if (!empty($systemUser->ban)) {
echo '<div class="gmenu"><font color="red"><b>You are banned..!!</b></font></div><div class="gmenu"><img src="../images/prvs.gif"/> We are sorry..<br>You are not allowed to create new thread..!!<br>' . $lng['ban'] . '&#160;<a href="' . $config['homeurl'] . '/users/profile.php?act=ban">' . _t('Know Reason For Ban') . '</a></div></div>';
require('../system/end.php');
exit;
}
if (empty($systemUser->id)) {
echo '<div class="gmenu"><img src="../images/prvlock.gif" class="left"/>&nbsp;We are sorry..<br>To create new thread you may <a href="' . $config['homeurl'] . '/index.php">login</a> first..<br>or if you not already a member you may <a href="' . $config['homeurl'] . '/registration/index.php">register</a> first..!!<br><a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">' . _t('Go Back') . '</a></div></div>';
require('../system/end.php');
exit;
}
if ($systemUser->id && $systemUser->ban['1'] || $systemUser->ban['12'] || $ban['11'] || $systemUser['postforum'] < 25) {
echo '<div class="gmenu"><img src="../images/prvlock.gif" class="left"/>&nbsp;We are sorry..!!<br>To create fast new thread required atleast 25 post in forum..<br>and your post are <span class="red">' . $datauser['postforum'] . '</span><br>you must active in forum to post thread in another section first..<br><img src="../images/prvs.gif"/> but please dont spam or you will get banned..!!</div><div class="phdr"><a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">Go ' . _t('Back') . '</a></div></div>';
require_once("../system/end.php");
exit;
}
if (isset($_POST['submit'])) {
$error = [];
$th = filter_has_var(INPUT_POST, 'th')
    ? mb_substr(filter_var($_POST['th'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
$msg = isset($_POST['msg']) ? trim($_POST['msg']) : '';
$tiento = $_POST['tiento'];
$pf = intval($_POST['pf']);
if (empty($th))
$error[] = _t('Topic Name Is Empty');
if (mb_strlen($th) < 2)
$error[] = _t('Length of topic name is too short');
if (empty($msg))
$error[] = _t('Message is empty');
if (mb_strlen($msg) < 4)
$error[] = _t('Message is too short');
if (empty($systemUser->isValid()))
$error[] = 'You must login or register before creating new thread..!!';
if (!$pf)
$error[] = 'You must choose category before creating new thread..!!';
$checktopic = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type` = 't' AND `refid` = '$id' AND `text` = '$th'")->fetchColumn();
if ($checktopic)
$error[] = _t('Topic Already Exist');
$flood = $tools->antiflood();
if ($flood)
$error[] = _t('You cannot add message so often. Please wait') . ' ' . $flood . '&#160;' . _t('Seconds');
if (!$error) {
$rid = 0;
if (!empty($_POST['pf']) && ($_POST['pf'] != '0')) {
$pf = intval($_POST['pf']);
$rz = $_POST['rz'];
$pr = $db->query("SELECT * FROM `forum` WHERE `refid` = '$pf' AND `type` = 'r'");
while ($pr1 = $pr->fetch()) {
$arr[] = $pr1['id'];
}
foreach ($rz as $v) {
if (in_array($v, $arr)) {
        $db->prepare('
          INSERT INTO `forum` SET
          `refid` = ?,
          `type` = \'t\',
           `time` = ?,
           `user_id` = ?,
           `from` = ?,
           `text` = ?,
           `soft` = \'\',
           `edit` = \'\'
        ')->execute([
            $v,
            time(),
            $systemUser->id,
            $systemUser->name,
            $th,
        ]);

        /** @var Johncms\Api\EnvironmentInterface $env */
        $env = App::getContainer()->get(Johncms\Api\EnvironmentInterface::class);
        $rid = $db->lastInsertId();

        // Добавляем текст поста
        $db->prepare('
          INSERT INTO `forum` SET
          `refid` = ?,
          `type` = \'m\',
          `time` = ?,
          `user_id` = ?,
          `from` = ?,
          `ip` = ?,
          `ip_via_proxy` = ?,
          `soft` = ?,
          `text` = ?,
          `edit` = \'\',
          `curators` = \'\'
        ')->execute([
            $rid,
            time(),
            $systemUser->id,
            $systemUser->name,
            $env->getIp(),
            $env->getIpViaProxy(),
            $env->getUserAgent(),
            $msg,
        ]);

        $postid = $db->lastInsertId();
        // Записываем счетчик постов юзера
        $fpst = $systemUser->postforum + 1;
        $balans = $systemUser->balans + 59;
        $db->exec("UPDATE `users` SET
            `postforum` = '$fpst',
            `balans` = '$balans',
            `lastpost` = '" . time() . "'
            WHERE `id` = '" . $systemUser->id . "'
        ");

        // Ставим метку о прочтении
        $db->exec("INSERT INTO `cms_forum_rdm` SET
            `topic_id`='$rid',
            `user_id`='" . $systemUser->id . "',
            `time`='" . time() . "'
        ");
}
}
}
if ($_POST['addfiles'] == 1)
header("Location: ../forum/index.php?id=$postid&act=addfile");
else
header("Location: ../forum/index.php?id=$rid");
} else {
echo '<div class="gmenu">';
echo $tools->displayError($error, '<a href="' . $config['homeurl'] . '/index.php">Go back home</a>');
echo '</div></div>';
require('../system/end.php');
exit;
}
} else {
echo '<form name="fthread" action="fthread.php" method="post"><div class="gmenu">' .
'<p><h3>' . _t('Thread Name') . '</h3></p>' .
'<p><input type="text" size="17" maxlength="100" name="th" value="' . $th . '"/>' .
'</p><p><h3>' . _t('Message') . '</h3>';

echo '</p><p>' . $container->get(Johncms\Api\BbcodeInterface::class)->buttons('fthread', 'msg');
echo '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="msg">' . (isset($_POST['msg']) ? $tools->checkout($_POST['msg']) : '') . '</textarea></p>';
echo '</div><div class="phdr"><img src="/images/anu.png" width="14" height="14" class="left"/>&nbsp;<b>Forum category</b></div><div class="menu"><p>';
$fr = $db->query("SELECT * FROM `forum` WHERE `type` = 'f'");
while ($fr1 = $fr->fetch()) {
echo '<input type="radio" name="pf" value="' . $fr1['id'] . '"/>' . $fr1['text'] . '<br/><select name="rz[]">';
$pr = $db->query("SELECT * FROM `forum` WHERE `type` = 'r' AND `refid` = '" . $fr1['id'] . "'");
while ($pr1 = $pr->fetch()) {
echo '<option value="' . $pr1['id'] . '">' . $pr1['text'] . '</option>';
}
echo '</select><br/>';
}
echo '</p></div><div class="phdr"><img src="/images/anu.png" width="14" height="14" class="left"/>&nbsp;<b>Thread option</b></div><div class="menu"><p>';
echo '</p><p><input type="checkbox" name="addfiles" value="1" ' . (isset($_POST['addfiles']) ? 'checked="checked" ' : '') . '/> ' . _t('Add file') . '</p>';
echo '<p><input type="submit" name="submit" value="Create thread" style="width: 107px; cursor: pointer;"/></div></form></p>' .
'<div class="phdr"><a href="' . $_SERVER['HTTP_REFERER'] . '">Go back</a></div>';
}
echo '</div>';
#Hacklord
if ($systemUser->isValid()) {
$upload_file_size = 1024;
echo '<div class="mainblok"><div class="phdr"><img src="/images/file.png" align="top" alt="file"/>&#160;<b>BBcode images</b></div>';
echo '<form enctype="multipart/form-data" method="post"><div class="gmenu">' .
'Import an image:<br/><input type="text" name="url" value="http://"/>' .
'<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $upload_file_size) . '"/>' . '<br/>' .
'<input type="submit" name="proceed" value="Import image"/></div></form>';
#Hacklord
if (isset($_POST['proceed'])) {
#folder to save imported files must end with slash..
$url = $_POST['url'];
$destination_folder = '../files/forum/attach/';
$file = fopen($newfname, "rb");
$newfname = $destination_folder.basename($url);
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
$target_file = $newfname;
require_once ('../downloads/classes/class.upload.php');
$handle = new upload($target_file);
if ($handle->uploaded) {
$name_file = time() . '_' . mt_rand(100, 999);
$handle->file_new_name_body = $name_file;
$handle->allowed = array('image/jpeg', 'image/gif', 'image/bmp', 'image/png');
$handle->file_max_size = 1024 * $upload_file_size;
$handle->file_overwrite = true;
$handle->image_convert = 'jpg';
$handle->process('../files/images/');
if ($handle->processed) {
$handle->file_new_name_body = $name_file;
$GetImageSize = GetImageSize('../files/images/' . $name_file . '.jpg');
$handle->file_overwrite = true;
$handle->jpeg_quality = 90;
$handle->image_ratio_fill = true;
$handle->image_ratio_crop = true;
$x_ratio = 100 / $GetImageSize[0];
$y_ratio = 100 / $GetImageSize[1];
if (($GetImageSize[0] <= 100) && ($GetImageSize[1] <= 100)) {
$handle->image_x = $GetImageSize[0];
$handle->image_y = $GetImageSize[1];
}
else if (($x_ratio * $GetImageSize[1]) < 100) {
$handle->image_y = ceil($x_ratio * $GetImageSize[1]);
$handle->image_x = 100;
} else {
$handle->image_x = ceil($y_ratio * $GetImageSize[0]);
$handle->image_y = 100;
}
$handle->image_convert = 'jpg';
$handle->process('../files/images/');
if ($handle->processed) {
echo '<div class="gmenu">Image successfully imported..!! You now can paste it into your post..!!<br/>' .
'BBimg: <input type="text" value="[img=' . $name_file . ']"/></div>';
@unlink($newfname);
} else {
echo '<div class="gmenu">';
echo $tools->displayError($handle->error);
echo '</div>';
@unlink($newfname);
}
} else {
echo '<div class="gmenu">';
echo $tools->displayError($handle->error);
echo '</div>';
@unlink($newfname);
$handle->clean();
}
} else {
echo '<div class="gmenu">';
echo $tools->displayError('No image imported..!!');
echo '</div>';
@unlink($newfname);
}
}
echo '<div class="phdr">Allowed to import files jpg, jpeg, png, gif<br/>' .
'file size should not exceed ' . $upload_file_size . ' kb</div></div>';
} else {
#ONLY FOR MEMBERS
}
require('../system/end.php');
exit;
?>