}
         eval("\$pollbox = \"" . $templates->get("showthread_poll") . "\";");
         $plugins->run_hooks("showthread_poll");
     }
 } else {
     $pollbox = "";
 }
 // Create the forum jump dropdown box.
 if ($mybb->settings['enableforumjump'] != 0) {
     $forumjump = build_forum_jump("", $fid, 1);
 }
 // Fetch some links
 $next_oldest_link = get_thread_link($tid, 0, "nextoldest");
 $next_newest_link = get_thread_link($tid, 0, "nextnewest");
 // Mark this thread as read
 mark_thread_read($tid, $fid);
 // If the forum is not open, show closed newreply button unless the user is a moderator of this forum.
 if ($forum['open'] != 0) {
     eval("\$newthread = \"" . $templates->get("showthread_newthread") . "\";");
     // Show the appropriate reply button if this thread is open or closed
     if ($thread['closed'] == 1) {
         eval("\$newreply = \"" . $templates->get("showthread_newreply_closed") . "\";");
     } else {
         eval("\$newreply = \"" . $templates->get("showthread_newreply") . "\";");
     }
 }
 // Create the admin tools dropdown box.
 if ($ismod == true) {
     $adminpolloptions = $closelinkch = $stickch = '';
     if ($pollbox) {
         $adminpolloptions = "<option value=\"deletepoll\">" . $lang->delete_poll . "</option>";
 function post_save_each($doquery = true)
 {
     if (!$this->condition and $this->fetch_field('dateline') == TIMENOW) {
         $this->insert_dupehash(0);
     }
     $this->post_save_each_post($doquery);
     if (!$this->condition and $this->fetch_field('dateline') == TIMENOW) {
         $this->insert_postlog_data();
     }
     $threadid = intval($this->fetch_field('threadid'));
     if ($this->thread['visible'] === 0) {
         $postid = intval($this->fetch_field('firstpostid'));
         /*insert query*/
         $this->dbobject->query_write("INSERT IGNORE INTO " . TABLE_PREFIX . "moderation (primaryid, type, dateline) VALUES ({$threadid}, 'thread', " . TIMENOW . ")");
     }
     if ($this->info['forum']['podcast'] and $postid = intval($this->fetch_field('firstpostid'))) {
         $this->dbobject->query_write("\n\t\t\t\tREPLACE INTO " . TABLE_PREFIX . "podcastitem\n\t\t\t\t\t(postid, url, length, explicit, author, keywords, subtitle)\n\t\t\t\tVALUES\n\t\t\t\t\t(\n\t\t\t\t\t\t{$postid},\n\t\t\t\t\t\t'" . $this->dbobject->escape_string($this->info['podcasturl']) . "',\n\t\t\t\t\t\t" . intval($this->info['podcastsize']) . ",\n\t\t\t\t\t\t" . intval($this->info['podcastexplicit']) . ",\n\t\t\t\t\t\t'" . $this->dbobject->escape_string($this->info['podcastauthor']) . "',\n\t\t\t\t\t\t'" . $this->dbobject->escape_string($this->info['podcastkeywords']) . "',\n\t\t\t\t\t\t'" . $this->dbobject->escape_string($this->info['podcastsubtitle']) . "'\n\t\t\t\t\t)\n\t\t\t");
         // reset rss cache for this forum
         $this->dbobject->query_write("\n\t\t\t\tDELETE FROM " . TABLE_PREFIX . "externalcache\n\t\t\t\tWHERE forumid = " . intval($this->info['forum']['forumid']) . "\n\t\t\t");
     }
     if ($this->info['mark_thread_read'] and $this->info['forum'] and $this->registry->options['threadmarking'] and $userid = $this->fetch_field('postuserid')) {
         $threadinfo = fetch_threadinfo($threadid);
         if ($threadinfo) {
             require_once DIR . '/includes/functions_bigthree.php';
             mark_thread_read($threadinfo, $this->info['forum'], $userid, $this->fetch_field('dateline'));
         }
     }
     $this->insert_moderator_log();
     if (!$this->condition) {
         $this->email_moderators(array('newthreademail', 'newpostemail'));
     }
     if ($this->info['forum'] and $this->fetch_field('firstpostid')) {
         // ### UPDATE SEARCH INDEX ###
         require_once DIR . '/includes/functions_databuild.php';
         build_post_index($this->fetch_field('firstpostid'), $this->info['forum'], 1);
     }
     ($hook = vBulletinHook::fetch_hook('threadfpdata_postsave')) ? eval($hook) : false;
 }
Example #3
0
function do_get_thread()
{
    global $vbulletin, $db, $foruminfo, $threadinfo, $postid, $vault, $vbphrase;
    $vbulletin->input->clean_array_gpc('r', array('pagenumber' => TYPE_UINT, 'perpage' => TYPE_UINT, 'password' => TYPE_STR, 'signature' => TYPE_BOOL));
    if (empty($threadinfo['threadid'])) {
        json_error(ERR_INVALID_THREAD);
    }
    $threadedmode = 0;
    $threadid = $vbulletin->GPC['threadid'];
    // Goto first unread post?
    if ($vbulletin->GPC['pagenumber'] == FR_LAST_POST) {
        $threadinfo = verify_id('thread', $threadid, 1, 1);
        if ($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) {
            $vbulletin->userinfo['lastvisit'] = max($threadinfo['threadread'], $threadinfo['forumread'], TIMENOW - $vbulletin->options['markinglimit'] * 86400);
        } else {
            if (($tview = intval(fetch_bbarray_cookie('thread_lastview', $threadid))) > $vbulletin->userinfo['lastvisit']) {
                $vbulletin->userinfo['lastvisit'] = $tview;
            }
        }
        $coventry = fetch_coventry('string');
        $posts = $db->query_first("\n\t    SELECT MIN(postid) AS postid\n\t    FROM " . TABLE_PREFIX . "post\n\t    WHERE threadid = {$threadinfo['threadid']}\n\t    AND visible = 1\n\t    AND dateline > " . intval($vbulletin->userinfo['lastvisit']) . "\n\t    " . ($coventry ? "AND userid NOT IN ({$coventry})" : "") . "\n\t    LIMIT 1\n\t");
        if ($posts['postid']) {
            $postid = $posts['postid'];
        } else {
            $postid = $threadinfo['lastpostid'];
        }
    }
    // *********************************************************************************
    // workaround for header redirect issue from forms with enctype in IE
    // (use a scrollIntoView javascript call in the <body> onload event)
    $onload = '';
    // *********************************************************************************
    // set $perpage
    $perpage = max(FR_MIN_PERPAGE, min($vbulletin->GPC['perpage'], FR_MAX_PERPAGE));
    // FRNR
    //$perpage = sanitize_maxposts($vbulletin->GPC['perpage']);
    // *********************************************************************************
    // set post order
    if ($vbulletin->userinfo['postorder'] == 0) {
        $postorder = '';
    } else {
        $postorder = 'DESC';
    }
    // *********************************************************************************
    // get thread info
    $thread = verify_id('thread', $threadid, 1, 1);
    $threadinfo =& $thread;
    ($hook = vBulletinHook::fetch_hook('showthread_getinfo')) ? eval($hook) : false;
    // *********************************************************************************
    // check for visible / deleted thread
    if (!$thread['visible'] and !can_moderate($thread['forumid'], 'canmoderateposts') or $thread['isdeleted'] and !can_moderate($thread['forumid'])) {
        json_error(ERR_INVALID_THREAD);
    }
    // *********************************************************************************
    // Tachy goes to coventry
    if (in_coventry($thread['postuserid']) and !can_moderate($thread['forumid'])) {
        json_error(ERR_INVALID_THREAD);
    }
    // FRNR Start
    // Check the forum password (set necessary cookies)
    if ($vbulletin->GPC['password'] && $foruminfo['password'] == $vbulletin->GPC['password']) {
        // set a temp cookie for guests
        if (!$vbulletin->userinfo['userid']) {
            set_bbarray_cookie('forumpwd', $foruminfo['forumid'], md5($vbulletin->userinfo['userid'] . $vbulletin->GPC['password']));
        } else {
            set_bbarray_cookie('forumpwd', $foruminfo['forumid'], md5($vbulletin->userinfo['userid'] . $vbulletin->GPC['password']), 1);
        }
    }
    // FRNR End
    // *********************************************************************************
    // do word wrapping for the thread title
    if ($vbulletin->options['wordwrap'] != 0) {
        $thread['title'] = fetch_word_wrapped_string($thread['title']);
    }
    $thread['title'] = fetch_censored_text($thread['title']);
    $thread['meta_description'] = strip_bbcode(strip_quotes($thread['description']), false, true);
    $thread['meta_description'] = htmlspecialchars_uni(fetch_censored_text(fetch_trimmed_title($thread['meta_description'], 500, false)));
    // *********************************************************************************
    // words to highlight from the search engine
    if (!empty($vbulletin->GPC['highlight'])) {
        $highlight = preg_replace('#\\*+#s', '*', $vbulletin->GPC['highlight']);
        if ($highlight != '*') {
            $regexfind = array('\\*', '\\<', '\\>');
            $regexreplace = array('[\\w.:@*/?=]*?', '<', '>');
            $highlight = preg_quote(strtolower($highlight), '#');
            $highlight = explode(' ', $highlight);
            $highlight = str_replace($regexfind, $regexreplace, $highlight);
            foreach ($highlight as $val) {
                if ($val = trim($val)) {
                    $replacewords[] = htmlspecialchars_uni($val);
                }
            }
        }
    }
    // *********************************************************************************
    // make the forum jump in order to fill the forum caches
    $navpopup = array('id' => 'showthread_navpopup', 'title' => $foruminfo['title_clean'], 'link' => fetch_seo_url('thread', $threadinfo));
    construct_quick_nav($navpopup);
    // *********************************************************************************
    // get forum info
    $forum = fetch_foruminfo($thread['forumid']);
    $foruminfo =& $forum;
    // *********************************************************************************
    // check forum permissions
    $forumperms = fetch_permissions($thread['forumid']);
    if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canview']) or !($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads'])) {
        json_error(ERR_NO_PERMISSION);
    }
    if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewothers']) and ($thread['postuserid'] != $vbulletin->userinfo['userid'] or $vbulletin->userinfo['userid'] == 0)) {
        json_error(ERR_NO_PERMISSION);
    }
    // *********************************************************************************
    // check if there is a forum password and if so, ensure the user has it set
    if (!verify_forum_password($foruminfo['forumid'], $foruminfo['password'])) {
        // FRNR
        json_error(ERR_NEED_PASSWORD, RV_NEED_FORUM_PASSWORD);
    }
    // verify that we are at the canonical SEO url
    // and redirect to this if not
    //verify_seo_url('thread|js', $threadinfo, array('pagenumber' => $_REQUEST['pagenumber']));
    // *********************************************************************************
    // jump page if thread is actually a redirect
    if ($thread['open'] == 10) {
        $destthreadinfo = fetch_threadinfo($threadinfo['pollid']);
        exec_header_redirect(fetch_seo_url('thread|js', $destthreadinfo, $pageinfo));
    }
    // *********************************************************************************
    // get ignored users
    $ignore = array();
    if (trim($vbulletin->userinfo['ignorelist'])) {
        $ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
        foreach ($ignorelist as $ignoreuserid) {
            $ignore["{$ignoreuserid}"] = 1;
        }
    }
    DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
    // *********************************************************************************
    // filter out deletion notices if can't be seen
    if ($forumperms & $vbulletin->bf_ugp_forumpermissions['canseedelnotice'] or can_moderate($threadinfo['forumid'])) {
        $deljoin = "LEFT JOIN " . TABLE_PREFIX . "deletionlog AS deletionlog ON(post.postid = deletionlog.primaryid AND deletionlog.type = 'post')";
    } else {
        $deljoin = '';
    }
    $show['viewpost'] = can_moderate($threadinfo['forumid']) ? true : false;
    $show['managepost'] = iif(can_moderate($threadinfo['forumid'], 'candeleteposts') or can_moderate($threadinfo['forumid'], 'canremoveposts'), true, false);
    $show['approvepost'] = can_moderate($threadinfo['forumid'], 'canmoderateposts') ? true : false;
    $show['managethread'] = can_moderate($threadinfo['forumid'], 'canmanagethreads') ? true : false;
    $show['approveattachment'] = can_moderate($threadinfo['forumid'], 'canmoderateattachments') ? true : false;
    $show['inlinemod'] = (!$show['threadedmode'] and ($show['managethread'] or $show['managepost'] or $show['approvepost'])) ? true : false;
    $show['spamctrls'] = ($show['inlinemod'] and $show['managepost']);
    $url = $show['inlinemod'] ? SCRIPTPATH : '';
    // build inline moderation popup
    if ($show['popups'] and $show['inlinemod']) {
        $threadadmin_imod_menu_post = vB_Template::create('threadadmin_imod_menu_post')->render();
    } else {
        $threadadmin_imod_menu_post = '';
    }
    // *********************************************************************************
    // find the page that we should be on to display this post
    if (!empty($postid) and $threadedmode == 0) {
        $postinfo = verify_id('post', $postid, 1, 1);
        $threadid = $postinfo['threadid'];
        $getpagenum = $db->query_first("\n    \t\tSELECT COUNT(*) AS posts\n    \t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\tWHERE threadid = {$threadid} AND visible = 1\n    \t\tAND dateline " . iif(!$postorder, '<=', '>=') . " {$postinfo['dateline']}\n    \t");
        $vbulletin->GPC['pagenumber'] = ceil($getpagenum['posts'] / $perpage);
    }
    // *********************************************************************************
    // update views counter
    if ($vbulletin->options['threadviewslive']) {
        // doing it as they happen; for optimization purposes, this cannot use a DM!
        $db->shutdown_query("\n    \t\tUPDATE " . TABLE_PREFIX . "thread\n    \t\tSET views = views + 1\n    \t\tWHERE threadid = " . intval($threadinfo['threadid']));
    } else {
        // or doing it once an hour
        $db->shutdown_query("\n    \t\tINSERT INTO " . TABLE_PREFIX . "threadviews (threadid)\n    \t\tVALUES (" . intval($threadinfo['threadid']) . ')');
    }
    // *********************************************************************************
    // display ratings if enabled
    $show['rating'] = false;
    if ($forum['allowratings'] == 1) {
        if ($thread['votenum'] > 0) {
            $thread['voteavg'] = vb_number_format($thread['votetotal'] / $thread['votenum'], 2);
            $thread['rating'] = intval(round($thread['votetotal'] / $thread['votenum']));
            if ($thread['votenum'] >= $vbulletin->options['showvotes']) {
                $show['rating'] = true;
            }
        }
        devdebug("threadinfo[vote] = {$threadinfo['vote']}");
        if ($threadinfo['vote']) {
            $voteselected["{$threadinfo['vote']}"] = 'selected="selected"';
            $votechecked["{$threadinfo['vote']}"] = 'checked="checked"';
        } else {
            $voteselected[0] = 'selected="selected"';
            $votechecked[0] = 'checked="checked"';
        }
    }
    // *********************************************************************************
    // set page number
    if ($vbulletin->GPC['pagenumber'] < 1) {
        $vbulletin->GPC['pagenumber'] = 1;
    } else {
        if ($vbulletin->GPC['pagenumber'] > ceil(($thread['replycount'] + 1) / $perpage)) {
            $vbulletin->GPC['pagenumber'] = ceil(($thread['replycount'] + 1) / $perpage);
        }
    }
    // *********************************************************************************
    // initialise some stuff...
    $limitlower = ($vbulletin->GPC['pagenumber'] - 1) * $perpage;
    $limitupper = $vbulletin->GPC['pagenumber'] * $perpage;
    $counter = 0;
    if ($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) {
        $threadview = max($threadinfo['threadread'], $threadinfo['forumread'], TIMENOW - $vbulletin->options['markinglimit'] * 86400);
    } else {
        $threadview = intval(fetch_bbarray_cookie('thread_lastview', $thread['threadid']));
        if (!$threadview) {
            $threadview = $vbulletin->userinfo['lastvisit'];
        }
    }
    $threadinfo['threadview'] = intval($threadview);
    $displayed_dateline = 0;
    ################################################################################
    ############################### SHOW POLL ######################################
    ################################################################################
    $poll = '';
    if ($thread['pollid']) {
        $pollbits = '';
        $counter = 1;
        $pollid = $thread['pollid'];
        $show['editpoll'] = iif(can_moderate($threadinfo['forumid'], 'caneditpoll'), true, false);
        // get poll info
        $pollinfo = $db->query_first_slave("\n    \t\tSELECT *\n    \t\tFROM " . TABLE_PREFIX . "poll\n    \t\tWHERE pollid = {$pollid}\n    \t");
        require_once DIR . '/includes/class_bbcode.php';
        $bbcode_parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
        $pollinfo['question'] = $bbcode_parser->parse(unhtmlspecialchars($pollinfo['question']), $forum['forumid'], true);
        $splitoptions = explode('|||', $pollinfo['options']);
        $splitoptions = array_map('rtrim', $splitoptions);
        $splitvotes = explode('|||', $pollinfo['votes']);
        $showresults = 0;
        $uservoted = 0;
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canvote'])) {
            $nopermission = 1;
        }
        if (!$pollinfo['active'] or !$thread['open'] or $pollinfo['dateline'] + $pollinfo['timeout'] * 86400 < TIMENOW and $pollinfo['timeout'] != 0 or $nopermission) {
            //thread/poll is closed, ie show results no matter what
            $showresults = 1;
        } else {
            //get userid, check if user already voted
            $voted = intval(fetch_bbarray_cookie('poll_voted', $pollid));
            if ($voted) {
                $uservoted = 1;
            }
        }
        ($hook = vBulletinHook::fetch_hook('showthread_poll_start')) ? eval($hook) : false;
        if ($pollinfo['timeout'] and !$showresults) {
            $pollendtime = vbdate($vbulletin->options['timeformat'], $pollinfo['dateline'] + $pollinfo['timeout'] * 86400);
            $pollenddate = vbdate($vbulletin->options['dateformat'], $pollinfo['dateline'] + $pollinfo['timeout'] * 86400);
            $show['pollenddate'] = true;
        } else {
            $show['pollenddate'] = false;
        }
        foreach ($splitvotes as $index => $value) {
            $pollinfo['numbervotes'] += $value;
        }
        if ($vbulletin->userinfo['userid'] > 0) {
            $pollvotes = $db->query_read_slave("\n    \t\t\tSELECT voteoption\n    \t\t\tFROM " . TABLE_PREFIX . "pollvote\n    \t\t\tWHERE userid = " . $vbulletin->userinfo['userid'] . " AND pollid = {$pollid}\n    \t\t");
            if ($db->num_rows($pollvotes) > 0) {
                $uservoted = 1;
            }
        }
        if ($showresults or $uservoted) {
            if ($uservoted) {
                $uservote = array();
                while ($pollvote = $db->fetch_array($pollvotes)) {
                    $uservote["{$pollvote['voteoption']}"] = 1;
                }
            }
        }
        $left = vB_Template_Runtime::fetchStyleVar('left');
        $right = vB_Template_Runtime::fetchStyleVar('right');
        $option['open'] = $left[0];
        $option['close'] = $right[0];
        foreach ($splitvotes as $index => $value) {
            $arrayindex = $index + 1;
            $option['uservote'] = iif($uservote["{$arrayindex}"], true, false);
            $option['question'] = $bbcode_parser->parse($splitoptions["{$index}"], $forum['forumid'], true);
            // public link
            if ($pollinfo['public'] and $value) {
                $option['votes'] = '<a href="poll.php?' . $vbulletin->session->vars['sessionurl'] . 'do=showresults&amp;pollid=' . $pollinfo['pollid'] . '">' . vb_number_format($value) . '</a>';
            } else {
                $option['votes'] = vb_number_format($value);
                //get the vote count for the option
            }
            $option['number'] = $counter;
            //number of the option
            //Now we check if the user has voted or not
            if ($showresults or $uservoted) {
                // user did vote or poll is closed
                if ($value <= 0) {
                    $option['percentraw'] = 0;
                } else {
                    if ($pollinfo['multiple']) {
                        $option['percentraw'] = $value < $pollinfo['voters'] ? $value / $pollinfo['voters'] * 100 : 100;
                    } else {
                        $option['percentraw'] = $value < $pollinfo['numbervotes'] ? $value / $pollinfo['numbervotes'] * 100 : 100;
                    }
                }
                $option['percent'] = vb_number_format($option['percentraw'], 2);
                $option['graphicnumber'] = $option['number'] % 6 + 1;
                $option['barnumber'] = round($option['percent']) * 2;
                $option['remainder'] = 201 - $option['barnumber'];
                // Phrase parts below
                if ($nopermission) {
                    $pollstatus = $vbphrase['you_may_not_vote_on_this_poll'];
                } else {
                    if ($showresults) {
                        $pollstatus = $vbphrase['this_poll_is_closed'];
                    } else {
                        if ($uservoted) {
                            $pollstatus = $vbphrase['you_have_already_voted_on_this_poll'];
                        }
                    }
                }
                ($hook = vBulletinHook::fetch_hook('showthread_polloption')) ? eval($hook) : false;
                $templater = vB_Template::create('pollresult');
                $templater->register('names', $names);
                $templater->register('option', $option);
                $pollbits .= $templater->render();
            } else {
                ($hook = vBulletinHook::fetch_hook('showthread_polloption')) ? eval($hook) : false;
                if ($pollinfo['multiple']) {
                    $templater = vB_Template::create('polloption_multiple');
                    $templater->register('option', $option);
                    $pollbits .= $templater->render();
                } else {
                    $templater = vB_Template::create('polloption');
                    $templater->register('option', $option);
                    $pollbits .= $templater->render();
                }
            }
            $counter++;
        }
        if ($pollinfo['multiple']) {
            $pollinfo['numbervotes'] = $pollinfo['voters'];
            $show['multiple'] = true;
        }
        if ($pollinfo['public']) {
            $show['publicwarning'] = true;
        } else {
            $show['publicwarning'] = false;
        }
        $displayed_dateline = $threadinfo['lastpost'];
        ($hook = vBulletinHook::fetch_hook('showthread_poll_complete')) ? eval($hook) : false;
        if ($showresults or $uservoted) {
            $templater = vB_Template::create('pollresults_table');
            $templater->register('pollbits', $pollbits);
            $templater->register('pollenddate', $pollenddate);
            $templater->register('pollendtime', $pollendtime);
            $templater->register('pollinfo', $pollinfo);
            $templater->register('pollstatus', $pollstatus);
            $poll = $templater->render();
        } else {
            $templater = vB_Template::create('polloptions_table');
            $templater->register('pollbits', $pollbits);
            $templater->register('pollenddate', $pollenddate);
            $templater->register('pollendtime', $pollendtime);
            $templater->register('pollinfo', $pollinfo);
            $poll = $templater->render();
        }
    }
    // work out if quickreply should be shown or not
    if ($vbulletin->options['quickreply'] and !$thread['isdeleted'] and !is_browser('netscape') and $vbulletin->userinfo['userid'] and ($vbulletin->userinfo['userid'] == $threadinfo['postuserid'] and $forumperms & $vbulletin->bf_ugp_forumpermissions['canreplyown'] or $vbulletin->userinfo['userid'] != $threadinfo['postuserid'] and $forumperms & $vbulletin->bf_ugp_forumpermissions['canreplyothers']) and ($thread['open'] or can_moderate($threadinfo['forumid'], 'canopenclose')) and !fetch_require_hvcheck('post')) {
        $show['quickreply'] = true;
    } else {
        $show['quickreply'] = false;
        $show['wysiwyg'] = 0;
        $quickreply = '';
    }
    $show['largereplybutton'] = (!$thread['isdeleted'] and !$show['threadedmode'] and $forum['allowposting'] and !$show['search_engine']);
    if (!$forum['allowposting']) {
        $show['quickreply'] = false;
    }
    $show['multiquote_global'] = ($vbulletin->options['multiquote'] and $vbulletin->userinfo['userid']);
    if ($show['multiquote_global']) {
        $vbulletin->input->clean_array_gpc('c', array('vbulletin_multiquote' => TYPE_STR));
        $vbulletin->GPC['vbulletin_multiquote'] = explode(',', $vbulletin->GPC['vbulletin_multiquote']);
    }
    // post is cachable if option is enabled, last post is newer than max age, and this user
    // isn't showing a sessionhash
    $post_cachable = ($vbulletin->options['cachemaxage'] > 0 and TIMENOW - $vbulletin->options['cachemaxage'] * 60 * 60 * 24 <= $thread['lastpost'] and $vbulletin->session->vars['sessionurl'] == '');
    $saveparsed = '';
    $save_parsed_sigs = '';
    ($hook = vBulletinHook::fetch_hook('showthread_post_start')) ? eval($hook) : false;
    ################################################################################
    ####################### SHOW THREAD IN LINEAR MODE #############################
    ################################################################################
    if ($threadedmode == 0) {
        // allow deleted posts to not be counted in number of posts displayed on the page;
        // prevents issue with page count on forum display being incorrect
        $ids = array();
        $lastpostid = 0;
        $hook_query_joins = $hook_query_where = '';
        ($hook = vBulletinHook::fetch_hook('showthread_query_postids')) ? eval($hook) : false;
        if (empty($deljoin) and !$show['approvepost']) {
            $totalposts = $threadinfo['replycount'] + 1;
            if (can_moderate($thread['forumid'])) {
                $coventry = '';
            } else {
                $coventry = fetch_coventry('string');
            }
            $getpostids = $db->query_read("\n    \t\t\tSELECT post.postid\n    \t\t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\t\t{$hook_query_joins}\n    \t\t\tWHERE post.threadid = {$threadid}\n    \t\t\t\tAND post.visible = 1\n    \t\t\t\t" . ($coventry ? "AND post.userid NOT IN ({$coventry})" : '') . "\n    \t\t\t\t{$hook_query_where}\n    \t\t\tORDER BY post.dateline {$postorder}\n    \t\t\tLIMIT {$limitlower}, {$perpage}\n    \t\t");
            while ($post = $db->fetch_array($getpostids)) {
                if (!isset($qrfirstpostid)) {
                    $qrfirstpostid = $post['postid'];
                }
                $qrlastpostid = $post['postid'];
                $ids[] = $post['postid'];
            }
            $db->free_result($getpostids);
            $lastpostid = $qrlastpostid;
        } else {
            $getpostids = $db->query_read("\n    \t\t\tSELECT post.postid, post.visible, post.userid\n    \t\t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\t\t{$hook_query_joins}\n    \t\t\tWHERE post.threadid = {$threadid}\n    \t\t\t\tAND post.visible IN (1\n    \t\t\t\t" . (!empty($deljoin) ? ",2" : "") . "\n    \t\t\t\t" . ($show['approvepost'] ? ",0" : "") . "\n    \t\t\t\t)\n    \t\t\t\t{$hook_query_where}\n    \t\t\tORDER BY post.dateline {$postorder}\n    \t\t");
            $totalposts = 0;
            if ($limitlower != 0) {
                $limitlower++;
            }
            while ($post = $db->fetch_array($getpostids)) {
                if (!isset($qrfirstpostid)) {
                    $qrfirstpostid = $post['postid'];
                }
                $qrlastpostid = $post['postid'];
                if ($post['visible'] == 1 and !in_coventry($post['userid']) and !$ignore[$post['userid']]) {
                    $totalposts++;
                }
                if ($totalposts < $limitlower or $totalposts > $limitupper) {
                    continue;
                }
                // remember, these are only added if they're going to be displayed
                $ids[] = $post['postid'];
                $lastpostid = $post['postid'];
            }
            $db->free_result($getpostids);
        }
        // '0' inside parenthesis in unlikely case we have no ids for this page
        // (this could happen if the replycount is wrong in the db)
        $postids = "post.postid IN (0" . implode(',', $ids) . ")";
        // load attachments
        if ($thread['attach']) {
            require_once DIR . '/packages/vbattach/attach.php';
            $attach = new vB_Attach_Display_Content($vbulletin, 'vBForum_Post');
            $postattach = $attach->fetch_postattach(0, $ids);
        }
        $hook_query_fields = $hook_query_joins = '';
        ($hook = vBulletinHook::fetch_hook('showthread_query')) ? eval($hook) : false;
        $posts = $db->query_read("\n    \t\tSELECT\n    \t\t\tpost.*, post.username AS postusername, post.ipaddress AS ip, IF(post.visible = 2, 1, 0) AS isdeleted,\n    \t\t\tuser.*, userfield.*, usertextfield.*,\n    \t\t\t" . iif($forum['allowicons'], 'icon.title as icontitle, icon.iconpath,') . "\n    \t\t\t" . iif($vbulletin->options['avatarenabled'], 'avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustomavatar, customavatar.dateline AS avatardateline,customavatar.width AS avwidth,customavatar.height AS avheight,') . "\n    \t\t\t" . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? 'spamlog.postid AS spamlog_postid,' : '') . "\n    \t\t\t" . iif($deljoin, 'deletionlog.userid AS del_userid, deletionlog.username AS del_username, deletionlog.reason AS del_reason,') . "\n    \t\t\teditlog.userid AS edit_userid, editlog.username AS edit_username, editlog.dateline AS edit_dateline,\n    \t\t\teditlog.reason AS edit_reason, editlog.hashistory,\n    \t\t\tpostparsed.pagetext_html, postparsed.hasimages,\n    \t\t\tsigparsed.signatureparsed, sigparsed.hasimages AS sighasimages,\n    \t\t\tsigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline, sigpic.width AS sigpicwidth, sigpic.height AS sigpicheight,\n    \t\t\tIF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid\n    \t\t\t" . iif(!($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canseehiddencustomfields']), $vbulletin->profilefield['hidden']) . "\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = post.userid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON(userfield.userid = user.userid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON(usertextfield.userid = user.userid)\n    \t\t" . iif($forum['allowicons'], "LEFT JOIN " . TABLE_PREFIX . "icon AS icon ON(icon.iconid = post.iconid)") . "\n    \t\t" . iif($vbulletin->options['avatarenabled'], "LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON(avatar.avatarid = user.avatarid) LEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON(customavatar.userid = user.userid)") . "\n    \t\t" . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? "LEFT JOIN " . TABLE_PREFIX . "spamlog AS spamlog ON(spamlog.postid = post.postid)" : '') . "\n    \t\t\t{$deljoin}\n    \t\tLEFT JOIN " . TABLE_PREFIX . "editlog AS editlog ON(editlog.postid = post.postid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "postparsed AS postparsed ON(postparsed.postid = post.postid AND postparsed.styleid = " . intval(STYLEID) . " AND postparsed.languageid = " . intval(LANGUAGEID) . ")\n    \t\tLEFT JOIN " . TABLE_PREFIX . "sigparsed AS sigparsed ON(sigparsed.userid = user.userid AND sigparsed.styleid = " . intval(STYLEID) . " AND sigparsed.languageid = " . intval(LANGUAGEID) . ")\n    \t\tLEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON(sigpic.userid = post.userid)\n    \t\t\t{$hook_query_joins}\n    \t\tWHERE {$postids}\n    \t\tORDER BY post.dateline {$postorder}\n    \t");
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canseethumbnails']) and !($forumperms & $vbulletin->bf_ugp_forumpermissions['cangetattachment'])) {
            $vbulletin->options['attachthumbs'] = 0;
        }
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['cangetattachment'])) {
            $vbulletin->options['viewattachedimages'] = 0;
        }
        $postcount = ($vbulletin->GPC['pagenumber'] - 1) * $perpage;
        if ($postorder) {
            // Newest first
            $postcount = $totalposts - $postcount + 1;
        }
        $counter = 0;
        $postbits = '';
        $postbit_factory = new vB_Postbit_Factory();
        $postbit_factory->registry =& $vbulletin;
        $postbit_factory->forum =& $foruminfo;
        $postbit_factory->thread =& $thread;
        $postbit_factory->cache = array();
        $postbit_factory->bbcode_parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
        while ($post = $db->fetch_array($posts)) {
            if ($tachyuser = in_coventry($post['userid']) and !can_moderate($thread['forumid'])) {
                continue;
            }
            if ($post['visible'] == 1 and !$tachyuser) {
                ++$counter;
                if ($postorder) {
                    $post['postcount'] = --$postcount;
                } else {
                    $post['postcount'] = ++$postcount;
                }
            }
            if ($tachyuser) {
                $fetchtype = 'post_global_ignore';
            } else {
                if ($ignore["{$post['userid']}"]) {
                    $fetchtype = 'post_ignore';
                } else {
                    if ($post['visible'] == 2) {
                        $fetchtype = 'post_deleted';
                    } else {
                        $fetchtype = 'post';
                    }
                }
            }
            if ($vbulletin->GPC['viewfull'] and $post['postid'] == $postinfo['postid'] and $fetchtype != 'post' and (can_moderate($threadinfo['forumid']) or !$post['isdeleted'])) {
                $fetchtype = 'post';
            }
            if ($fetchtype != 'post' && $fetchtype != 'post_deleted') {
                continue;
            }
            ($hook = vBulletinHook::fetch_hook('showthread_postbit_create')) ? eval($hook) : false;
            $postbit_obj =& $postbit_factory->fetch_postbit($fetchtype);
            if ($fetchtype == 'post') {
                $postbit_obj->highlight =& $replacewords;
            }
            $postbit_obj->cachable = $post_cachable;
            $post['islastshown'] = $post['postid'] == $lastpostid;
            $post['isfirstshown'] = ($counter == 1 and $fetchtype == 'post' and $post['visible'] == 1);
            $post['islastshown'] = $post['postid'] == $lastpostid;
            $post['attachments'] = $postattach["{$post['postid']}"];
            $parsed_postcache = array('text' => '', 'images' => 1, 'skip' => false);
            $postbits .= $postbit_obj->construct_postbit($post);
            // Only show after the first post, counter isn't incremented for deleted/moderated posts
            if ($post['isfirstshown']) {
                $postbits .= vB_Template::create('ad_showthread_firstpost')->render();
            }
            if ($post_cachable and $post['pagetext_html'] == '') {
                if (!empty($saveparsed)) {
                    $saveparsed .= ',';
                }
                $saveparsed .= "({$post['postid']}, " . intval($thread['lastpost']) . ', ' . intval($postbit_obj->post_cache['has_images']) . ", '" . $db->escape_string($postbit_obj->post_cache['text']) . "', " . intval(STYLEID) . ", " . intval(LANGUAGEID) . ")";
            }
            if (!empty($postbit_obj->sig_cache) and $post['userid']) {
                if (!empty($save_parsed_sigs)) {
                    $save_parsed_sigs .= ',';
                }
                $save_parsed_sigs .= "({$post['userid']}, " . intval(STYLEID) . ", " . intval(LANGUAGEID) . ", '" . $db->escape_string($postbit_obj->sig_cache['text']) . "', " . intval($postbit_obj->sig_cache['has_images']) . ")";
            }
            // get first and last post ids for this page (for big reply buttons)
            if (!isset($FIRSTPOSTID)) {
                $FIRSTPOSTID = $post['postid'];
            }
            $LASTPOSTID = $post['postid'];
            if ($post['dateline'] > $displayed_dateline) {
                $displayed_dateline = $post['dateline'];
                if ($displayed_dateline <= $threadview) {
                    $updatethreadcookie = true;
                }
            }
            // FRNR Start
            // find out if first post
            $getpost = $db->query_first("\n                    SELECT firstpostid\n                    FROM " . TABLE_PREFIX . "thread\n                    WHERE threadid = {$threadinfo['threadid']}\n                ");
            $isfirstpost = $getpost['firstpostid'] == $post['postid'];
            $candelete = false;
            if ($isfirstpost and can_moderate($threadinfo['forumid'], 'canmanagethreads')) {
                $candelete = true;
            } else {
                if (!$isfirstpost and can_moderate($threadinfo['forumid'], 'candeleteposts')) {
                    $candelete = true;
                } else {
                    if (($forumperms & $vbulletin->bf_ugp_forumpermissions['candeletepost'] and !$isfirstpost or $forumperms & $vbulletin->bf_ugp_forumpermissions['candeletethread'] and $isfirstpost) and $vbulletin->userinfo['userid'] == $post['userid']) {
                        $candelete = true;
                    }
                }
            }
            // Get post date/time
            $postdate = vbdate($vbulletin->options['dateformat'], $post['dateline'], 1);
            $posttime = vbdate($vbulletin->options['timeformat'], $post['dateline']);
            $fr_images = array();
            $docattach = array();
            // Attachments (images).
            if (is_array($post['attachments']) && count($post['attachments']) > 0) {
                foreach ($post['attachments'] as $attachment) {
                    $lfilename = strtolower($attachment['filename']);
                    if (strpos($lfilename, '.jpe') !== false || strpos($lfilename, '.png') !== false || strpos($lfilename, '.gif') !== false || strpos($lfilename, '.jpg') !== false || strpos($lfilename, '.jpeg') !== false) {
                        $tmp = array('img' => $vbulletin->options['bburl'] . '/attachment.php?attachmentid=' . $attachment['attachmentid']);
                        if ($vbulletin->options['attachthumbs']) {
                            $tmp['tmb'] = $vbulletin->options['bburl'] . '/attachment.php?attachmentid=' . $attachment['attachmentid'] . '&stc=1&thumb=1';
                        }
                        $fr_images[] = $tmp;
                    }
                    if (strpos($lfilename, '.pdf') !== false) {
                        $docattach[] = $vbulletin->options['bburl'] . '/attachment.php?attachmentid=' . $attachment['attachmentid'];
                    }
                }
            }
            // Parse the post for quotes and inline images
            list($text, $nuked_quotes, $images) = parse_post($post['pagetext'], $post['allowsmilie'] && $usesmilies);
            if (count($fr_images) > 0) {
                $text .= "<br/>";
                foreach ($fr_images as $attachment) {
                    $text .= "<img src=\"{$attachment['img']}\"/>";
                }
            }
            foreach ($images as $image) {
                $fr_images[] = array('img' => $image);
            }
            $avatarurl = '';
            // Avatar work
            if ($post['avatarurl']) {
                $avatarurl = process_avatarurl($post['avatarurl']);
            }
            $tmp = array('post_id' => $post['postid'], 'thread_id' => $post['threadid'], 'forum_id' => $foruminfo['forumid'], 'forum_title' => prepare_utf8_string($foruminfo['title_clean']), 'username' => prepare_utf8_string(strip_tags($post['username'])), 'joindate' => prepare_utf8_string($post['joindate']), 'usertitle' => prepare_utf8_string(strip_tags($post['usertitle'])), 'numposts' => $post['posts'] ? (string) $post['posts'] : '0', 'userid' => $post['userid'], 'title' => prepare_utf8_string($post['title']), 'online' => fetch_online_status(fetch_userinfo($post['userid']), false), 'post_timestamp' => prepare_utf8_string(date_trunc($postdate) . ' ' . $posttime), 'fr_images' => $fr_images);
            if ($candelete) {
                $tmp['candelete'] = true;
            }
            // Soft Deleted
            if ($post['visible'] == 2) {
                $tmp['deleted'] = true;
                $tmp['del_username'] = prepare_utf8_string($post['del_username']);
                if ($post['del_reason']) {
                    $tmp['del_reason'] = prepare_utf8_string($post['del_reason']);
                }
            } else {
                $tmp['text'] = $text;
                $tmp['quotable'] = $nuked_quotes;
                if ($post['editlink']) {
                    $tmp['canedit'] = true;
                    $tmp['edittext'] = prepare_utf8_string($post['pagetext']);
                }
            }
            if ($avatarurl != '') {
                $tmp['avatarurl'] = $avatarurl;
            }
            if (count($docattach) > 0) {
                $tmp['docattach'] = $docattach;
            }
            if ($vbulletin->GPC['signature']) {
                $sig = trim(remove_bbcode(strip_tags($post['signatureparsed']), true, true), '<a>');
                $sig = str_replace(array("\t", "\r"), array('', ''), $sig);
                $sig = str_replace("\n\n", "\n", $sig);
                $tmp['sig'] = prepare_utf8_string($sig);
            }
            // Begin Support for Post Thanks Hack - http://www.vbulletin.org/forum/showthread.php?t=122944
            if ($vbulletin->userinfo['userid'] && function_exists('post_thanks_off') && function_exists('can_thank_this_post') && function_exists('thanked_already') && function_exists('fetch_thanks')) {
                if (!post_thanks_off($thread['forumid'], $post, $thread['firstpostid'], THIS_SCRIPT)) {
                    global $ids;
                    if (can_thank_this_post($post, $thread['isdeleted'])) {
                        $tmp['canlike'] = true;
                    }
                    if (thanked_already($post, 0, true)) {
                        $tmp['likes'] = true;
                        if (!$vbulletin->options['post_thanks_delete_own']) {
                            $tmp['canlike'] = $tmp['likes'] = false;
                        }
                    }
                    $thanks = fetch_thanks($post['postid']);
                    $thank_users = array();
                    if (is_array($thanks)) {
                        foreach ($thanks as $thank) {
                            $thank_users[] = $thank['username'];
                        }
                    }
                    if (count($thank_users)) {
                        $tmp['likestext'] = prepare_utf8_string($vbphrase['fr_thanked_by'] . ': ' . join(', ', $thank_users));
                        $tmp['likesusers'] = join(', ', $thank_users);
                    }
                }
            }
            // End Support for Post Thanks Hack
            $posts_out[] = $tmp;
            // FRNR End
        }
        $db->free_result($posts);
        unset($post);
        if ($postbits == '' and $vbulletin->GPC['pagenumber'] > 1) {
            $pageinfo = array('page' => $vbulletin->GPC['pagenumber'] - 1);
            if (!empty($vbulletin->GPC['perpage'])) {
                $pageinfo['pp'] = $perpage;
            }
            if (!empty($vbulletin->GPC['highlight'])) {
                $pageinfo['highlight'] = urlencode($vbulletin->GPC['highlight']);
            }
            exec_header_redirect(fetch_seo_url('thread|js', $threadinfo, $pageinfo));
        }
        DEVDEBUG("First Post: {$FIRSTPOSTID}; Last Post: {$LASTPOSTID}");
        $pageinfo = array();
        if ($vbulletin->GPC['highlight']) {
            $pageinfo['highlight'] = urlencode($vbulletin->GPC['highlight']);
        }
        if (!empty($vbulletin->GPC['perpage'])) {
            $pageinfo['pp'] = $perpage;
        }
        $pagenav = construct_page_nav($vbulletin->GPC['pagenumber'], $perpage, $totalposts, 'showthread.php?' . $vbulletin->session->vars['sessionurl'] . "t={$threadinfo['threadid']}", '', '', 'thread', $threadinfo, $pageinfo);
        if ($thread['lastpost'] > $threadview) {
            if ($firstnew) {
                $firstunread = fetch_seo_url('thread', $threadinfo, array('page' => $vbulletin->GPC['pagenumber'])) . '#post' . $firstnew;
                $show['firstunreadlink'] = true;
            } else {
                $firstunread = fetch_seo_url('thread', $threadinfo, array('goto' => 'newpost'));
                $show['firstunreadlink'] = true;
            }
        } else {
            $firstunread = '';
            $show['firstunreadlink'] = false;
        }
        if ($vbulletin->userinfo['postorder']) {
            // disable ajax qr when displaying linear newest first
            $show['allow_ajax_qr'] = 0;
        } else {
            // only allow ajax on the last page of a thread when viewing oldest first
            $show['allow_ajax_qr'] = $vbulletin->GPC['pagenumber'] == ceil($totalposts / $perpage) ? 1 : 0;
        }
        ################################################################################
        ################ SHOW THREAD IN THREADED OR HYBRID MODE ########################
        ################################################################################
    } else {
        // ajax qr doesn't work with threaded controls
        $show['allow_ajax_qr'] = 0;
        require_once DIR . '/includes/functions_threadedmode.php';
        // save data
        $ipostarray = array();
        $postarray = array();
        $userarray = array();
        $postparent = array();
        $postorder = array();
        $hybridposts = array();
        $deletedparents = array();
        $totalposts = 0;
        $links = '';
        $cache_postids = '';
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        ($hook = vBulletinHook::fetch_hook('showthread_query_postids_threaded')) ? eval($hook) : false;
        // get all posts
        $listposts = $db->query_read("\n    \t\tSELECT\n    \t\t\tpost.*, post.username AS postusername, post.ipaddress AS ip, IF(post.visible = 2, 1, 0) AS isdeleted,\n    \t\t\tuser.*, userfield.*\n    \t\t\t" . iif(!($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canseehiddencustomfields']), $vbulletin->profilefield['hidden']) . "\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = post.userid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON(userfield.userid = user.userid)\n    \t\t{$hook_query_joins}\n    \t\tWHERE threadid = {$threadid}\n    \t\t\t{$hook_query_where}\n    \t\tORDER BY postid\n    \t");
        // $toppostid is the first post in the thread
        // $curpostid is the postid passed from the URL, or if not specified, the first post in the thread
        $ids = array();
        while ($post = $db->fetch_array($listposts)) {
            if ($post['visible'] == 2 and !$deljoin or $post['visible'] == 0 and !$show['approvepost'] or in_coventry($post['userid']) and !can_moderate($thread['forumid'])) {
                $deletedparents["{$post['postid']}"] = iif(isset($deletedparents["{$post['parentid']}"]), $deletedparents["{$post['parentid']}"], $post['parentid']);
                continue;
            }
            if (empty($toppostid)) {
                $toppostid = $post['postid'];
            }
            if (empty($postid)) {
                if (empty($curpostid)) {
                    $curpostid = $post['postid'];
                    if ($threadedmode == 2 and empty($vbulletin->GPC['postid'])) {
                        $vbulletin->GPC['postid'] = $curpostid;
                    }
                    $curpostparent = $post['parentid'];
                }
            } else {
                if ($post['postid'] == $postid) {
                    $curpostid = $post['postid'];
                    $curpostparent = $post['parentid'];
                }
            }
            $postparent["{$post['postid']}"] = $post['parentid'];
            $ipostarray["{$post['parentid']}"][] = $post['postid'];
            $postarray["{$post['postid']}"] = $post;
            $userarray["{$post['userid']}"] = $db->escape_string($post['username']);
            $totalposts++;
            $ids[] = $post['postid'];
        }
        $db->free_result($listposts);
        // hooks child posts up to new parent if actual parent has been deleted or hidden
        if (count($deletedparents) > 0) {
            foreach ($deletedparents as $dpostid => $dparentid) {
                if (is_array($ipostarray[$dpostid])) {
                    foreach ($ipostarray[$dpostid] as $temppostid) {
                        $postparent[$temppostid] = $dparentid;
                        $ipostarray[$dparentid][] = $temppostid;
                        $postarray[$temppostid]['parentid'] = $dparentid;
                    }
                    unset($ipostarray[$dpostid]);
                }
                if ($curpostparent == $dpostid) {
                    $curpostparent = $dparentid;
                }
            }
        }
        unset($post, $listposts, $deletedparents);
        if ($thread['attach']) {
            require_once DIR . '/packages/vbattach/attach.php';
            $attach = new vB_Attach_Display_Content($vbulletin, 'vBForum_Post');
            $postattach = $attach->fetch_postattach(0, $ids);
        }
        // get list of usernames from post list
        $userjs = '';
        foreach ($userarray as $userid => $username) {
            if ($userid) {
                $userjs .= "pu[{$userid}] = \"" . addslashes_js($username) . "\";\n";
            }
        }
        unset($userarray, $userid, $username);
        $parent_postids = fetch_post_parentlist($curpostid);
        if (!$parent_postids) {
            $currentdepth = 0;
        } else {
            $currentdepth = sizeof(explode(',', $parent_postids));
        }
        sort_threaded_posts();
        if (empty($curpostid)) {
            eval(standard_error(fetch_error('invalidid', $vbphrase['post'], $vbulletin->options['contactuslink'])));
        }
        if ($threadedmode == 2) {
            $numhybrids = sizeof($hybridposts);
            if ($vbulletin->GPC['pagenumber'] < 1) {
                $vbulletin->GPC['pagenumber'] = 1;
            }
            $startat = ($vbulletin->GPC['pagenumber'] - 1) * $perpage;
            if ($startat > $numhybrids) {
                $vbulletin->GPC['pagenumber'] = 1;
                $startat = 0;
            }
            $endat = $startat + $perpage;
            for ($i = $startat; $i < $endat; $i++) {
                if (isset($hybridposts["{$i}"])) {
                    if (!isset($FIRSTPOSTID)) {
                        $FIRSTPOSTID = $hybridposts["{$i}"];
                    }
                    $cache_postids .= ",{$hybridposts[$i]}";
                    $LASTPOSTID = $hybridposts["{$i}"];
                }
            }
            $pageinfo = array('p' => $vbulletin->GPC['postid']);
            if ($vbulletin->GPC['highlight']) {
                $pageinfo['highlight'] = urlencode($vbulletin->GPC['highlight']);
            }
            if (!empty($vbulletin->GPC['perpage'])) {
                $pageinfo['pp'] = $perpage;
            }
            $pagenav = construct_page_nav($vbulletin->GPC['pagenumber'], $perpage, $numhybrids, 'showthread.php?' . $vbulletin->session->vars['sessionurl'] . "t={$threadinfo['threadid']}", '', '', 'thread', $threadinfo, $pageinfo);
        } else {
            $FIRSTPOSTID = $curpostid;
            $LASTPOSTID = $curpostid;
            // sort out which posts to cache:
            if (!$vbulletin->options['threaded_maxcache']) {
                $vbulletin->options['threaded_maxcache'] = 999999;
            }
            // cache $vbulletin->options['threaded_maxcache'] posts
            // take 0.25 from above $curpostid
            // and take 0.75 below
            if (sizeof($postorder) <= $vbulletin->options['threaded_maxcache']) {
                $startat = 0;
            } else {
                if ($curpostidkey + $vbulletin->options['threaded_maxcache'] * 0.75 > sizeof($postorder)) {
                    $startat = sizeof($postorder) - $vbulletin->options['threaded_maxcache'];
                } else {
                    if ($curpostidkey - $vbulletin->options['threaded_maxcache'] * 0.25 < 0) {
                        $startat = 0;
                    } else {
                        $startat = intval($curpostidkey - $vbulletin->options['threaded_maxcache'] * 0.25);
                    }
                }
            }
            unset($curpostidkey);
            foreach ($postorder as $postkey => $pid) {
                if ($postkey > $startat + $vbulletin->options['threaded_maxcache']) {
                    break;
                }
                if ($postkey >= $startat and empty($morereplies["{$pid}"])) {
                    $cache_postids .= ',' . $pid;
                }
            }
            // get next/previous posts for each post in the list
            // key: NAVJS[postid][0] = prev post, [1] = next post
            $NAVJS = array();
            $prevpostid = 0;
            foreach ($postorder as $pid) {
                $NAVJS["{$pid}"][0] = $prevpostid;
                $NAVJS["{$prevpostid}"][1] = $pid;
                $prevpostid = $pid;
            }
            $NAVJS["{$toppostid}"][0] = $pid;
            //prev button for first post
            $NAVJS["{$pid}"][1] = $toppostid;
            //next button for last post
            $navjs = '';
            foreach ($NAVJS as $pid => $info) {
                $navjs .= "pn[{$pid}] = \"{$info['0']},{$info['1']}\";\n";
            }
        }
        unset($ipostarray, $postparent, $postorder, $NAVJS, $postid, $info, $prevpostid, $postkey);
        $cache_postids = substr($cache_postids, 1);
        if (empty($cache_postids)) {
            // umm... something weird happened. Just prevent an error.
            eval(standard_error(fetch_error('invalidid', $vbphrase['post'], $vbulletin->options['contactuslink'])));
        }
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        ($hook = vBulletinHook::fetch_hook('showthread_query')) ? eval($hook) : false;
        $cacheposts = $db->query_read("\n    \t\tSELECT\n    \t\t\tpost.*, post.username AS postusername, post.ipaddress AS ip, IF(post.visible = 2, 1, 0) AS isdeleted,\n    \t\t\tuser.*, userfield.*, usertextfield.*,\n    \t\t\t" . iif($forum['allowicons'], 'icon.title as icontitle, icon.iconpath,') . "\n    \t\t\t" . iif($vbulletin->options['avatarenabled'], 'avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustomavatar, customavatar.dateline AS avatardateline,') . "\n    \t\t\t" . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? 'spamlog.postid AS spamlog_postid,' : '') . "\n    \t\t\t" . iif($deljoin, "deletionlog.userid AS del_userid, deletionlog.username AS del_username, deletionlog.reason AS del_reason,") . "\n    \t\t\teditlog.userid AS edit_userid, editlog.username AS edit_username, editlog.dateline AS edit_dateline,\n    \t\t\teditlog.reason AS edit_reason, editlog.hashistory,\n    \t\t\tpostparsed.pagetext_html, postparsed.hasimages,\n    \t\t\tsigparsed.signatureparsed, sigparsed.hasimages AS sighasimages,\n    \t\t\tsigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline, sigpic.width AS sigpicwidth, sigpic.height AS sigpicheight,\n    \t\t\tIF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid\n    \t\t\t" . iif(!($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canseehiddencustomfields']), $vbulletin->profilefield['hidden']) . "\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "post AS post\n    \t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = post.userid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON(userfield.userid = user.userid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON(usertextfield.userid = user.userid)\n    \t\t" . iif($forum['allowicons'], "LEFT JOIN " . TABLE_PREFIX . "icon AS icon ON(icon.iconid = post.iconid)") . "\n    \t\t" . iif($vbulletin->options['avatarenabled'], "LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON(avatar.avatarid = user.avatarid) LEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON(customavatar.userid = user.userid)") . "\n    \t\t" . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? "LEFT JOIN " . TABLE_PREFIX . "spamlog AS spamlog ON(spamlog.postid = post.postid)" : '') . "\n    \t\t\t{$deljoin}\n    \t\tLEFT JOIN " . TABLE_PREFIX . "editlog AS editlog ON(editlog.postid = post.postid)\n    \t\tLEFT JOIN " . TABLE_PREFIX . "postparsed AS postparsed ON(postparsed.postid = post.postid AND postparsed.styleid = " . intval(STYLEID) . " AND postparsed.languageid = " . intval(LANGUAGEID) . ")\n    \t\tLEFT JOIN " . TABLE_PREFIX . "sigparsed AS sigparsed ON(sigparsed.userid = user.userid AND sigparsed.styleid = " . intval(STYLEID) . " AND sigparsed.languageid = " . intval(LANGUAGEID) . ")\n    \t\tLEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON(sigpic.userid = post.userid)\n    \t\t\t{$hook_query_joins}\n    \t\tWHERE post.postid IN (" . $cache_postids . ") {$hook_query_where}\n    \t");
        // re-initialise the $postarray variable
        $postarray = array();
        while ($post = $db->fetch_array($cacheposts)) {
            $postarray["{$post['postid']}"] = $post;
        }
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['cangetattachment'])) {
            $vbulletin->options['viewattachedimages'] = 0;
            $vbulletin->options['attachthumbs'] = 0;
        }
        // init
        $postcount = 0;
        $postbits = '';
        $saveparsed = '';
        $jspostbits = '';
        $postbit_factory = new vB_Postbit_Factory();
        $postbit_factory->registry =& $vbulletin;
        $postbit_factory->forum =& $foruminfo;
        $postbit_factory->thread =& $thread;
        $postbit_factory->cache = array();
        $postbit_factory->bbcode_parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
        foreach (explode(',', $cache_postids) as $id) {
            // get the post from the post array
            if (!isset($postarray["{$id}"])) {
                continue;
            }
            $post = $postarray["{$id}"];
            if ($tachyuser = in_coventry($post['userid']) and !can_moderate($thread['forumid'])) {
                continue;
            }
            if ($tachyuser) {
                $fetchtype = 'post_global_ignore';
            } else {
                if ($ignore["{$post['userid']}"]) {
                    $fetchtype = 'post_ignore';
                } else {
                    if ($post['visible'] == 2) {
                        $fetchtype = 'post_deleted';
                    } else {
                        $fetchtype = 'post';
                    }
                }
            }
            if ($vbulletin->GPC['viewfull'] and $post['postid'] == $postinfo['postid'] and $fetchtype != 'post' and (can_moderate($threadinfo['forumid']) or !$post['isdeleted'])) {
                $fetchtype = 'post';
            }
            ($hook = vBulletinHook::fetch_hook('showthread_postbit_create')) ? eval($hook) : false;
            $postbit_obj =& $postbit_factory->fetch_postbit($fetchtype);
            if ($fetchtype == 'post') {
                $postbit_obj->highlight =& $replacewords;
            }
            $postbit_obj->cachable = $post_cachable;
            $post['postcount'] = ++$postcount;
            $post['attachments'] =& $postattach["{$post['postid']}"];
            $parsed_postcache = array('text' => '', 'images' => 1);
            $bgclass = 'alt2';
            if ($threadedmode == 2) {
                $postbits .= $postbit_obj->construct_postbit($post);
            } else {
                $postbit = $postbit_obj->construct_postbit($post);
                if ($curpostid == $post['postid']) {
                    $curpostdateline = $post['dateline'];
                    $curpostbit = $postbit;
                }
                $postbit = preg_replace('#</script>#i', "<\\/scr' + 'ipt>", addslashes_js($postbit));
                $jspostbits .= "pd[{$post['postid']}] = '{$postbit}';\n";
            }
            // end threaded mode
            if ($post_cachable and $post['pagetext_html'] == '') {
                if (!empty($saveparsed)) {
                    $saveparsed .= ',';
                }
                $saveparsed .= "({$post['postid']}, " . intval($thread['lastpost']) . ', ' . intval($postbit_obj->post_cache['has_images']) . ", '" . $db->escape_string($postbit_obj->post_cache['text']) . "'," . intval(STYLEID) . ", " . intval(LANGUAGEID) . ")";
            }
            if (!empty($postbit_obj->sig_cache) and $post['userid']) {
                if (!empty($save_parsed_sigs)) {
                    $save_parsed_sigs .= ',';
                }
                $save_parsed_sigs .= "({$post['userid']}, " . intval(STYLEID) . ", " . intval(LANGUAGEID) . ", '" . $db->escape_string($postbit_obj->sig_cache['text']) . "', " . intval($postbit_obj->sig_cache['has_images']) . ")";
            }
            if ($post['dateline'] > $displayed_dateline) {
                $displayed_dateline = $post['dateline'];
                if ($displayed_dateline <= $threadview) {
                    $updatethreadcookie = true;
                }
            }
        }
        // end while ($post)
        $db->free_result($cacheposts);
        if ($threadedmode == 1) {
            $postbits = $curpostbit;
        }
        $templater = vB_Template::create('showthread_list');
        $templater->register('curpostid', $curpostid);
        $templater->register('highlightwords', $highlightwords);
        $templater->register('jspostbits', $jspostbits);
        $templater->register('links', $links);
        $templater->register('navjs', $navjs);
        $templater->register('threadedmode', $threadedmode);
        $templater->register('userjs', $userjs);
        $threadlist = $templater->render();
        unset($curpostbit, $post, $cacheposts, $parsed_postcache, $postbit);
    }
    ################################################################################
    ########################## END LINEAR / THREADED ###############################
    ################################################################################
    $effective_lastpost = max($displayed_dateline, $thread['lastpost']);
    // *********************************************************************************
    //set thread last view
    if ($thread['pollid'] and $vbulletin->options['updatelastpost'] and ($displayed_dateline == $thread['lastpost'] or $threadview == $thread['lastpost']) and $pollinfo['lastvote'] > $thread['lastpost']) {
        $displayed_dateline = $pollinfo['lastvote'];
    }
    if ((!$vbulletin->GPC['posted'] or $updatethreadcookie) and $displayed_dateline and $displayed_dateline > $threadview) {
        mark_thread_read($threadinfo, $foruminfo, $vbulletin->userinfo['userid'], $displayed_dateline);
    }
    // FRNR Below
    fr_update_subsent($threadinfo['threadid'], $displayed_dateline);
    if (!is_array($posts_out)) {
        $posts_out = array();
    }
    // Figure out if we can post
    $canpost = true;
    if ($threadinfo['isdeleted'] or !$threadinfo['visible'] and !can_moderate($threadinfo['forumid'], 'canmoderateposts')) {
        $canpost = false;
    }
    if (!$foruminfo['allowposting'] or $foruminfo['link'] or !$foruminfo['cancontainthreads']) {
        $canpost = false;
    }
    if (!$threadinfo['open']) {
        if (!can_moderate($threadinfo['forumid'], 'canopenclose')) {
            $canpost = false;
        }
    }
    if (($vbulletin->userinfo['userid'] != $threadinfo['postuserid'] or !$vbulletin->userinfo['userid']) and (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewothers']) or !($forumperms & $vbulletin->bf_ugp_forumpermissions['canreplyothers']))) {
        $canpost = false;
    }
    if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canview']) or !($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']) or !($forumperms & $vbulletin->bf_ugp_forumpermissions['canreplyown']) and $vbulletin->userinfo['userid'] == $threadinfo['postuserid']) {
        $canpost = false;
    }
    $mod = 0;
    if (can_moderate($threadinfo['forumid'], 'candeleteposts') or can_moderate($threadinfo['forumid'], 'canremoveposts')) {
        $mod |= MOD_DELETEPOST;
    }
    if (can_moderate($threadinfo['forumid'], 'canmanagethreads')) {
        if ($threadinfo['sticky']) {
            $mod |= MOD_UNSTICK;
        } else {
            $mod |= MOD_STICK;
        }
    }
    if ($threadinfo['visible'] != 2 and can_moderate($threadinfo['forumid'], 'candeleteposts') or can_moderate($threadinfo['forumid'], 'canremoveposts') or $forumperms & $vbulletin->bf_ugp_forumpermissions['candeletepost'] and $forumperms & $vbulletin->bf_ugp_forumpermissions['candeletethread'] and $vbulletin->userinfo['userid'] == $threadinfo['postuserid'] and ($vbulletin->options['edittimelimit'] == 0 or $threadinfo['dateline'] > TIMENOW - $vbulletin->options['edittimelimit'] * 60)) {
        $mod |= MOD_DELETETHREAD;
    }
    if (can_moderate($threadinfo['forumid'], 'canopenclose') or $forumperms & $vbulletin->bf_ugp_forumpermissions['canopenclose'] and $threadinfo['postuserid'] == $vbulletin->userinfo['userid']) {
        if ($threadinfo['open']) {
            $mod |= MOD_CLOSE;
        } else {
            $mod |= MOD_OPEN;
        }
    }
    if (can_moderate($threadinfo['forumid'], 'canmanagethreads') or $forumperms & $vbulletin->bf_ugp_forumpermissions['canmove'] and $threadinfo['postuserid'] == $vbulletin->userinfo['userid']) {
        $mod |= MOD_MOVETHREAD;
    }
    if ($show['spamctrls']) {
        $mod |= MOD_SPAM_CONTROLS;
    }
    $out = array('posts' => $posts_out, 'total_posts' => $totalposts, 'page' => $vbulletin->GPC['pagenumber'], 'canpost' => $canpost ? 1 : 0, 'mod' => $mod, 'pollid' => $thread['pollid'], 'subscribed' => $threadinfo['issubscribed'] ? 1 : 0, 'title' => prepare_utf8_string($thread['title']), 'canattach' => $forumperms & $vbulletin->bf_ugp_forumpermissions['canpostattachment'] and $vbulletin->userinfo['userid']);
    if ($postid) {
        $out['gotopostid'] = $postid;
    }
    return $out;
}
Example #4
0
    $templater->register('threadedmode', $threadedmode);
    $templater->register('userjs', $userjs);
    $threadlist = $templater->render();
    unset($curpostbit, $post, $cacheposts, $parsed_postcache, $postbit);
}
################################################################################
########################## END LINEAR / THREADED ###############################
################################################################################
$effective_lastpost = max($displayed_dateline, $thread['lastpost']);
// *********************************************************************************
//set thread last view
if ($thread['pollid'] and $vbulletin->options['updatelastpost'] and ($displayed_dateline == $thread['lastpost'] or $threadview == $thread['lastpost']) and $pollinfo['lastvote'] > $thread['lastpost']) {
    $displayed_dateline = $pollinfo['lastvote'];
}
if ((!$vbulletin->GPC['posted'] or $updatethreadcookie) and $displayed_dateline and $displayed_dateline > $threadview) {
    mark_thread_read($threadinfo, $foruminfo, $vbulletin->userinfo['userid'], $displayed_dateline);
}
if ($db->explain) {
    $aftertime = microtime(true) - TIMESTART;
    echo "Time after parsing all posts:  {$aftertime}\n";
    if (function_exists('memory_get_usage')) {
        echo "Memory After: " . number_format(memory_get_usage() / 1024) . 'KB' . " \n";
    }
    echo "\n<hr />\n\n";
}
// *********************************************************************************
// save parsed post HTML
if (!empty($saveparsed)) {
    $db->shutdown_query("\n\t\tREPLACE INTO " . TABLE_PREFIX . "postparsed (postid, dateline, hasimages, pagetext_html, styleid, languageid)\n\t\tVALUES {$saveparsed}\n\t");
    unset($saveparsed);
}
Example #5
0
function get_article_comments($article, $associated_thread_id, $userinfo, &$pageno, &$perpage, &$total)
{
    require_once DIR . '/includes/functions_misc.php';
    require_once DIR . '/includes/functions.php';
    require_once DIR . '/includes/functions_databuild.php';
    require_once DIR . '/includes/functions_bigthree.php';
    $posts_out = array();
    fetch_phrase_group('posting');
    $threadinfo = verify_id('thread', $associated_thread_id, 0, 1);
    $foruminfo = verify_id('forum', $threadinfo['forumid'], 0, 1);
    //First let's see if we have forum/thread view permissions. If not,
    // we're done
    if (!($permissions = can_view_thread($article->getNodeId(), $userinfo))) {
        return array();
    }
    $forumperms = fetch_permissions($threadinfo['forumid']);
    //Normally this thread will be wide open, so let's get the list first
    // without checking. We'll verify each post anyway.
    //get our results
    $results = get_comments($permissions, $associated_thread_id);
    $record_count = count($results);
    if (!$results or !count($results)) {
        return array();
    }
    //we accept the parameter "last" for pageno.
    if ($pageno == FR_LAST_POST) {
        $pageno = intval(($record_count + $perpage - 1) / $perpage);
        $first = ($pageno - 1) * $perpage;
    } else {
        $pageno = max(1, intval($pageno));
        $first = $perpage * ($pageno - 1);
    }
    //Let's trim off the results we need.
    //This also tells us if we should show the "next" button.
    $post_array = array_slice($results, $first, $perpage, true);
    if (!$post_array) {
        return array();
    }
    $firstpostid = false;
    $displayed_dateline = 0;
    if (vB::$vbulletin->options['threadmarking'] and vB::$vbulletin->userinfo['userid']) {
        $threadview = max($threadinfo['threadread'], $threadinfo['forumread'], TIMENOW - vB::$vbulletin->options['markinglimit'] * 86400);
    } else {
        $threadview = intval(fetch_bbarray_cookie('thread_lastview', $thread['threadid']));
        if (!$threadview) {
            $threadview = vB::$vbulletin->userinfo['lastvisit'];
        }
    }
    require_once DIR . '/includes/functions_user.php';
    $show['inlinemod'] = false;
    $postids = array();
    $postids = ' post.postid in (' . implode(', ', $post_array) . ')';
    $posts = vB::$vbulletin->db->query_read($sql = "\n\tSELECT\n\tpost.*, post.username AS postusername, post.ipaddress AS ip, IF(post.visible = 2, 1, 0) AS isdeleted,\n\t    user.*, userfield.*, usertextfield.*,\n\t    " . iif($forum['allowicons'], 'icon.title as icontitle, icon.iconpath,') . "\n\t    " . iif(vB::$vbulletin->options['avatarenabled'], 'avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustomavatar, customavatar.dateline AS avatardateline,customavatar.width AS avwidth,customavatar.height AS avheight,') . "\n\t    " . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? 'spamlog.postid AS spamlog_postid,' : '') . "\n\t    " . iif($deljoin, 'deletionlog.userid AS del_userid, deletionlog.username AS del_username, deletionlog.reason AS del_reason,') . "\n\t    editlog.userid AS edit_userid, editlog.username AS edit_username, editlog.dateline AS edit_dateline,\n\t    editlog.reason AS edit_reason, editlog.hashistory,\n\t    postparsed.pagetext_html, postparsed.hasimages,\n\t    sigparsed.signatureparsed, sigparsed.hasimages AS sighasimages,\n\t    sigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline, sigpic.width AS sigpicwidth, sigpic.height AS sigpicheight,\n\t    IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid,\n\t    customprofilepic.userid AS profilepic, customprofilepic.dateline AS profilepicdateline, customprofilepic.width AS ppwidth, customprofilepic.height AS ppheight\n\t    " . iif(!($permissions['genericpermissions'] & vB::$vbulletin->bf_ugp_genericpermissions['canseehiddencustomfields']), vB::$vbulletin->profilefield['hidden']) . "\n\t    {$hook_query_fields}\n\t    FROM " . TABLE_PREFIX . "post AS post\n\t    LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = post.userid)\n\t    LEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON(userfield.userid = user.userid)\n\t    LEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON(usertextfield.userid = user.userid)\n\t    " . iif($forum['allowicons'], "LEFT JOIN " . TABLE_PREFIX . "icon AS icon ON(icon.iconid = post.iconid)") . "\n\t    " . iif(vB::$vbulletin->options['avatarenabled'], "LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON(avatar.avatarid = user.avatarid) LEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON(customavatar.userid = user.userid)") . "\n\t    " . ((can_moderate($thread['forumid'], 'canmoderateposts') or can_moderate($thread['forumid'], 'candeleteposts')) ? "LEFT JOIN " . TABLE_PREFIX . "spamlog AS spamlog ON(spamlog.postid = post.postid)" : '') . "\n\t    {$deljoin}\n\t    LEFT JOIN " . TABLE_PREFIX . "editlog AS editlog ON(editlog.postid = post.postid)\n\t    LEFT JOIN " . TABLE_PREFIX . "postparsed AS postparsed ON(postparsed.postid = post.postid AND postparsed.styleid = " . intval(STYLEID) . " AND postparsed.languageid = " . intval(LANGUAGEID) . ")\n\t    LEFT JOIN " . TABLE_PREFIX . "sigparsed AS sigparsed ON(sigparsed.userid = user.userid AND sigparsed.styleid = " . intval(STYLEID) . " AND sigparsed.languageid = " . intval(LANGUAGEID) . ")\n\t    LEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON(sigpic.userid = post.userid)\n\t    LEFT JOIN " . TABLE_PREFIX . "customprofilepic AS customprofilepic ON (user.userid = customprofilepic.userid)\n\t    {$hook_query_joins}\n\t    WHERE {$postids}\n\t    ORDER BY post.dateline\n\t    ");
    if (!($forumperms & vB::$vbulletin->bf_ugp_forumpermissions['canseethumbnails']) and !($forumperms & vB::$vbulletin->bf_ugp_forumpermissions['cangetattachment'])) {
        vB::$vbulletin->options['attachthumbs'] = 0;
    }
    if (!($forumperms & vB::$vbulletin->bf_ugp_forumpermissions['cangetattachment'])) {
        vB::$vbulletin->options['viewattachedimages'] = 0;
    }
    $postcount = count($postid_array);
    $counter = 0;
    $postbits = '';
    vB::$vbulletin->noheader = true;
    while ($post = vB::$vbulletin->db->fetch_array($posts)) {
        if (!$privileges['can_moderate_forums']) {
            if ($privileges['is_coventry'] or $post['visible'] == 2) {
                continue;
            }
        }
        // post/thread is deleted by moderator and we don't have permission to see it
        if (!($post['visible'] or $privileges['can_moderate_posts'])) {
            continue;
        }
        if (!intval($post['userid'])) {
            $post['avatarid'] = false;
        } else {
            if (!$post['hascustomavatar']) {
                if ($post['profilepic']) {
                    $post['hascustomavatar'] = 1;
                    $post['avatarid'] = true;
                    $post['avatarpath'] = "./image.php?u=" . $post['userid'] . "&amp;dateline=" . $post['profilepicdateline'] . "&amp;type=profile";
                    $post['avwidth'] = $post['ppwidth'];
                    $post['avheight'] = $post['ppheight'];
                } else {
                    $post['hascustomavatar'] = 1;
                    $post['avatarid'] = true;
                    // explicity setting avatarurl to allow guests comments to show unknown avatar
                    $post['avatarurl'] = $post['avatarpath'] = vB_Template_Runtime::fetchStyleVar('imgdir_misc') . '/unknown.gif';
                    $post['avwidth'] = 60;
                    $post['avheight'] = 60;
                }
            }
        }
        if ($tachyuser = in_coventry($post['userid']) and !can_moderate($thread['forumid'])) {
            continue;
        }
        if ($post['visible'] == 1 and !$tachyuser) {
            ++$counter;
            if ($postorder) {
                $post['postcount'] = --$postcount;
            } else {
                $post['postcount'] = ++$postcount;
            }
        }
        if ($tachyuser) {
            $fetchtype = 'post_global_ignore';
        } else {
            if ($ignore["{$post['userid']}"]) {
                $fetchtype = 'post_ignore';
            } else {
                if ($post['visible'] == 2) {
                    $fetchtype = 'post_deleted';
                } else {
                    $fetchtype = 'post';
                }
            }
        }
        if (vB::$vbulletin->GPC['viewfull'] and $post['postid'] == $postinfo['postid'] and $fetchtype != 'post' and (can_moderate($threadinfo['forumid']) or !$post['isdeleted'])) {
            $fetchtype = 'post';
        }
        if (!$firstpostid) {
            $firstpostid = $post['postid'];
        }
        $post['islastshown'] = $post['postid'] == $lastpostid;
        $post['isfirstshown'] = ($counter == 1 and $fetchtype == 'post' and $post['visible'] == 1);
        $post['islastshown'] = $post['postid'] == $lastpostid;
        $post['attachments'] = $postattach["{$post['postid']}"];
        $canedit = false;
        if (!$threadinfo['isdeleted'] and !$post['isdeleted'] and (can_moderate($threadinfo['forumid'], 'caneditposts') or $threadinfo['open'] and $post['userid'] == vB::$vbulletin->userinfo['userid'] and $forumperms & vB::$vbulletin->bf_ugp_forumpermissions['caneditpost'] and ($post['dateline'] >= TIMENOW - vB::$vbulletin->options['edittimelimit'] * 60 or vB::$vbulletin->options['edittimelimit'] == 0))) {
            $canedit = true;
        }
        // Get post date/time
        $postdate = vbdate(vB::$vbulletin->options['dateformat'], $post['dateline'], 1);
        $posttime = vbdate(vB::$vbulletin->options['timeformat'], $post['dateline']);
        $attachments = array();
        $fr_images = array();
        // Attachments (images).
        if (count($post['attachments']) > 0) {
            foreach ($post['attachments'] as $attachment) {
                $lfilename = strtolower($attachment['filename']);
                if (strpos($lfilename, '.jpe') !== false || strpos($lfilename, '.png') !== false || strpos($lfilename, '.gif') !== false || strpos($lfilename, '.jpg') !== false || strpos($lfilename, '.jpeg') !== false) {
                    $fr_images[] = array('img' => vB::$vbulletin->options['bburl'] . '/attachment.php?attachmentid=' . $attachment['attachmentid'], 'tmb' => vB::$vbulletin->options['bburl'] . '/attachment.php?attachmentid=' . $attachment['attachmentid'] . '&stc=1&thumb=1');
                }
            }
        }
        // Parse the post for quotes and inline images
        list($text, $nuked_quotes, $images) = parse_post($post['pagetext'], false);
        if (count($fr_images) > 0) {
            $text .= "<br/>";
            foreach ($fr_images as $attachment) {
                $text .= "<img src=\"{$attachment['img']}\"/>";
            }
        }
        foreach ($images as $image) {
            $fr_images[] = array('img' => $image);
        }
        $avatarurl = '';
        // Avatar work
        if (vB::$vbulletin->options['avatarenabled']) {
            require_once DIR . '/includes/functions_user.php';
            $userinfo = fetch_userinfo($post['userid'], FETCH_USERINFO_AVATAR);
            fetch_avatar_from_userinfo($userinfo);
            if ($userinfo['avatarurl']) {
                $avatarurl = process_avatarurl($userinfo['avatarurl']);
            }
        }
        $tmp = array('post_id' => $post['postid'], 'thread_id' => $post['threadid'], 'forum_id' => $foruminfo['forumid'], 'username' => prepare_utf8_string(strip_tags($post['username'])), 'joindate' => prepare_utf8_string($post['joindate']), 'usertitle' => prepare_utf8_string(strip_tags($post['usertitle'])), 'numposts' => $post['posts'], 'userid' => $post['userid'], 'title' => prepare_utf8_string($post['title']), 'post_timestamp' => prepare_utf8_string(date_trunc($postdate) . ' ' . $posttime), 'fr_images' => $fr_images, 'image_thumbs' => array());
        // Soft Deleted
        if ($post['visible'] == 2) {
            $tmp['deleted'] = true;
            $tmp['del_username'] = prepare_utf8_string($post['del_username']);
            if ($post['del_reason']) {
                $tmp['del_reason'] = prepare_utf8_string($post['del_reason']);
            }
        } else {
            $tmp['text'] = $text;
            $tmp['quotable'] = $nuked_quotes;
            if ($canedit) {
                $tmp['canedit'] = true;
                $tmp['edittext'] = prepare_utf8_string($post['pagetext']);
            }
        }
        if ($avatarurl != '') {
            $tmp['avatarurl'] = $avatarurl;
        }
        $posts_out[] = $tmp;
    }
    if ($LASTPOST['dateline'] > $displayed_dateline) {
        $displayed_dateline = $LASTPOST['dateline'];
        if ($displayed_dateline <= $threadview) {
            $updatethreadcookie = true;
        }
    }
    // Set thread last view
    if ($displayed_dateline and $displayed_dateline > $threadview) {
        mark_thread_read($threadinfo, $foruminfo, vB::$vbulletin->userinfo['userid'], $displayed_dateline);
    }
    vB::$vbulletin->db->free_result($posts);
    unset($post);
    $total = $record_count;
    return $posts_out;
}
Example #6
0
	private static function renderResult($userinfo, $post_array, $permissions,
		$forumperms, $target_url, $nodeid)
	{

		if (!count($post_array))
		{
			return '';
		}
		require_once DIR . '/includes/functions_bigthree.php' ;
		require_once DIR . '/includes/class_postbit.php' ;

		fetch_phrase_group('showthread');
		fetch_phrase_group('postbit');

		global $vbphrase;
		global $template_hook;
		global $show;
		global $thread;
		$thread = $thread->get_record();
		$threadinfo = verify_id('thread', $thread['threadid'], 1, 1);
		$foruminfo = verify_id('forum', $threadinfo['forumid'], 1, 1);
		$firstpostid = false;

		$displayed_dateline = 0;
		if (vB::$vbulletin->options['threadmarking'] AND vB::$vbulletin->userinfo['userid'])
		{
			$threadview = max($threadinfo['threadread'], $threadinfo['forumread'], TIMENOW - (vB::$vbulletin->options['markinglimit'] * 86400));
		}
		else
		{
			$threadview = intval(fetch_bbarray_cookie('thread_lastview', $thread['threadid']));
			if (!$threadview)
			{
				$threadview = vB::$vbulletin->userinfo['lastvisit'];
			}
		}
		require_once DIR . '/includes/functions_user.php';
		$show['inlinemod'] = false;
		$postids = array();

		if (! isset(vB::$vbulletin->userinfo['permissions']['cms']))
		{
			vBCMS_Permissions::getUserPerms();
		}



		$postids = ' post.postid in ('
 			. implode(', ', $post_array) .')';


		$posts =  vB::$vbulletin->db->query_read($sql = "
			SELECT
			post.*, post.username AS postusername, post.ipaddress AS ip, IF(post.visible = 2, 1, 0) AS isdeleted,
			user.*, userfield.*, usertextfield.*,
			" . iif($forum['allowicons'], 'icon.title as icontitle, icon.iconpath,') . "
			" . iif( vB::$vbulletin->options['avatarenabled'], 'avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustomavatar, customavatar.dateline AS avatardateline,customavatar.width AS avwidth,customavatar.height AS avheight,') . "
			" . ((can_moderate($thread['forumid'], 'canmoderateposts') OR can_moderate($thread['forumid'], 'candeleteposts')) ? 'spamlog.postid AS spamlog_postid,' : '') . "
				" . iif($deljoin, 'deletionlog.userid AS del_userid, deletionlog.username AS del_username, deletionlog.reason AS del_reason,') . "
				editlog.userid AS edit_userid, editlog.username AS edit_username, editlog.dateline AS edit_dateline,
				editlog.reason AS edit_reason, editlog.hashistory,
				postparsed.pagetext_html, postparsed.hasimages,
				sigparsed.signatureparsed, sigparsed.hasimages AS sighasimages,
				sigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline, sigpic.width AS sigpicwidth, sigpic.height AS sigpicheight,
				IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid,
			 	customprofilepic.userid AS profilepic, customprofilepic.dateline AS profilepicdateline, customprofilepic.width AS ppwidth, customprofilepic.height AS ppheight
				" . iif(!($permissions['genericpermissions'] &  vB::$vbulletin->bf_ugp_genericpermissions['canseehiddencustomfields']),  vB::$vbulletin->profilefield['hidden']) . "
				$hook_query_fields
			FROM " . TABLE_PREFIX . "post AS post
			LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = post.userid)
			LEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON(userfield.userid = user.userid)
			LEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON(usertextfield.userid = user.userid)
			" . iif($forum['allowicons'], "LEFT JOIN " . TABLE_PREFIX . "icon AS icon ON(icon.iconid = post.iconid)") . "
			" . iif( vB::$vbulletin->options['avatarenabled'], "LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON(avatar.avatarid = user.avatarid) LEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON(customavatar.userid = user.userid)") . "
			" . ((can_moderate($thread['forumid'], 'canmoderateposts') OR can_moderate($thread['forumid'], 'candeleteposts')) ? "LEFT JOIN " . TABLE_PREFIX . "spamlog AS spamlog ON(spamlog.postid = post.postid)" : '') . "
				$deljoin
			LEFT JOIN " . TABLE_PREFIX . "editlog AS editlog ON(editlog.postid = post.postid)
			LEFT JOIN " . TABLE_PREFIX . "postparsed AS postparsed ON(postparsed.postid = post.postid AND postparsed.styleid = " . intval(STYLEID) . " AND postparsed.languageid = " . intval(LANGUAGEID) . ")
			LEFT JOIN " . TABLE_PREFIX . "sigparsed AS sigparsed ON(sigparsed.userid = user.userid AND sigparsed.styleid = " . intval(STYLEID) . " AND sigparsed.languageid = " . intval(LANGUAGEID) . ")
			LEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON(sigpic.userid = post.userid)
			LEFT JOIN " . TABLE_PREFIX . "customprofilepic AS customprofilepic ON (user.userid = customprofilepic.userid)
				$hook_query_joins
			WHERE $postids
			ORDER BY post.dateline
		");

		if (!($forumperms &  vB::$vbulletin->bf_ugp_forumpermissions['canseethumbnails']) AND !($forumperms &  vB::$vbulletin->bf_ugp_forumpermissions['cangetattachment']))
		{
			 vB::$vbulletin->options['attachthumbs'] = 0;
		}

		if (!($forumperms &  vB::$vbulletin->bf_ugp_forumpermissions['cangetattachment']))
		{
			 vB::$vbulletin->options['viewattachedimages'] = 0;
		}

		$postcount = count($postid_array);

		$counter = 0;
		$postbits = '';
		 vB::$vbulletin->noheader = true;
		$postbit_factory = new vB_Postbit_Factory();
		$postbit_factory->registry =  vB::$vbulletin;
		$postbit_factory->forum = $foruminfo;
		$postbit_factory->thread = $thread;
		$postbit_factory->cache = array();
		$postbit_factory->bbcode_parser = new vB_BbCodeParser( vB::$vbulletin, fetch_tag_list());
		//We need to tell the parser to handle quotes differently.
		$postbit_factory->bbcode_parser->set_quote_template('vbcms_bbcode_quote');
		$postbit_factory->bbcode_parser->set_quote_vars(array('page_url' => $target_url .
			(strpos($target_url, '?') == false ? '?' : '&')));
		$show['return_node'] = $nodeid;
		$show['avatar'] = 1;

		while ($post =  vB::$vbulletin->db->fetch_array($posts))
		{
			if (! self::canViewPost($post, $permissions) )
			{
				continue;
			}

			if (! intval($post['userid']))
			{
				$post['avatarid'] = false;
			}
			else if (!$post['hascustomavatar'])
			{
				if ($post['profilepic'])
				{
					$post['hascustomavatar'] = 1;
					$post['avatarid'] = true;
					$post['avatarpath'] = "./image.php?u=" . $post['userid']  . "&amp;dateline=" . $post['profilepicdateline'] . "&amp;type=profile";
					$post['avwidth'] = $post['ppwidth'];
					$post['avheight'] = $post['ppheight'];
				}
				else
				{
					$post['hascustomavatar'] = 1;
					$post['avatarid'] = true;
					// explicity setting avatarurl to allow guests comments to show unknown avatar
					$post['avatarurl'] = $post['avatarpath'] = vB_Template_Runtime::fetchStyleVar('imgdir_misc') . '/unknown.gif';
					$post['avwidth'] = 60;
					$post['avheight'] = 60;
				}
			}

			if ($tachyuser = in_coventry($post['userid']) AND !can_moderate($thread['forumid']))
			{
				continue;
			}

			if ($post['visible'] == 1 AND !$tachyuser)
			{
				++$counter;
				if ($postorder)
				{
					$post['postcount'] = --$postcount;
				}
				else
				{
					$post['postcount'] = ++$postcount;
				}
			}

			if ($tachyuser)
			{
				$fetchtype = 'post_global_ignore';
			}
			else if ($ignore["$post[userid]"])
			{
				$fetchtype = 'post_ignore';
			}
			else if ($post['visible'] == 2)
			{
				$fetchtype = 'post_deleted';
			}
			else
			{
				$fetchtype = 'post';
			}

			if (
				( vB::$vbulletin->GPC['viewfull'] AND $post['postid'] == $postinfo['postid'] AND $fetchtype != 'post')
				AND
				(can_moderate($threadinfo['forumid']) OR !$post['isdeleted'])
				)
			{
				$fetchtype = 'post';
			}

			($hook = vBulletinHook::fetch_hook('showthread_postbit_create')) ? eval($hook) : false;

			$postbit_obj = $postbit_factory->fetch_postbit($fetchtype);
			$postbit_obj->set_template_prefix('vbcms_');

			if ($fetchtype == 'post')
			{
				$postbit_obj->highlight = $replacewords;
			}

			if (!$firstpostid)
			{
				$firstpostid = $post['postid'];
			}

			$post['islastshown'] = ($post['postid'] == $lastpostid);
			$post['isfirstshown'] = ($counter == 1 AND $fetchtype == 'post' AND $post['visible'] == 1);
			$post['islastshown'] = ($post['postid'] == $lastpostid);
			$post['attachments'] = $postattach["$post[postid]"];

			$parsed_postcache = array('text' => '', 'images' => 1, 'skip' => false);


			$this_postbit = $postbit_obj->construct_postbit($post);

			$this_template = vB_Template::create('vbcms_comments_detail');
			$this_template->register('postid', $post['postid'] );
			$this_template->register('postbit', $this_postbit);
			$this_template->register('indent', $post_array[$this_key]['level'] * $pixel_indent);

			$postbits .= $this_template->render();
			$LASTPOST = $post;

			// Only show after the first post, counter isn't incremented for deleted/moderated posts

			if ($post_cachable AND $post['pagetext_html'] == '')
			{
				if (!empty($saveparsed))
				{
					$saveparsed .= ',';
				}
				$saveparsed .= "($post[postid], " . intval($thread['lastpost']) . ', ' . intval($postbit_obj->post_cache['has_images']) . ", '" . vB::$vbulletin->db->escape_string($postbit_obj->post_cache['text']) . "', " . intval(STYLEID) . ", " . intval(LANGUAGEID) . ")";
			}

			if (!empty($postbit_obj->sig_cache) AND $post['userid'])
			{
				if (!empty($save_parsed_sigs))
				{
					$save_parsed_sigs .= ',';
				}
				$save_parsed_sigs .= "($post[userid], " . intval(STYLEID) . ", " . intval(LANGUAGEID) . ", '" . vB::$vbulletin->db->escape_string($postbit_obj->sig_cache['text']) . "', " . intval($postbit_obj->sig_cache['has_images']) . ")";
			}
		}


		if ($LASTPOST['dateline'] > $displayed_dateline)
		{
			$displayed_dateline = $LASTPOST['dateline'];
			if ($displayed_dateline <= $threadview)
			{
				$updatethreadcookie = true;
			}
		}

		if ($firstpostid)
		{
			$this_template->register('FIRSTPOSTID', $firstpostid );
		}

		if ($lastpostid)
		{
			$this_template->register('LASTPOSTID', $lastpostid);
		}
		// Set thread last view
		if ($displayed_dateline AND $displayed_dateline > $threadview)
		{
			mark_thread_read($threadinfo, $foruminfo, vB::$vbulletin->userinfo['userid'], $displayed_dateline);
		}

		vB::$vbulletin->db->free_result($posts);
		unset($post);
		return $postbits;
	}
Example #7
0
     }
     // ### PREVIEW POST ###
     $postpreview = process_post_preview($newpost, 0, $postattach);
     $_REQUEST['do'] = 'newthread';
     $newpost['message'] = htmlspecialchars_uni($newpost['message']);
     $podcasturl = htmlspecialchars_uni($newpost['podcasturl']);
     $podcastsize = $newpost['podcastsize'] ? $newpost['podcastsize'] : '';
     $podcastkeywords = htmlspecialchars_uni($newpost['podcastkeywords']);
     $podcastsubtitle = htmlspecialchars_uni($newpost['podcastsubtitle']);
     $podcastauthor = htmlspecialchars_uni($newpost['podcastauthor']);
     $explicitchecked = $newpost['podcastexplicit'] ? 'checked="checked"' : '';
 } else {
     // ### NOT PREVIEW - ACTUAL POST ###
     $threadinfo = fetch_threadinfo($newpost['threadid']);
     // need the forumread variable from this
     mark_thread_read($threadinfo, $foruminfo, $vbulletin->userinfo['userid'], TIMENOW);
     ($hook = vBulletinHook::fetch_hook('newthread_post_complete')) ? eval($hook) : false;
     if ($newpost['postpoll']) {
         $vbulletin->url = 'poll.php?' . $vbulletin->session->vars['sessionurl'] . "t={$newpost['threadid']}&polloptions={$newpost['polloptions']}";
         if ($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']) {
             eval(print_standard_redirect('redirect_postthanks', true, true));
         } else {
             eval(print_standard_redirect('redirect_postthanks_nopermission', true, true));
         }
     } else {
         if ($newpost['visible']) {
             if ($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']) {
                 $vbulletin->url = fetch_seo_url('thread', $threadinfo, array('p' => $newpost['postid'] . "#post{$newpost['postid']}"));
                 eval(print_standard_redirect('redirect_postthanks'));
             } else {
                 $vbulletin->url = fetch_seo_url('forum', $foruminfo);
Example #8
0
function get_thread_func($xmlrpc_params)
{
    global $db, $lang, $mybb, $position, $plugins, $pids;
    global $pforumcache, $currentitem, $forum_cache, $navbits, $base_url, $archiveurl;
    $input = Tapatalk_Input::filterXmlInput(array('topic_id' => Tapatalk_Input::STRING, 'start_num' => Tapatalk_Input::INT, 'last_num' => Tapatalk_Input::INT, 'return_html' => Tapatalk_Input::INT), $xmlrpc_params);
    if (preg_match('/^ann_/', $input['topic_id'])) {
        $_GET["aid"] = intval(str_replace('ann_', '', $input['topic_id']));
        return get_announcement_func($xmlrpc_params);
    }
    $lang->load("showthread");
    global $parser;
    $parser = new Tapatalk_Parser();
    // Get the thread details from the database.
    $thread = get_thread($input['topic_id']);
    if (!empty($thread['closed'])) {
        $moved = explode("|", $thread['closed']);
        if ($moved[0] == "moved") {
            $thread = get_thread($moved[1]);
        }
    }
    // Get thread prefix if there is one.
    $thread['threadprefix'] = '';
    $thread['displayprefix'] = '';
    if ($thread['prefix'] != 0) {
        $threadprefix = build_prefixes($thread['prefix']);
        if ($threadprefix['prefix']) {
            $thread['threadprefix'] = $threadprefix['prefix'] . '&nbsp;';
            $thread['displayprefix'] = $threadprefix['displaystyle'] . '&nbsp;';
        }
    }
    $thread['subject'] = $parser->parse_badwords($thread['subject']);
    $tid = $thread['tid'];
    $fid = $thread['fid'];
    if (!$thread['username']) {
        $thread['username'] = $lang->guest;
    }
    $visibleonly = "AND visible='1'";
    // Is the currently logged in user a moderator of this forum?
    if (is_moderator($fid)) {
        $visibleonly = " AND (visible='1' OR visible='0')";
        $ismod = true;
    } else {
        $ismod = false;
    }
    $forumpermissions = forum_permissions($thread['fid']);
    // Does the user have permission to view this thread?
    if ($forumpermissions['canview'] != 1 || $forumpermissions['canviewthreads'] != 1) {
        error_no_permission();
    }
    if ($forumpermissions['canonlyviewownthreads'] == 1 && $thread['uid'] != $mybb->user['uid']) {
        error_no_permission();
    }
    // Make sure we are looking at a real thread here.
    if (!$thread['tid'] || $thread['visible'] == 0 && $ismod == false || $thread['visible'] > 1 && $ismod == true) {
        return xmlrespfalse($lang->error_invalidthread);
    }
    // Does the thread belong to a valid forum?
    $forum = get_forum($fid);
    if (!$forum || $forum['type'] != "f") {
        return xmlrespfalse($lang->error_invalidforum);
    }
    tt_check_forum_password($forum['fid']);
    if ($thread['firstpost'] == 0) {
        update_first_post($tid);
    }
    // Mark this thread as read
    mark_thread_read($tid, $fid);
    // Increment the thread view.
    if ($mybb->settings['delayedthreadviews'] == 1) {
        $db->shutdown_query("INSERT INTO " . TABLE_PREFIX . "threadviews (tid) VALUES('{$tid}')");
    } else {
        $db->shutdown_query("UPDATE " . TABLE_PREFIX . "threads SET views=views+1 WHERE tid='{$tid}'");
    }
    ++$thread['views'];
    // Work out if we are showing unapproved posts as well (if the user is a moderator etc.)
    if ($ismod) {
        $visible = "AND (p.visible='0' OR p.visible='1')";
    } else {
        $visible = "AND p.visible='1'";
    }
    // Fetch the ignore list for the current user if they have one
    $ignored_users = array();
    if ($mybb->user['uid'] > 0 && $mybb->user['ignorelist'] != "") {
        $ignore_list = explode(',', $mybb->user['ignorelist']);
        foreach ($ignore_list as $uid) {
            $ignored_users[$uid] = 1;
        }
    }
    list($start, $limit) = process_page($input['start_num'], $input['last_num']);
    // Recount replies if user is a moderator to take into account unapproved posts.
    if ($ismod) {
        $query = $db->simple_select("posts p", "COUNT(*) AS replies", "p.tid='{$tid}' {$visible}");
        $thread['replies'] = $db->fetch_field($query, 'replies') - 1;
    }
    $postcount = intval($thread['replies']) + 1;
    $pids = "";
    $comma = '';
    $query = $db->simple_select("posts p", "p.pid", "p.tid='{$tid}' {$visible}", array('order_by' => 'p.dateline', 'limit_start' => $start, 'limit' => $limit));
    while ($getid = $db->fetch_array($query)) {
        // Set the ID of the first post on page to $pid if it doesn't hold any value
        // to allow this value to be used for Thread Mode/Linear Mode links
        // and ensure the user lands on the correct page after changing view mode
        if (!$pid) {
            $pid = $getid['pid'];
        }
        // Gather a comma separated list of post IDs
        $pids .= "{$comma}'{$getid['pid']}'";
        $comma = ",";
    }
    if ($pids) {
        $pids = "pid IN({$pids})";
        global $attachcache;
        $attachcache = array();
        if ($thread['attachmentcount'] > 0) {
            // Now lets fetch all of the attachments for these posts.
            $query = $db->simple_select("attachments", "*", $pids);
            while ($attachment = $db->fetch_array($query)) {
                $attachcache[$attachment['pid']][$attachment['aid']] = $attachment;
            }
        }
    } else {
        // If there are no pid's the thread is probably awaiting approval.
        return xmlrespfalse($lang->error_invalidthread);
    }
    $post_list = array();
    // Get the actual posts from the database here.
    $posts = '';
    $query = $db->query("\n        SELECT u.*, u.username AS userusername, p.*, f.*, eu.username AS editusername, IF(b.lifted > UNIX_TIMESTAMP() OR b.lifted = 0, 1, 0) as isbanned\n        FROM " . TABLE_PREFIX . "posts p\n        LEFT JOIN " . TABLE_PREFIX . "users u ON (u.uid=p.uid)\n        LEFT JOIN " . TABLE_PREFIX . "userfields f ON (f.ufid=u.uid)\n        LEFT JOIN " . TABLE_PREFIX . "users eu ON (eu.uid=p.edituid)\n        LEFT JOIN " . TABLE_PREFIX . "banned b ON (b.uid = p.uid)\n        WHERE {$pids}\n        ORDER BY p.dateline\n    ");
    //can_rename topic
    $can_rename = (is_moderator($fid, "caneditposts") || $forumpermissions['caneditposts'] == 1 && $mybb->user['uid'] == $thread['uid']) && $mybb->user['uid'] != 0;
    while ($post = $db->fetch_array($query)) {
        if ($thread['firstpost'] == $post['pid'] && $thread['visible'] == 0) {
            $post['visible'] = 0;
        }
        //$posts .= build_postbit($post);
        $parser_options = array();
        $parser_options['allow_html'] = false;
        $parser_options['allow_mycode'] = true;
        $parser_options['allow_smilies'] = false;
        $parser_options['allow_imgcode'] = true;
        $parser_options['allow_videocode'] = true;
        $parser_options['nl2br'] = (bool) $input['return_html'];
        $parser_options['filter_badwords'] = 1;
        if (!$post['username']) {
            $post['username'] = $lang->guest;
        }
        if ($post['userusername']) {
            $parser_options['me_username'] = $post['userusername'];
        } else {
            $parser_options['me_username'] = $post['username'];
        }
        $post['subject'] = $parser->parse_badwords($post['subject']);
        $post['author'] = $post['uid'];
        if ($post['userusername']) {
            // This post was made by a registered user
            $post['username'] = $post['userusername'];
        }
        // Eidt Option
        $can_edit = (is_moderator($fid, "caneditposts") || $forumpermissions['caneditposts'] == 1 && $mybb->user['uid'] == $post['uid']) && $mybb->user['uid'] != 0;
        // Quick Delete Option
        $can_delete = 0;
        if ($mybb->user['uid'] == $post['uid']) {
            if ($forumpermissions['candeletethreads'] == 1 && $postcounter == 1) {
                $can_delete = 1;
            } else {
                if ($forumpermissions['candeleteposts'] == 1 && $postcounter != 1) {
                    $can_delete = 1;
                }
            }
        }
        $can_delete = (is_moderator($fid, "candeleteposts") || $can_delete == 1) && $mybb->user['uid'] != 0;
        // User Online status
        $is_online = false;
        $timecut = TIME_NOW - $mybb->settings['wolcutoff'];
        if ($post['lastactive'] > $timecut && ($post['invisible'] != 1 || $mybb->usergroup['canviewwolinvis'] == 1) && $post['lastvisit'] != $post['lastactive']) {
            $is_online = true;
        }
        $post['message'] = post_bbcode_clean($post['message']);
        $plugins->remove_hook('parse_message', 'mybbirckeditor_parser');
        // Post content and attachments
        $post['message'] = $parser->parse_message($post['message'], $parser_options);
        $attachment_list = process_post_attachments($post['pid'], $post);
        // add for thank/like support
        $post = $plugins->run_hooks("postbit", $post);
        if (is_array($ignored_users) && $post['uid'] != 0 && $ignored_users[$post['uid']] == 1) {
            $show_spoiler = "[spoiler]" . $post['message'] . "[/spoiler]";
            $post['message'] = $lang->sprintf($lang->postbit_currently_ignoring_user, $post['username']) . $show_spoiler;
        }
        $post_xmlrpc = array('post_id' => new xmlrpcval($post['pid'], 'string'), 'post_title' => new xmlrpcval(basic_clean($post['subject']), 'base64'), 'post_content' => new xmlrpcval(process_post($post['message'], $input['return_html']), 'base64'), 'post_author_id' => new xmlrpcval($post['uid'], 'string'), 'post_author_name' => new xmlrpcval(basic_clean($post['username']), 'base64'), 'icon_url' => new xmlrpcval(absolute_url($post['avatar']), 'string'), 'post_time' => new xmlrpcval(mobiquo_iso8601_encode($post['dateline']), 'dateTime.iso8601'), 'timestamp' => new xmlrpcval($post['dateline'], 'string'), 'attachments' => new xmlrpcval($attachment_list, 'array'));
        if (!$post['visible']) {
            $post_xmlrpc['is_approved'] = new xmlrpcval(false, 'boolean');
        }
        // default as true
        if ($post['smilieoff']) {
            $post_xmlrpc['allow_smilies'] = new xmlrpcval(false, 'boolean');
        }
        // default as true
        if ($post['isbanned']) {
            $post_xmlrpc['is_ban'] = new xmlrpcval(true, 'boolean');
        }
        if ($is_online) {
            $post_xmlrpc['is_online'] = new xmlrpcval(true, 'boolean');
        }
        if ($can_edit) {
            $post_xmlrpc['can_edit'] = new xmlrpcval(true, 'boolean');
        }
        if ($can_delete) {
            $post_xmlrpc['can_delete'] = new xmlrpcval(true, 'boolean');
        }
        if (is_moderator($fid, 'canmanagethreads')) {
            $post_xmlrpc['can_approve'] = new xmlrpcval(true, 'boolean');
        }
        if (is_moderator($fid, 'canmanagethreads')) {
            $post_xmlrpc['can_move'] = new xmlrpcval(true, 'boolean');
        }
        if ($mybb->usergroup['canmodcp'] == 1) {
            $post_xmlrpc['can_ban'] = new xmlrpcval(true, 'boolean');
        }
        if ($post['edituid']) {
            //add edit info
            $edit_info = array('editor_id' => new xmlrpcval($post['edituid'], 'string'), 'editor_name' => new xmlrpcval($post['editusername'], 'base64'), 'edit_time' => new xmlrpcval($post['edittime'], 'string'));
            if (!empty($post['editreason'])) {
                $edit_info['edit_reason'] = new xmlrpcval($post['editreason'], 'base64');
            }
            $post_xmlrpc = array_merge($post_xmlrpc, $edit_info);
        }
        // add for thank/like support
        if (isset($post['button_tyl']) && $mybb->user['uid']) {
            global $mobiquo_config, $g33k_pcache;
            $thlprefix = $mobiquo_config['thlprefix'];
            $tyled = false;
            $tyl_list = array();
            if ($mybb->settings[$thlprefix . 'enabled'] == "1") {
                if ($post['thankyoulike'] && isset($g33k_pcache[$post['pid']])) {
                    foreach ($g33k_pcache[$post['pid']] as $tyl) {
                        if ($tyl['uid'] == $mybb->user['uid']) {
                            $tyled = true;
                        }
                        $tyl_list[] = new xmlrpcval(array('userid' => new xmlrpcval($tyl['uid'], 'string'), 'username' => new xmlrpcval(basic_clean($tyl['username']), 'base64')), 'struct');
                    }
                }
                if ($mybb->settings[$thlprefix . 'thankslike'] == "like") {
                    if ($post['button_tyl']) {
                        $post_xmlrpc['can_like'] = new xmlrpcval(true, 'boolean');
                    }
                    if ($tyled) {
                        $post_xmlrpc['is_liked'] = new xmlrpcval(true, 'boolean');
                    }
                    if ($tyl_list) {
                        $post_xmlrpc['likes_info'] = new xmlrpcval($tyl_list, 'array');
                    }
                } else {
                    if ($mybb->settings[$thlprefix . 'thankslike'] == "thanks") {
                        if ($post['button_tyl']) {
                            $post_xmlrpc['can_thank'] = new xmlrpcval(true, 'boolean');
                        }
                        if ($mybb->settings[$thlprefix . 'removing'] == 1) {
                            $post_xmlrpc['can_remove_thank'] = new xmlrpcval(true, 'boolean');
                        }
                        if ($tyled) {
                            $post_xmlrpc['is_thanked'] = new xmlrpcval(true, 'boolean');
                        }
                        if ($tyl_list) {
                            $post_xmlrpc['thanks_info'] = new xmlrpcval($tyl_list, 'array');
                        }
                    }
                }
            }
        }
        $post_list[] = new xmlrpcval($post_xmlrpc, 'struct');
    }
    $query = $db->simple_select("threadsubscriptions", "tid", "tid='" . intval($tid) . "' AND uid='" . intval($mybb->user['uid']) . "'", array('limit' => 1));
    $subscribed = (bool) $db->fetch_field($query, 'tid');
    $query = $db->simple_select("banned", "uid", "uid='{$thread['uid']}'");
    $isbanned = !!$db->fetch_field($query, "uid");
    $can_reply = $forumpermissions['canpostreplys'] != 0 && $mybb->user['suspendposting'] != 1 && ($thread['closed'] != 1 || is_moderator($fid)) && $forum['open'] != 0;
    build_tt_breadcrumb($fid);
    $navgation_arr = $navbits;
    if (is_array($navgation_arr) && count($navgation_arr) > 1) {
        unset($navgation_arr[0]);
        foreach ($navgation_arr as $navigation) {
            $forum_id = $navigation['fid'];
            $sub_only = false;
            if ($navigation['type'] != 'f') {
                $sub_only = true;
            }
            $breadcrumb[] = new xmlrpcval(array('forum_id' => new xmlrpcval($forum_id, 'string'), 'forum_name' => new xmlrpcval($navigation['name'], 'base64'), 'sub_only' => new xmlrpcval($sub_only, 'boolean')), 'struct');
        }
    }
    $is_poll = !empty($thread['poll']) ? true : false;
    $result = array('total_post_num' => new xmlrpcval($postcount, 'int'), 'forum_id' => new xmlrpcval($thread['fid'], 'string'), 'forum_name' => new xmlrpcval(basic_clean($forum['name']), 'base64'), 'topic_id' => new xmlrpcval($thread['tid'], 'string'), 'topic_title' => new xmlrpcval(basic_clean($thread['subject']), 'base64'), 'can_upload' => new xmlrpcval($forumpermissions['canpostattachments'] != 0, 'boolean'), 'can_report' => new xmlrpcval(true, 'boolean'), 'can_reply' => new xmlrpcval($can_reply, 'boolean'), 'is_poll' => new xmlrpcval($is_poll, 'boolean'), 'view_number' => new xmlrpcval(intval($thread['views']), 'int'));
    if ($forumpermissions['canview'] == 0 || $forumpermissions['canviewthreads'] == 0) {
        $new_topic['can_subscribe'] = new xmlrpcval(false, 'boolean');
    } else {
        $new_topic['can_subscribe'] = new xmlrpcval(true, 'boolean');
    }
    if ($thread['prefix']) {
        $result['prefix'] = new xmlrpcval(basic_clean($thread['displayprefix']), 'base64');
    }
    if (!$thread['visible']) {
        $result['is_approved'] = new xmlrpcval(false, 'boolean');
    }
    // default as true
    if ($thread['closed']) {
        $result['is_closed'] = new xmlrpcval(true, 'boolean');
    }
    if ($thread['sticky']) {
        $result['is_sticky'] = new xmlrpcval(true, 'boolean');
    }
    if ($subscribed) {
        $result['is_subscribed'] = new xmlrpcval(true, 'boolean');
    } else {
        $result['is_subscribed'] = new xmlrpcval(false, 'boolean');
    }
    if ($isbanned) {
        $result['is_ban'] = new xmlrpcval(true, 'boolean');
    }
    if ($position) {
        $result['position'] = new xmlrpcval(intval($position), 'int');
    }
    if (is_moderator($fid, "canopenclosethreads")) {
        $result['can_close'] = new xmlrpcval(true, 'boolean');
    }
    if (is_moderator($fid, "candeleteposts")) {
        $result['can_delete'] = new xmlrpcval(true, 'boolean');
    }
    if (is_moderator($fid, "canmanagethreads")) {
        $result['can_stick'] = new xmlrpcval(true, 'boolean');
    }
    if (is_moderator($fid, "canmanagethreads")) {
        $result['can_move'] = new xmlrpcval(true, 'boolean');
        $result['can_merge'] = new xmlrpcval(true, 'boolean');
        $result['can_merge_post'] = new xmlrpcval(true, 'boolean');
    }
    if (is_moderator($fid, "canopenclosethreads")) {
        $result['can_approve'] = new xmlrpcval(true, 'boolean');
    }
    if ($can_rename) {
        $result['can_rename'] = new xmlrpcval(true, 'boolean');
    }
    if ($mybb->usergroup['canmodcp'] == 1) {
        $result['can_ban'] = new xmlrpcval(true, 'boolean');
    }
    if (!empty($breadcrumb)) {
        $result['breadcrumb'] = new xmlrpcval($breadcrumb, 'array');
    }
    $result['posts'] = new xmlrpcval($post_list, 'array');
    return new xmlrpcresp(new xmlrpcval($result, 'struct'));
}
 /**
  * Insert plugin read data for new reply / new thread action.
  *      
  */
 public function newThreadOrReplyMark()
 {
     global $fid, $tid;
     if (isset($fid) && isset($tid)) {
         $this->readTime = TIME_NOW;
         mark_thread_read($tid, $fid, TIME_NOW);
         $this->already_marked = true;
     }
 }
Example #10
0
$msg = fetch_message($user, $mid);
$iid = mid_to_iid($mid);
$sql = "update f_messages{$iid}  set views = views + 1 where mid = ?";
db_exec($sql, array($mid));
if (!empty($msg['flags'])) {
    $flagexp = explode(",", $msg['flags']);
    while (list(, $flag) = each($flagexp)) {
        $flags[$flag] = true;
    }
}
$uuser = new ForumUser($msg['aid']);
/* Grab some information about the parent (if there is one) */
if ($msg['pmid'] != 0) {
    $pmsg = fetch_message($user, $msg['pmid'], 'mid,subject,name');
}
mark_thread_read($forum['fid'], $msg, $user);
/* generate message subjects in the thread this message is a part of */
$thread = get_thread($msg['tid']);
/* UGLY hack, kludge, etc to workaround nasty ordering problem */
$_page = $tpl->get_var("PAGE");
unset($tpl->varkeys["PAGE"]);
unset($tpl->varvals["PAGE"]);
$tpl->set_var("PAGE", $_page);
$_domain = $tpl->get_var("DOMAIN");
unset($tpl->varkeys["DOMAIN"]);
unset($tpl->varvals["DOMAIN"]);
$tpl->set_var("DOMAIN", $_domain);
if (isset($pmsg)) {
    $tpl->set_var(array("PMSG_MID" => $pmsg['mid'], "PMSG_SUBJECT" => $pmsg['subject'], "PMSG_NAME" => $pmsg['name'], "PMSG_DATE" => $pmsg['date']));
} else {
    $tpl->set_var("parent", "");
Example #11
0
function new_topic_func($xmlrpc_params)
{
    global $db, $lang, $theme, $plugins, $mybb, $session, $settings, $cache, $time, $mybbgroups, $thread_info, $pid, $tid, $visible, $fid, $new_thread;
    $lang->load("newthread");
    $input = Tapatalk_Input::filterXmlInput(array('forum_id' => Tapatalk_Input::INT, 'subject' => Tapatalk_Input::STRING, 'message' => Tapatalk_Input::STRING, 'prefix_id' => Tapatalk_Input::STRING, 'attachment_id_array' => Tapatalk_Input::RAW, 'group_id' => Tapatalk_Input::STRING), $xmlrpc_params);
    $fid = $input['forum_id'];
    // Fetch forum information.
    $forum = get_forum($fid);
    if (!$forum) {
        return xmlrespfalse($lang->error_invalidforum);
    }
    $forumpermissions = forum_permissions($fid);
    if ($forum['open'] == 0 || $forum['type'] != "f") {
        return xmlrespfalse($lang->error_closedinvalidforum);
    }
    if ($mybb->user['uid'] < 1 || $forumpermissions['canview'] == 0 || $forumpermissions['canpostthreads'] == 0 || $mybb->user['suspendposting'] == 1) {
        return tt_no_permission();
    }
    // Check if this forum is password protected and we have a valid password
    tt_check_forum_password($forum['fid']);
    // Check the maximum posts per day for this user
    if ($mybb->settings['maxposts'] > 0 && $mybb->usergroup['cancp'] != 1) {
        $daycut = TIME_NOW - 60 * 60 * 24;
        $query = $db->simple_select("posts", "COUNT(*) AS posts_today", "uid='{$mybb->user['uid']}' AND visible='1' AND dateline>{$daycut}");
        $post_count = $db->fetch_field($query, "posts_today");
        if ($post_count >= $mybb->settings['maxposts']) {
            $lang->error_maxposts = $lang->sprintf($lang->error_maxposts, $mybb->settings['maxposts']);
            return xmlrespfalse($lang->error_maxposts);
        }
    }
    $username = $mybb->user['username'];
    $uid = $mybb->user['uid'];
    // Attempt to see if this post is a duplicate or not
    if ($uid > 0) {
        $user_check = "p.uid='{$uid}'";
    } else {
        $user_check = "p.ipaddress='" . $db->escape_string($session->ipaddress) . "'";
    }
    if (!$mybb->input['savedraft'] && !$pid) {
        $query = $db->simple_select("posts p", "p.pid", "{$user_check} AND p.fid='{$forum['fid']}' AND p.subject='{$input['subject_esc']}' AND p.message='{$input['message_esc']}'");
        $duplicate_check = $db->fetch_field($query, "pid");
        if ($duplicate_check) {
            return xmlrespfalse($lang->error_post_already_submitted);
        }
    }
    // Set up posthandler.
    require_once MYBB_ROOT . "inc/datahandlers/post.php";
    $posthandler = new PostDataHandler("insert");
    $posthandler->action = "thread";
    // Set the thread data that came from the input to the $thread array.
    $new_thread = array("fid" => $forum['fid'], "subject" => $input['subject'], "prefix" => $input['prefix_id'], "icon" => 0, "uid" => $uid, "username" => $username, "message" => $input['message'], "ipaddress" => get_ip(), "posthash" => $input['group_id_esc']);
    $new_thread['savedraft'] = 0;
    // Set up the thread options from the input.
    $new_thread['options'] = array("signature" => 1, "subscriptionmethod" => $mybb->user['subscriptionmethod'] == 0 ? '' : $mybb->user['subscriptionmethod'], "disablesmilies" => 0);
    $posthandler->set_data($new_thread);
    // Now let the post handler do all the hard work.
    $valid_thread = $posthandler->validate_thread();
    $post_errors = array();
    // Fetch friendly error messages if this is an invalid thread
    if (!$valid_thread) {
        $post_errors = $posthandler->get_friendly_errors();
        return xmlrespfalse(implode(" :: ", $post_errors));
    }
    $thread_info = $posthandler->insert_thread();
    $tid = $thread_info['tid'];
    $pid = $thread_info['pid'];
    $visible = $thread_info['visible'];
    if ($pid != '') {
        if (!empty($input['group_id_esc'])) {
            $db->update_query("attachments", array("pid" => intval($pid)), "posthash='{$input['group_id_esc']}'");
        }
    }
    tapatalk_push_newtopic();
    tapatalk_push_quote();
    tapatalk_push_tag();
    // Mark thread as read
    require_once MYBB_ROOT . "inc/functions_indicators.php";
    mark_thread_read($tid, $fid);
    $result = new xmlrpcval(array('result' => new xmlrpcval(true, 'boolean'), 'result_text' => new xmlrpcval('', 'base64'), 'topic_id' => new xmlrpcval($tid, 'string'), 'state' => new xmlrpcval($visible ? 0 : 1, 'int')), 'struct');
    return new xmlrpcresp($result);
}
Example #12
0
function reply_post_func($xmlrpc_params)
{
    global $db, $lang, $theme, $plugins, $mybb, $session, $settings, $cache, $time, $mybbgroups, $tid, $pid, $visible, $thread, $post;
    $input = Tapatalk_Input::filterXmlInput(array('forum_id' => Tapatalk_Input::INT, 'topic_id' => Tapatalk_Input::INT, 'subject' => Tapatalk_Input::STRING, 'text_body' => Tapatalk_Input::STRING, 'attachment_id_array' => Tapatalk_Input::RAW, 'group_id' => Tapatalk_Input::STRING, 'return_html' => Tapatalk_Input::INT), $xmlrpc_params);
    $lang->load("newreply");
    $parser = new Tapatalk_Parser();
    $tid = $input['topic_id'];
    $options = array("limit" => 1);
    $query = $db->simple_select("threads", "*", "tid='" . $tid . "'");
    if ($db->num_rows($query) == 0) {
        return xmlrespfalse($lang->error_invalidthread);
    }
    $thread = $db->fetch_array($query);
    $fid = $thread['fid'];
    // Get forum info
    $forum = get_forum($fid);
    if (!$forum) {
        return xmlrespfalse($lang->error_invalidforum);
    }
    $forumpermissions = forum_permissions($fid);
    if ($thread['visible'] == 0 && !is_moderator($fid) || $thread['visible'] < 0) {
        return xmlrespfalse($lang->error_invalidthread);
    }
    if ($forum['open'] == 0 || $forum['type'] != "f") {
        return xmlrespfalse($lang->error_closedinvalidforum);
    }
    if ($mybb->user['uid'] < 1 || $forumpermissions['canview'] == 0 || $forumpermissions['canpostreplys'] == 0 || $mybb->user['suspendposting'] == 1) {
        return tt_no_permission();
    }
    if ($forumpermissions['canonlyviewthreads'] == 1 && $thread['uid'] != $mybb->user['uid']) {
        return tt_no_permission();
    }
    tt_check_forum_password($forum['fid']);
    // Check to see if the thread is closed, and if the user is a mod.
    if (!is_moderator($fid, "caneditposts")) {
        if ($thread['closed'] == 1) {
            return xmlrespfalse($lang->redirect_threadclosed);
        }
    }
    // Is the currently logged in user a moderator of this forum?
    if (is_moderator($fid)) {
        $ismod = true;
    } else {
        $ismod = false;
    }
    if (!empty($input['group_id'])) {
        $posthash = $input['group_id'];
    } else {
        $posthash = md5($thread['tid'] . $mybb->user['uid'] . random_str());
    }
    if ($mybb->settings['maxposts'] > 0 && $mybb->usergroup['cancp'] != 1) {
        $daycut = TIME_NOW - 60 * 60 * 24;
        $query = $db->simple_select("posts", "COUNT(*) AS posts_today", "uid='{$mybb->user['uid']}' AND visible='1' AND dateline>{$daycut}");
        $post_count = $db->fetch_field($query, "posts_today");
        if ($post_count >= $mybb->settings['maxposts']) {
            $lang->error_maxposts = $lang->sprintf($lang->error_maxposts, $mybb->settings['maxposts']);
            return xmlrespfalse($lang->error_maxposts);
        }
    }
    $username = $mybb->user['username'];
    $uid = $mybb->user['uid'];
    $user_check = "p.uid='{$uid}'";
    if (version_compare($mybb->version, '1.8.0', '<')) {
        $query = $db->simple_select("posts p", "p.pid, p.visible", "{$user_check} AND p.tid='{$thread['tid']}' AND p.subject='" . $db->escape_string($mybb->input['subject']) . "' AND p.message='" . $db->escape_string($mybb->input['message']) . "' AND p.posthash='" . $db->escape_string($mybb->input['posthash']) . "' AND p.visible != '-2'");
    } else {
        $query = $db->simple_select("posts p", "p.pid, p.visible", "{$user_check} AND p.tid='{$thread['tid']}' AND p.subject='" . $db->escape_string($mybb->get_input('subject')) . "' AND p.message='" . $db->escape_string($mybb->get_input('message')) . "' AND p.visible != '-2' AND p.dateline>" . (TIME_NOW - 600));
    }
    $duplicate_check = $db->fetch_field($query, "pid");
    if ($duplicate_check) {
        return xmlrespfalse($lang->error_post_already_submitted);
    }
    require_once MYBB_ROOT . "inc/datahandlers/post.php";
    $posthandler = new PostDataHandler("insert");
    $post = array("tid" => $input['topic_id'], "replyto" => 0, "fid" => $thread['fid'], "subject" => $input['subject'], "icon" => 0, "uid" => $uid, "username" => $username, "message" => $input['text_body'], "ipaddress" => get_ip(), "posthash" => $posthash);
    if ($mybb->input['pid']) {
        $post['pid'] = $mybb->input['pid'];
    }
    $post['savedraft'] = 0;
    // Set up the post options from the input.
    $post['options'] = array("signature" => 1, "subscriptionmethod" => $mybb->user['subscriptionmethod'] == 0 ? '' : $mybb->user['subscriptionmethod'], "disablesmilies" => 0);
    $post['modoptions']['stickthread'] = $thread['sticky'];
    $post['modoptions']['closethread'] = $thread['closed'];
    $posthandler->set_data($post);
    // Now let the post handler do all the hard work.
    $valid_post = $posthandler->validate_post();
    $post_errors = array();
    // Fetch friendly error messages if this is an invalid post
    if (!$valid_post) {
        $post_errors = $posthandler->get_friendly_errors();
    }
    // Mark thread as read
    require_once MYBB_ROOT . "inc/functions_indicators.php";
    mark_thread_read($tid, $fid);
    // One or more errors returned, fetch error list and throw to newreply page
    if (count($post_errors) > 0) {
        return xmlrespfalse(implode(" :: ", $post_errors));
    } else {
        $postinfo = $posthandler->insert_post();
        $pid = $postinfo['pid'];
        $visible = $postinfo['visible'];
        tapatalk_push_reply();
        tapatalk_push_quote();
        tapatalk_push_tag();
        // Deciding the fate
        if ($visible == -2) {
            $state = 1;
        } elseif ($visible == 1) {
            $state = 0;
        } else {
            $state = 1;
        }
    }
    $pid = intval($pid);
    if (!empty($input['group_id_esc'])) {
        $db->update_query("attachments", array("pid" => $pid), "posthash='{$input['group_id_esc']}'");
    }
    // update thread attachment account
    if (count($input['attachment_id_array']) > 0) {
        update_thread_counters($tid, array("attachmentcount" => "+" . count($input['attachment_id_array'])));
    }
    $post = get_post($pid);
    $parser_options = array();
    $parser_options['allow_html'] = false;
    $parser_options['allow_mycode'] = true;
    $parser_options['allow_smilies'] = false;
    $parser_options['allow_imgcode'] = true;
    $parser_options['allow_videocode'] = true;
    $parser_options['nl2br'] = (bool) $input['return_html'];
    $parser_options['filter_badwords'] = 1;
    if (!$post['username']) {
        $post['username'] = $lang->guest;
    }
    if ($post['userusername']) {
        $parser_options['me_username'] = $post['userusername'];
    } else {
        $parser_options['me_username'] = $post['username'];
    }
    $post['message'] = post_bbcode_clean($post['message']);
    $post['message'] = $parser->parse_message($post['message'], $parser_options);
    global $attachcache;
    $attachcache = array();
    if ($thread['attachmentcount'] > 0) {
        // Now lets fetch all of the attachments for these posts.
        $query = $db->simple_select("attachments", "*", "pid='{$pid}'");
        while ($attachment = $db->fetch_array($query)) {
            $attachcache[$attachment['pid']][$attachment['aid']] = $attachment;
        }
    }
    $attachment_list = process_post_attachments($post['pid'], $post);
    $can_delete = 0;
    if ($mybb->user['uid'] == $post['uid']) {
        if ($forumpermissions['candeletethreads'] == 1 && $postcounter == 1) {
            $can_delete = 1;
        } else {
            if ($forumpermissions['candeleteposts'] == 1 && $postcounter != 1) {
                $can_delete = 1;
            }
        }
    }
    $can_delete = (is_moderator($fid, "candeleteposts") || $can_delete == 1) && $mybb->user['uid'] != 0;
    $result = new xmlrpcval(array('result' => new xmlrpcval(true, 'boolean'), 'result_text' => new xmlrpcval('', 'base64'), 'post_id' => new xmlrpcval($postinfo['pid'], 'string'), 'state' => new xmlrpcval($state, 'int'), 'post_author_id' => new xmlrpcval($mybb->user['uid'], 'string'), 'post_author_name' => new xmlrpcval(basic_clean($mybb->user['username']), 'base64'), 'icon_url' => new xmlrpcval(absolute_url($mybb->user['avatar']), 'string'), 'post_content' => new xmlrpcval(process_post($post['message'], $input['return_html']), 'base64'), 'can_edit' => new xmlrpcval(is_moderator($fid, "caneditposts") || $thread['closed'] == 0 && $forumpermissions['caneditposts'] == 1, 'boolean'), 'can_delete' => new xmlrpcval($can_delete, 'boolean'), 'post_time' => new xmlrpcval(mobiquo_iso8601_encode(TIME_NOW), 'dateTime.iso8601'), 'timestamp' => new xmlrpcval(TIME_NOW, 'string'), 'attachments' => new xmlrpcval($attachment_list, 'array')), 'struct');
    return new xmlrpcresp($result);
}
function PostReply($who, $threadid, $pagetext, $quotepostid = 0)
{
    global $db, $vbulletin, $server, $structtypes, $lastpostarray;
    $result = RegisterService($who);
    if ($result['Code'] != 0) {
        $retval['Result'] = $result;
        return $retval;
    }
    $threadinfo = fetch_threadinfo($threadid);
    $foruminfo = fetch_foruminfo($threadinfo['forumid'], false);
    $postdm = new vB_DataManager_Post($vbulletin, ERRTYPE_STANDARD);
    $postdm->set_info('skip_maximagescheck', true);
    $postdm->set_info('forum', $foruminfo);
    $postdm->set_info('thread', $threadinfo);
    $postdm->set('threadid', $threadid);
    $postdm->set('userid', $vbulletin->userinfo['userid']);
    $postdm->set('allowsmilie', 1);
    $postdm->set('visible', 1);
    $postdm->set('dateline', TIMENOW);
    if ($quotepostid > 0) {
        $quote_postids[] = $quotepostid;
        $quotetxt = fetch_quotable_posts($quote_postids, $threadinfo['threadid'], $unquoted_post_count, $quoted_post_ids, 'only');
        $pagetext = "{$quotetxt}{$pagetext}";
    }
    $postdm->set('pagetext', "{$pagetext}");
    $postdm->pre_save();
    $postid = 0;
    if (count($postdm->errors) > 0) {
        // pre_save failed
        return ErrorResult('pre_save_failed_thread_reply');
    } else {
        $postid = $postdm->save();
        require_once './includes/functions_databuild.php';
        build_thread_counters($threadinfo['threadid']);
        build_forum_counters($foruminfo['forumid']);
        correct_forum_counters($threadinfo['threadid'], $foruminfo['forumid']);
        mark_thread_read($threadinfo, $foruminfo, $vbulletin->userinfo['userid'], TIMENOW);
    }
    $retval['PostID'] = $postid;
    $result['Code'] = 1;
    $result['Text'] = "QuotePostID: {$quotepostid}";
    $result['RemoteUser'] = ConsumeArray($vbulletin->userinfo, $structtypes['RemoteUser']);
    $retval['Result'] = $result;
    return $retval;
}