<commit_before><?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| https://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: Viewthread.php
| Author: Chan (<NAME>)
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
namespace PHPFusion\Forums\Threads;

use PHPFusion\Forums\ForumServer;
use PHPFusion\httpdownload;

class ViewThread extends ForumServer {

    private $thread_data = array();

    public function display_thread() {

        $info = $this->thread()->get_threadInfo();

        if (isset($_GET['action'])) {

            $poll = new Poll($info);

            switch($_GET['action']) {
                case 'editpoll':
                    $poll->render_poll_form(true);
                    break;
                case 'deletepoll':
                    $poll->delete_poll();
                    break;
                case 'newpoll':
                    $poll->render_poll_form();
                    break;
                case 'edit':
                    $this->render_edit_form();
                    break;
                case 'reply':
                    $this->render_reply_form();
                    break;
                default:
                    redirect(clean_request('', array('action'), false));
            }

        } else {

            $response = self::check_download_request();
            if ($response == true) {
                redirect(clean_request("", array("getfile"), false));
            }

            // +1 threadviews
            $this->increment_thread_views($info['thread']['thread_id']);

            // +1 see who is viewing thread
            $this->thread()->set_thread_visitor();

            if ($info['thread']['forum_users'] == true) {
                $info['thread_users'] = $this->get_participated_users($info);
            }

            render_thread($info);
        }
    }

    /**
     * Delete a post
     * @param $post_id
     * @param $thread_id
     * @param $forum_id
     */
    private function delete_post($post_id, $thread_id, $forum_id) {

        if (isset($_POST['delete']) && isnum($post_id) && isnum($thread_id) && isnum($forum_id)) {

            $result = dbquery("SELECT post_author FROM ".DB_FORUM_POSTS." WHERE post_id='$post_id' AND thread_id='$thread_id'");

            if (dbrows($result) >0) {

                $data = dbarray($result);

                // Minus -1 post count on user
                dbquery("UPDATE ".DB_USERS." SET user_posts=user_posts-1 WHERE user_id='".$data['post_author']."'");
                // Delete the current post
                dbquery("DELETE FROM ".DB_FORUM_POSTS." WHERE post_id='$post_id' AND thread_id='$thread_id'");
                // Update forum post count -1 on forum
                dbquery("UPDATE ".DB_FORUMS." SET forum_postcount=forum_postcount-1 WHERE forum_id = '$forum_id'");
                // Delete all post attachment
                $result = dbquery("SELECT * FROM ".DB_FORUM_ATTACHMENTS." WHERE post_id='$post_id'");
                if (dbrows($result)) {
                    while ($attach = dbarray($result)) {
                        unlink(FORUM."attachments/".$attach['attach_name']);
                        dbquery("DELETE FROM ".DB_FORUM_ATTACHMENTS." WHERE post_id='$post_id'");
                    }
                }

                // Check if there are any remaining post in the thread
                $posts = dbcount("(post_id)", DB_FORUM_POSTS, "thread_id='$thread_id'");
                if (!$posts) {
                    // Delete the thread
                    dbquery("DELETE FROM ".DB_FORUM_THREADS." WHERE thread_id='$thread_id' AND forum_id='$forum_id'");
                    // Delete all tracked status for this thread
                    dbquery("DELETE FROM ".DB_FORUM_THREAD_NOTIFY." WHERE thread_id='$thread_id'");
                    // Update forum threadcount -1 on forum
                    dbquery("UPDATE ".DB_FORUMS." SET forum_threadcount=forum_threadcount-1 WHERE forum_id = '$forum_id'");
                }

                // check if this post id is current last post through forum table
                // If forum has other threads, tally the lastpost information on the forum table
                $result = dbquery("SELECT * FROM ".DB_FORUMS." WHERE forum_id='$forum_id' AND forum_lastpostid='".$_GET['post_id']."'");
                if (dbrows($result) >0) {
                    $result = dbquery("SELECT p.post_id, p.forum_id, p.post_author, p.post_datestamp
									FROM ".DB_FORUM_POSTS." p
									LEFT JOIN ".DB_FORUM_THREADS." t ON p.thread_id=t.thread_id
									WHERE p.forum_id='$forum_id' AND thread_hidden='0' AND post_hidden='0'
									ORDER BY post_datestamp DESC LIMIT 1");
                    if (dbrows($result)) {
                        $pdata2 = dbarray($result);
                        dbquery("UPDATE ".DB_FORUMS." SET forum_lastpost='".$pdata2['post_datestamp']."', forum_lastpostid='".$pdata2['post_id']."', forum_lastuser='".$pdata2['post_author']."' WHERE forum_id='$forum_id'");
                    } else {
                        dbquery("UPDATE ".DB_FORUMS." SET forum_lastpost='0', forum_lastpostid='0' , forum_lastuser='0' WHERE forum_id='$forum_id'");
                    }
                }

                if ($posts) {
                    // Check if this is the last user
                    $result = dbcount("(thread_id)", DB_FORUM_THREADS,
                                      "thread_id='$thread_id' AND thread_lastpostid='".$_GET['post_id']."' AND thread_lastuser='".$data['post_author']."'");
                    if (!empty($result)) {
                        $result = dbquery("SELECT thread_id, post_id, post_author, post_datestamp FROM ".DB_FORUM_POSTS." WHERE thread_id='$thread_id' AND post_hidden='0' ORDER BY post_datestamp DESC LIMIT 1");
                        $pdata2 = dbarray($result);
                        dbquery("UPDATE ".DB_FORUM_THREADS." SET thread_lastpost='".$pdata2['post_datestamp']."', thread_lastpostid='".$pdata2['post_id']."', thread_postcount=thread_postcount-1, thread_lastuser='".$pdata2['post_author']."' WHERE thread_id='$thread_id'");
                    }
                }

                redirect(FORUM."postify.php?post=edit&amp;thread_id=$thread_id&forum_id=$forum_id&post_count=$posts");
            }
        }
    }

    public function render_reply_form() {

        $thread = $this->thread();

        $thread_info = $thread->get_threadInfo();

        $thread_data = $thread_info['thread'];

        $forum_settings = $this->get_forum_settings();

        $locale = fusion_get_locale("", FORUM_LOCALE);

        $userdata = fusion_get_userdata();

        $this->thread_data = $thread_info['thread'];

        if ((!iMOD or !iSUPERADMIN) && $thread_data['thread_locked']) redirect(INFUSIONS.'forum/index.php');

        if ($thread->getThreadPermission("can_reply")) {

            add_to_title($locale['global_201'].$locale['forum_0503']);

            \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => FUSION_REQUEST, 'title' => $locale['forum_0503']]);

            // field data
            $post_data = array(
                'post_id' => 0,
                'post_cat' => isset($_GET['post_id']) && isnum($_GET['post_id']) ? intval($_GET['post_id']) : 0,
                'forum_id' => $thread_info['thread']['forum_id'],
                'thread_id' => $thread_info['thread']['thread_id'],
                'post_message' => isset($_POST['post_message']) ? form_sanitizer($_POST['post_message'], '', 'post_message') : '',
                'post_showsig' => isset($_POST['post_showsig']) ? 1 : 0,
                'post_smileys' => isset($_POST['post_smileys']) || isset($_POST['post_message']) && preg_match("#(\[code\](.*?)\[/code\]|\[geshi=(.*?)\](.*?)\[/geshi\]|\[php\](.*?)\[/php\])#si", $_POST['post_message']) ? 1 : 0,
                'post_author' => $userdata['user_id'],
                'post_datestamp' => time(),
                'post_ip' => USER_IP,
                'post_ip_type' => USER_IP_TYPE,
                'post_edituser' => 0,
                'post_edittime' => 0,
                'post_editreason' => '',
                'post_hidden' => 0,
                'notify_me' => 0,
                'post_locked' => $forum_settings['forum_edit_lock'] || isset($_POST['thread_locked']) ? 1 : 0,
            );

            // execute form post actions
            if (isset($_POST['post_reply'])) {

                require_once INCLUDES."flood_include.php";
                if (!flood_control("post_datestamp", DB_FORUM_POSTS, "post_author='".$userdata['user_id']."'")) { // have notice

                    // If you merge, the datestamp on all forum, threads, post will not be updated.
                    $update_forum_lastpost = FALSE;

                    if (\defender::safe()) {
                        // Prepare forum merging action
                        $last_post_author = dbarray(dbquery("
                        SELECT post_author FROM ".DB_FORUM_POSTS."
                        WHERE thread_id='".intval($thread_data['thread_id'])."'
                        ORDER BY post_id DESC LIMIT 1
                        "));

                        // delete post checkbox...
                        // if is lastpost, update thread on the last.

                        if ($last_post_author['post_author'] == $post_data['post_author'] && $thread_data['forum_merge'] == TRUE) {

                            $last_message = dbarray(dbquery("SELECT post_id, post_message, post_datestamp FROM ".DB_FORUM_POSTS." WHERE thread_id='".intval($thread_data['thread_id'])."' ORDER BY post_id DESC"));
                            $post_data['post_id'] = $last_message['post_id'];
                            $post_data['post_message'] = $last_message['post_message']."\n\n".$locale['forum_0640']." ".showdate("longdate", time()).":\n".$post_data['post_message'];
                            $post_data['post_datestamp'] = $last_message['post_datestamp'];
                            dbquery_insert(DB_FORUM_POSTS, $post_data, 'update', array('primary_key' => 'post_id', 'keep_session' => TRUE));

                        } else {

                            $update_forum_lastpost = TRUE;
                            dbquery_insert(DB_FORUM_POSTS, $post_data, 'save', array('primary_key' => 'post_id', 'keep_session' => TRUE));
                            $post_data['post_id'] = dblastid();
                            dbquery("UPDATE ".DB_USERS." SET user_posts=user_posts+1 WHERE user_id='".intval($post_data['post_author'])."'");

                        }

                        // Attach files if permitted
                        if (!empty($_FILES)
                            && is_uploaded_file($_FILES['file_attachments']['tmp_name'][0])
                            && $thread->getThreadPermission("can_upload_attach")) {

                            $upload = form_sanitizer($_FILES['file_attachments'], '', 'file_attachments');
                            if ($upload['error'] == 0) {

                                foreach ($upload['target_file'] as $arr => $file_name) {
                                    $attach_data = array('thread_id' => intval($thread_data['thread_id']),
                                                   'post_id' => $post_data['post_id'],
                                                   'attach_name' => $file_name,
                                                   'attach_mime' => $upload['type'][$arr],
                                                   'attach_size' => $upload['source_size'][$arr],
                                                   'attach_count' => 0, // downloaded times
                                    );
                                    dbquery_insert(DB_FORUM_ATTACHMENTS, $attach_data, "save", array('keep_session' => TRUE));
                                }

                            }
                        }

                        // Update stats in forum and threads
                        if ($update_forum_lastpost == TRUE) {

                            // find all parents and update them
                            $list_of_forums = get_all_parent( dbquery_tree(DB_FORUMS, 'forum_id', 'forum_cat'), intval($thread_data['forum_id']) );
                            foreach ($list_of_forums as $forumID) {
                                dbquery("
								UPDATE ".DB_FORUMS." SET
								forum_lastpost = '".time()."',
								forum_postcount=forum_postcount+1,
								forum_lastpostid='".intval($post_data['post_id'])."',
								forum_lastuser='".intval($post_data['post_author'])."'
								WHERE forum_id='".intval($forumID)."'
								");
                            }
<commit_msg>Close #1133<commit_after><?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| https://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: Viewthread.php
| Author: Chan (<NAME>)
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
namespace PHPFusion\Forums\Threads;

use PHPFusion\Forums\ForumServer;
use PHPFusion\httpdownload;

class ViewThread extends ForumServer {

    private $thread_data = array();

    public function display_thread() {

        $info = $this->thread()->get_threadInfo();

        if (isset($_GET['action'])) {

            $poll = new Poll($info);

            switch($_GET['action']) {
                case 'editpoll':
                    $poll->render_poll_form(true);
                    break;
                case 'deletepoll':
                    $poll->delete_poll();
                    break;
                case 'newpoll':
                    $poll->render_poll_form();
                    break;
                case 'edit':
                    $this->render_edit_form();
                    break;
                case 'reply':
                    $this->render_reply_form();
                    break;
                default:
                    redirect(clean_request('', array('action'), false));
            }

        } else {

            $response = self::check_download_request();
            if ($response == true) {
                redirect(clean_request("", array("getfile"), false));
            }

            // +1 threadviews
            $this->increment_thread_views($info['thread']['thread_id']);

            // +1 see who is viewing thread
            $this->thread()->set_thread_visitor();

            if ($info['thread']['forum_users'] == true) {
                $info['thread_users'] = $this->get_participated_users($info);
            }

            render_thread($info);
        }
    }

    /**
     * Delete a post
     * @param $post_id
     * @param $thread_id
     * @param $forum_id
     */
    private function delete_post($post_id, $thread_id, $forum_id) {

        if (isset($_POST['delete']) && isnum($post_id) && isnum($thread_id) && isnum($forum_id)) {

            $result = dbquery("SELECT post_author FROM ".DB_FORUM_POSTS." WHERE post_id='$post_id' AND thread_id='$thread_id'");

            if (dbrows($result) >0) {

                $data = dbarray($result);

                // Minus -1 post count on user
                dbquery("UPDATE ".DB_USERS." SET user_posts=user_posts-1 WHERE user_id='".$data['post_author']."'");
                // Delete the current post
                dbquery("DELETE FROM ".DB_FORUM_POSTS." WHERE post_id='$post_id' AND thread_id='$thread_id'");
                // Update forum post count -1 on forum
                dbquery("UPDATE ".DB_FORUMS." SET forum_postcount=forum_postcount-1 WHERE forum_id = '$forum_id'");
                // Delete all post attachment
                $result = dbquery("SELECT * FROM ".DB_FORUM_ATTACHMENTS." WHERE post_id='$post_id'");
                if (dbrows($result)) {
                    while ($attach = dbarray($result)) {
                        unlink(FORUM."attachments/".$attach['attach_name']);
                        dbquery("DELETE FROM ".DB_FORUM_ATTACHMENTS." WHERE post_id='$post_id'");
                    }
                }

                // Check if there are any remaining post in the thread
                $posts = dbcount("(post_id)", DB_FORUM_POSTS, "thread_id='$thread_id'");
                if (!$posts) {
                    // Delete the thread
                    dbquery("DELETE FROM ".DB_FORUM_THREADS." WHERE thread_id='$thread_id' AND forum_id='$forum_id'");
                    // Delete all tracked status for this thread
                    dbquery("DELETE FROM ".DB_FORUM_THREAD_NOTIFY." WHERE thread_id='$thread_id'");
                    // Update forum threadcount -1 on forum
                    dbquery("UPDATE ".DB_FORUMS." SET forum_threadcount=forum_threadcount-1 WHERE forum_id = '$forum_id'");
                }

                // check if this post id is current last post through forum table
                // If forum has other threads, tally the lastpost information on the forum table
                $result = dbquery("SELECT * FROM ".DB_FORUMS." WHERE forum_id='$forum_id' AND forum_lastpostid='".$_GET['post_id']."'");
                if (dbrows($result) >0) {
                    $result = dbquery("SELECT p.post_id, p.forum_id, p.post_author, p.post_datestamp
									FROM ".DB_FORUM_POSTS." p
									LEFT JOIN ".DB_FORUM_THREADS." t ON p.thread_id=t.thread_id
									WHERE p.forum_id='$forum_id' AND thread_hidden='0' AND post_hidden='0'
									ORDER BY post_datestamp DESC LIMIT 1");
                    if (dbrows($result)) {
                        $pdata2 = dbarray($result);
                        dbquery("UPDATE ".DB_FORUMS." SET forum_lastpost='".$pdata2['post_datestamp']."', forum_lastpostid='".$pdata2['post_id']."', forum_lastuser='".$pdata2['post_author']."' WHERE forum_id='$forum_id'");
                    } else {
                        dbquery("UPDATE ".DB_FORUMS." SET forum_lastpost='0', forum_lastpostid='0' , forum_lastuser='0' WHERE forum_id='$forum_id'");
                    }
                }

                if ($posts) {
                    // Check if this is the last user
                    $result = dbcount("(thread_id)", DB_FORUM_THREADS,
                                      "thread_id='$thread_id' AND thread_lastpostid='".$_GET['post_id']."' AND thread_lastuser='".$data['post_author']."'");
                    if (!empty($result)) {
                        $result = dbquery("SELECT thread_id, post_id, post_author, post_datestamp FROM ".DB_FORUM_POSTS." WHERE thread_id='$thread_id' AND post_hidden='0' ORDER BY post_datestamp DESC LIMIT 1");
                        $pdata2 = dbarray($result);
                        dbquery("UPDATE ".DB_FORUM_THREADS." SET thread_lastpost='".$pdata2['post_datestamp']."', thread_lastpostid='".$pdata2['post_id']."', thread_postcount=thread_postcount-1, thread_lastuser='".$pdata2['post_author']."' WHERE thread_id='$thread_id'");
                    }
                }

                redirect(FORUM."postify.php?post=edit&amp;thread_id=$thread_id&forum_id=$forum_id&post_count=$posts");
            }
        }
    }

    public function render_reply_form() {

        $thread = $this->thread();

        $thread_info = $thread->get_threadInfo();

        $thread_data = $thread_info['thread'];

        $forum_settings = $this->get_forum_settings();

        $locale = fusion_get_locale("", FORUM_LOCALE);

        $userdata = fusion_get_userdata();

        $this->thread_data = $thread_info['thread'];

        if ((!iMOD or !iSUPERADMIN) && $thread_data['thread_locked']) redirect(INFUSIONS.'forum/index.php');

        if ($thread->getThreadPermission("can_reply")) {

            add_to_title($locale['global_201'].$locale['forum_0503']);

            \PHPFusion\BreadCrumbs::getInstance()->addBreadCrumb(['link' => FUSION_REQUEST, 'title' => $locale['forum_0503']]);

            // field data
            $post_data = array(
                'post_id' => 0,
                'post_cat' => isset($_GET['post_id']) && isnum($_GET['post_id']) ? intval($_GET['post_id']) : 0,
                'forum_id' => $thread_info['thread']['forum_id'],
                'thread_id' => $thread_info['thread']['thread_id'],
                'post_message' => isset($_POST['post_message']) ? form_sanitizer($_POST['post_message'], '', 'post_message') : '',
                'post_showsig' => isset($_POST['post_showsig']) ? 1 : 0,
                'post_smileys' => isset($_POST['post_smileys']) || isset($_POST['post_message']) && preg_match("#(\[code\](.*?)\[/code\]|\[geshi=(.*?)\](.*?)\[/geshi\]|\[php\](.*?)\[/php\])#si", $_POST['post_message']) ? 1 : 0,
                'post_author' => $userdata['user_id'],
                'post_datestamp' => time(),
                'post_ip' => USER_IP,
                'post_ip_type' => USER_IP_TYPE,
                'post_edituser' => 0,
                'post_edittime' => 0,
                'post_editreason' => '',
                'post_hidden' => 0,
                'notify_me' => 0,
                'post_locked' => $forum_settings['forum_edit_lock'] || isset($_POST['thread_locked']) ? 1 : 0,
            );

            // execute form post actions
            if (isset($_POST['post_reply'])) {

                require_once INCLUDES."flood_include.php";
                if (!flood_control("post_datestamp", DB_FORUM_POSTS, "post_author='".$userdata['user_id']."'")) { // have notice

                    // If you merge, the datestamp on all forum, threads, post will not be updated.
                    $update_forum_lastpost = FALSE;

                    if (\defender::safe()) {
                        // Prepare forum merging action
                        $last_post_author = dbarray(dbquery("
                        SELECT post_author FROM ".DB_FORUM_POSTS."
                        WHERE thread_id='".intval($thread_data['thread_id'])."'
                        ORDER BY post_id DESC LIMIT 1
                        "));

                        // delete post checkbox...
                        // if is lastpost, update thread on the last.

                        if ($last_post_author['post_author'] == $post_data['post_author'] && $thread_data['forum_merge'] == TRUE) {

                            $last_message = dbarray(dbquery("SELECT post_id, post_message, post_datestamp FROM ".DB_FORUM_POSTS." WHERE thread_id='".intval($thread_data['thread_id'])."' ORDER BY post_id DESC"));
                            $post_data['post_id'] = $last_message['post_id'];
                            $post_data['post_message'] = $last_message['post_message']."\n\n".$locale['forum_0640']." ".showdate("longdate", time()).":\n".$post_data['post_message'];
                            $post_data['post_datestamp'] = $last_message['post_datestamp'];
                            dbquery_insert(DB_FORUM_POSTS, $post_data, 'update', array('primary_key' => 'post_id', 'keep_session' => TRUE));

                        } else {

                            $update_forum_lastpost = TRUE;
                            dbquery_insert(DB_FORUM_POSTS, $post_data, 'save', array('primary_key' => 'post_id', 'keep_session' => TRUE));
                            $post_data['post_id'] = dblastid();
                            dbquery("UPDATE ".DB_USERS." SET user_posts=user_posts+1 WHERE user_id='".intval($post_data['post_author'])."'");

                        }

                        // Attach files if permitted
                        if (!empty($_FILES)
                            && is_uploaded_file($_FILES['file_attachments']['tmp_name'][0])
                            && $thread->getThreadPermission("can_upload_attach")) {

                            $upload = form_sanitizer($_FILES['file_attachments'], '', 'file_attachments');
                            if ($upload['error'] == 0) {

                                foreach ($upload['target_file'] as $arr => $file_name) {
                                    $attach_data = array('thread_id' => intval($thread_data['thread_id']),
                                                   'post_id' => $post_data['post_id'],
                                                   'attach_name' => $file_name,
                                                   'attach_mime' => $upload['type'][$arr],
                                                   'attach_size' => $upload['source_size'][$arr],
                                                   'attach_count' => 0, // downloaded times
                                    );
                                    dbquery_insert(DB_FORUM_ATTACHMENTS, $attach_data, "save", array('keep_session' => TRUE));
                                }

                            }
                        }

                        // Update stats in forum and threads
                        if ($update_forum_lastpost == TRUE) {

                            // find all parents and update them
                            $list_of_forums = get_all_parent( dbquery_tree(DB_FORUMS, 'forum_id', 'forum_cat'), intval($thread_data['forum_id']) );
                            if (!empty($list_of_forums)) {
                                foreach ($list_of_forums as $forumID) {
                                    dbquery("
                                    UPDATE ".DB_FORUMS." SET
                                    forum_lastpost = '".time()."',
                                    forum_postcount=forum_postcount+1,
                                    forum_lastpostid='".intval($post_data['post_id'])."',
                                    forum_lastuser='".intval($post_data['post_author'])."'
                                    WHERE forum_id='".intval($forumID)."'
                                    ");
                                }
                            }


{'fraction_non_alphanumeric': 0.15400372439478585, 'fraction_numerical': 0.004618249534450652, 'mean_word_length': 1.6561479869423286, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 107, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 42, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4028779', 'n_tokens_mistral': 7748, 'n_tokens_neox': 7117, 'n_words': 1375}