Example #1
0
function fetch_forum_permissions($usergroupid, $forumid)
{
    global $vbulletin;
    // assign the permissions to the usergroup defaults
    $perms = $vbulletin->usergroupcache["{$usergroupid}"]['forumpermissions'];
    DEVDEBUG("FPerms: Usergroup Defaults: {$perms}");
    // get the parent list of the forum we are interested in, excluding -1
    $parentlist = substr($vbulletin->forumcache["{$forumid}"]['parentlist'], 0, -3);
    // query forum permissions for the forums in the parent list of the current one
    $fperms = $vbulletin->db->query_read("\n\t\tSELECT forumid, forumpermissions\n\t\tFROM " . TABLE_PREFIX . "forumpermission\n\t\tWHERE usergroupid = {$usergroupid}\n\t\tAND forumid IN({$parentlist})\n\t");
    // no custom permissions found, return usergroup defaults
    if ($vbulletin->db->num_rows($fperms) == 0) {
        return array('forumpermissions' => $perms);
    } else {
        // assign custom permissions to forums
        $fp = array();
        while ($fperm = $vbulletin->db->fetch_array($fperms)) {
            $fp["{$fperm['forumid']}"] = $fperm['forumpermissions'];
        }
        unset($fperm);
        $vbulletin->db->free_result($fperms);
        // run through each forum in the forum's parent list in order
        foreach (array_reverse(explode(',', $parentlist)) as $parentid) {
            // if the current parent forum has a custom permission, use it
            if (isset($fp["{$parentid}"])) {
                $perms = $fp["{$parentid}"];
                DEVDEBUG("FPerms: Custom - forum '" . $vbulletin->forumcache["{$parentid}"]['title'] . "': {$perms}");
            }
        }
        // return the permissions, whatever they may be now.
        return array('forumpermissions' => $perms);
    }
}
Example #2
0
function fetch_search_forumids(&$forumchoice, $childforums = 0)
{
    global $vbulletin, $display;
    // make sure that $forumchoice is an array
    if (!is_array($forumchoice)) {
        $forumchoice = array($forumchoice);
    }
    // initialize the $forumids for return by this function
    $forumids = array();
    foreach ($forumchoice as $forumid) {
        // get subscribed forumids
        if ($forumid === 'subscribed' and $vbulletin->userinfo['userid'] != 0) {
            DEVDEBUG("Querying subscribed forums for " . $vbulletin->userinfo['username']);
            $sforums = $vbulletin->db->query_read_slave("\n\t\t\t\tSELECT forumid FROM " . TABLE_PREFIX . "subscribeforum\n\t\t\t\tWHERE userid = " . $vbulletin->userinfo['userid']);
            if ($vbulletin->db->num_rows($sforums) == 0) {
                // no subscribed forums
                eval(standard_error(fetch_error('not_subscribed_to_any_forums')));
            }
            while ($sforum = $vbulletin->db->fetch_array($sforums)) {
                $forumids["{$sforum['forumid']}"] .= $sforum['forumid'];
            }
            unset($sforum);
            $vbulletin->db->free_result($sforums);
        } else {
            $forumid = intval($forumid);
            if (isset($vbulletin->forumcache["{$forumid}"]) and $vbulletin->forumcache["{$forumid}"]['link'] == '') {
                $forumids["{$forumid}"] = $forumid;
            }
        }
    }
    // now if there are any forumids we have to query, work out their child forums
    if (empty($forumids)) {
        $forumchoice = array();
        $display['forums'] = array();
    } else {
        // set $forumchoice to show the returned forumids
        #$forumchoice = implode(',', $forumids);
        // put current forumids into the display table
        $display['forums'] = $forumids;
        // get child forums of selected forums
        if ($childforums) {
            require_once DIR . '/includes/functions_misc.php';
            foreach ($forumids as $forumid) {
                $children = fetch_child_forums($forumid, 'ARRAY');
                if (!empty($children)) {
                    foreach ($children as $childid) {
                        $forumids["{$childid}"] = $childid;
                    }
                }
                unset($children);
            }
        }
    }
    // return the array of forumids
    return $forumids;
}
         $userids2cache[] = $moderator['userid'];
     }
 }
 //Who visited code - copied with permission from Paul M
 if ($vbulletin->kbank['who']['enabled'] and THIS_SCRIPT == 'index' and $vbulletin->userinfo['userid']) {
     if ($vbulletin->kbank['who']['get24h']) {
         $cutoff = TIMENOW - 86400;
         $whodesc = $vbphrase['visited_today_24'];
     } else {
         $whodesc = $vbphrase['visited_today'];
         $tnow = date('YmdHis', TIMENOW - intval($vbulletin->options['hourdiff']));
         $cutoff = TIMENOW - (substr($tnow, 8, 2) * 3600 + substr($tnow, 10, 2) * 60 + substr($tnow, 12, 2));
     }
     unset($whotoday);
     $todaysusers = $vbulletin->db->query_read_slave("\n\t\t\tSELECT userid,username,usergroupid,displaygroupid,infractiongroupid,lastactivity,options\n\t\t\tFROM " . TABLE_PREFIX . "user FORCE INDEX (lastactivity)\n\t\t\tWHERE lastactivity > {$cutoff}\n\t\t\tORDER BY username\n\t\t");
     DEVDEBUG('[kBank] Get $todaysusers');
     //Cache - Performance optimizing
     $users = array();
     $userids = array();
     while ($today = $vbulletin->db->fetch_array($todaysusers)) {
         $users[] = $today;
         $userids[] = $today['userid'];
     }
     if (count($userids2cache)) {
         $userids = array_merge($userids, $userids2cache);
         $userids2cache = array();
         //Reset
     }
     findItemsToWork($userids, false, false);
     //Cache - complete!
     $totaltoday = 0;
function can_moderate_calendar($calendarid = 0, $do = '', $userid = -1)
{
    global $vbulletin, $cmodcache;
    if ($userid == -1) {
        $userid = $vbulletin->userinfo['userid'];
    }
    if ($vbulletin->userinfo['permissions']['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['ismoderator']) {
        DEVDEBUG('  USER IS A SUPER MODERATOR');
        return true;
    }
    cache_calendar_moderators();
    if ($calendarid == 0) {
        // just check to see if the user is a moderator of any calendar
        DEVDEBUG('looping through cmodcache to find userid $userid');
        $ismod = 0;
        foreach ($cmodcache as $calendarmods) {
            if (!empty($calendarmods["{$userid}"])) {
                $ismod = 1;
                break;
            }
        }
        return $ismod;
    } else {
        // check to see if user is a moderator of specific calendar
        $getmodperms = intval($cmodcache["{$calendarid}"]["{$userid}"]['permissions']);
        if (empty($do) and $getmodperms) {
            return true;
        } else {
            // check if user is a mod and has permissions to '$do'
            if ($getmodperms & $vbulletin->bf_misc_calmoderatorpermissions["{$do}"]) {
                return true;
            } else {
                return false;
            }
            // if has perms for this action
        }
        // if is mod for calendar and no action set
    }
    // if calendarid=0
}
Example #5
0
         }
     }
 }
 $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, '', '', '', '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;
/**
* Reads results of form submission and updates special templates accordingly
*
* @param	array	Array of data from form
* @param	string	Variable type
* @param	string	Variable type name
*/
function build_special_templates($newtemplates, $templatetype, $vartype)
{
    global $vbulletin, $template_cache;
    DEVDEBUG('------------------------');
    foreach ($template_cache["{$templatetype}"] as $title => $oldtemplate) {
        // ignore the '_validation' and '_failsafe' keys
        if ($title == '_validation' or $title == '_failsafe') {
            continue;
        }
        // just carry on if there is no data for the current $newtemplate
        if (!isset($newtemplates["{$title}"])) {
            DEVDEBUG("\${$vartype}" . "['{$title}'] is not set");
            continue;
        }
        // if delete the customized template, delete and continue
        if ($vbulletin->GPC['delete']["{$vartype}"]["{$title}"]) {
            if ($vbulletin->GPC['dostyleid'] != -1) {
                $vbulletin->db->query_write("\n\t\t\t\t\tDELETE FROM " . TABLE_PREFIX . "template\n\t\t\t\t\tWHERE title = '" . $vbulletin->db->escape_string($title) . "' AND\n\t\t\t\t\ttemplatetype = '{$templatetype}' AND\n\t\t\t\t\tstyleid = " . $vbulletin->GPC['dostyleid'] . "\n\t\t\t\t");
                DEVDEBUG("{$vartype} {$title} (reverted)");
                if ($templatetype == 'stylevar' and $title == 'codeblockwidth') {
                    $vbulletin->db->query_write("TRUNCATE TABLE " . TABLE_PREFIX . "postparsed");
                }
            }
            continue;
        }
        // check for what to do with the template
        switch ($templatetype) {
            case 'stylevar':
                $newtemplate = $newtemplates["{$title}"];
                if (isset($newtemplates['_validation']["{$title}"])) {
                    if (!preg_match($newtemplates['_validation']["{$title}"], $newtemplate)) {
                        $newtemplate = $newtemplates['_failsafe']["{$title}"];
                    }
                }
                break;
            case 'css':
                $newtemplate = serialize($newtemplates["{$title}"]);
                break;
            case 'replacement':
                $newtemplate = $newtemplates["{$title}"];
                break;
        }
        if ($newtemplate != $oldtemplate['template']) {
            // update existing $vartype template
            if ($oldtemplate['styleid'] == $vbulletin->GPC['dostyleid']) {
                $vbulletin->db->query_write("\n\t\t\t\t\tUPDATE " . TABLE_PREFIX . "template\n\t\t\t\t\tSET template = '" . $vbulletin->db->escape_string($newtemplate) . "',\n\t\t\t\t\tdateline = " . TIMENOW . ",\n\t\t\t\t\tusername = '******'username']) . "'\n\t\t\t\t\tWHERE title = '" . $vbulletin->db->escape_string($title) . "' AND\n\t\t\t\t\ttemplatetype = '{$templatetype}' AND\n\t\t\t\t\tstyleid = " . $vbulletin->GPC['dostyleid'] . "\n\t\t\t\t");
                DEVDEBUG("{$vartype} {$title} (updated)");
                // insert new $vartype template
            } else {
                /*insert query*/
                $vbulletin->db->query_write("\n\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "template\n\t\t\t\t\t(styleid, templatetype, title, dateline, username, template)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(" . intval($vbulletin->GPC['dostyleid']) . ", '{$templatetype}', '" . $vbulletin->db->escape_string($title) . "', " . TIMENOW . ", '" . $vbulletin->db->escape_string($vbulletin->userinfo['username']) . "', '" . $vbulletin->db->escape_string($newtemplate) . "')\n\t\t\t\t");
                DEVDEBUG("{$vartype} {$title} (inserted)");
            }
            if ($templatetype == 'stylevar' and $title == 'codeblockwidth') {
                $vbulletin->db->query_write("TRUNCATE TABLE " . TABLE_PREFIX . "postparsed");
            }
        } else {
            DEVDEBUG("{$vartype} {$title} (not changed)");
        }
    }
    // end foreach($template_cache)
}
/**
* Rebuilds the $vbulletin->usergroupcache and $vbulletin->forumcache from the forum/usergroup tables
*
* @param	boolean	If true, force a recalculation of the forum parent and child lists
*/
function build_forum_permissions($rebuild_genealogy = true)
{
    global $vbulletin, $fpermcache;
    #echo "<h1>updateForumPermissions</h1>";
    $grouppermissions = array();
    $fpermcache = array();
    $vbulletin->forumcache = array();
    $vbulletin->usergroupcache = array();
    // query usergroups
    $usergroups = $vbulletin->db->query_read("SELECT * FROM " . TABLE_PREFIX . "usergroup ORDER BY title");
    while ($usergroup = $vbulletin->db->fetch_array($usergroups)) {
        foreach ($usergroup as $key => $val) {
            if (is_numeric($val)) {
                $usergroup["{$key}"] += 0;
            }
        }
        $vbulletin->usergroupcache["{$usergroup['usergroupid']}"] = $usergroup;
        // Profile pics disabled so don't inherit any of the profile pic settings
        if (!($vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canprofilepic'])) {
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['profilepicmaxwidth'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['profilepicmaxheight'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['profilepicmaxsize'] = -1;
        }
        // Avatars disabled so don't inherit any of the avatar settings
        if (!($vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canuseavatar'])) {
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['avatarmaxwidth'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['avatarmaxheight'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['avatarmaxsize'] = -1;
        }
        // Signature pics or signatures are disabled so don't inherit any of the signature pic settings
        if (!($vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['signaturepermissions'] & $vbulletin->bf_ugp_signaturepermissions['cansigpic']) or !($vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canusesignature'])) {
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigpicmaxwidth'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigpicmaxheight'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigpicmaxsize'] = -1;
        }
        // Signatures are disabled so don't inherit any of the signature settings
        if (!($vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canusesignature'])) {
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigmaxrawchars'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigmaxchars'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigmaxlines'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigmaxsizebbcode'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['sigmaximages'] = -1;
            $vbulletin->usergroupcache["{$usergroup['usergroupid']}"]['signaturepermissions'] = 0;
        }
        ($hook = vBulletinHook::fetch_hook('admin_build_forum_perms_group')) ? eval($hook) : false;
        $grouppermissions["{$usergroup['usergroupid']}"] = $usergroup['forumpermissions'];
    }
    unset($usergroup);
    $vbulletin->db->free_result($usergroups);
    DEVDEBUG('updateForumCache( ) - Queried Usergroups');
    $vbulletin->forumcache = array();
    $vbulletin->iforumcache = array();
    $forumdata = array();
    // get the vbulletin->iforumcache so we can traverse the forums in order within cache_forum_permissions
    $newforumcache = $vbulletin->db->query_read("\n\t\tSELECT forum.*" . (VB_AREA != 'Upgrade' ? ", NOT ISNULL(podcast.forumid) AS podcast" : "") . "\n\t\tFROM " . TABLE_PREFIX . "forum AS forum\n\t\t" . (VB_AREA != 'Upgrade' ? "LEFT JOIN " . TABLE_PREFIX . "podcast AS podcast ON (forum.forumid = podcast.forumid AND podcast.enabled = 1)" : "") . "\n\t\tORDER BY displayorder\n\t");
    while ($newforum = $vbulletin->db->fetch_array($newforumcache)) {
        foreach ($newforum as $key => $val) {
            /* values which begin with 0 and are greater than 1 character are strings, since 01 would be an octal number in PHP */
            if (is_numeric($val) and !(substr($val, 0, 1) == '0' and strlen($val) > 1) and !in_array($key, array('title', 'title_clean', 'description', 'description_clean'))) {
                $newforum["{$key}"] += 0;
            }
        }
        $vbulletin->iforumcache["{$newforum['parentid']}"]["{$newforum['forumid']}"] = $newforum['forumid'];
        $forumdata["{$newforum['forumid']}"] = $newforum;
    }
    $vbulletin->db->free_result($newforumcache);
    // get the forumcache into the order specified in $vbulletin->iforumcache
    $vbulletin->forumorder = array();
    fetch_forum_order();
    foreach ($vbulletin->forumorder as $forumid => $depth) {
        $vbulletin->forumcache["{$forumid}"] =& $forumdata["{$forumid}"];
        $vbulletin->forumcache["{$forumid}"]['depth'] = $depth;
    }
    unset($vbulletin->forumorder);
    // rebuild forum parent/child lists
    if ($rebuild_genealogy) {
        build_forum_genealogy();
    }
    // query forum permissions
    $fperms = $vbulletin->db->query_read("SELECT * FROM " . TABLE_PREFIX . "forumpermission");
    while ($fperm = $vbulletin->db->fetch_array($fperms)) {
        $fpermcache["{$fperm['forumid']}"]["{$fperm['usergroupid']}"] = intval($fperm['forumpermissions']);
        ($hook = vBulletinHook::fetch_hook('admin_build_forum_perms_forum')) ? eval($hook) : false;
    }
    unset($fperm);
    $vbulletin->db->free_result($fperms);
    DEVDEBUG('updateForumCache( ) - Queried Forum Pemissions');
    // call the function that will work out the forum permissions
    cache_forum_permissions($grouppermissions);
    // finally replace the existing cache templates
    build_datastore('usergroupcache', serialize($vbulletin->usergroupcache), 1);
    foreach (array_keys($vbulletin->forumcache) as $forumid) {
        unset($vbulletin->forumcache["{$forumid}"]['replycount'], $vbulletin->forumcache["{$forumid}"]['lastpost'], $vbulletin->forumcache["{$forumid}"]['lastposter'], $vbulletin->forumcache["{$forumid}"]['lastthread'], $vbulletin->forumcache["{$forumid}"]['lastthreadid'], $vbulletin->forumcache["{$forumid}"]['lasticonid'], $vbulletin->forumcache["{$forumid}"]['lastprefixid'], $vbulletin->forumcache["{$forumid}"]['threadcount']);
    }
    build_datastore('forumcache', serialize($vbulletin->forumcache), 1);
    DEVDEBUG('updateForumCache( ) - Updated caches, ' . $vbulletin->db->affected_rows() . ' rows affected.');
}
Example #8
0
 $usergroups = array();
 $badgroups = array();
 while ($getusergroup = $db->fetch_array($getusergroups)) {
     $ugid =& $getusergroup['usergroupid'];
     if (isset($vbulletin->usergroupcache["{$ugid}"])) {
         $vbulletin->usergroupcache["{$ugid}"]['joinrequests'] = $getusergroup['requests'];
     } else {
         $badgroups[] = $getusergroup['usergroupid'];
     }
 }
 unset($getusergroup);
 $db->free_result($getusergroups);
 // if there are any invalid requests, zap them now
 if (!empty($badgroups)) {
     $badgroups = implode(', ', $badgroups);
     DEVDEBUG("Deleting requests from the following invalid usergroups: {$badgroups}");
     $db->query_write("DELETE FROM " . TABLE_PREFIX . "usergrouprequest WHERE usergroupid IN ({$badgroups})");
 }
 // create array to hold options for the menu
 $groupsmenu = array();
 foreach ($vbulletin->usergroupcache as $id => $usergroup) {
     if ($usergroup['ispublicgroup']) {
         $groupsmenu["{$id}"] = htmlspecialchars_uni($usergroup['title']) . " ({$vbphrase['join_requests']}: " . vb_number_format($usergroup['joinrequests']) . ")";
     }
 }
 print_form_header('usergroup', 'viewjoinrequests', 0, 1, 'chooser');
 print_label_row($vbphrase['usergroup'], '<select name="usergroupid" onchange="this.form.submit();" class="bginput">' . construct_select_options($groupsmenu, $vbulletin->GPC['usergroupid']) . '</select><input type="submit" class="button" value="' . $vbphrase['go'] . '" />', 'thead');
 print_table_footer();
 unset($groupsmenu);
 // now if we are being asked to display a particular usergroup, do so.
 if ($vbulletin->GPC['usergroupid']) {
Example #9
0
 /**
  * Caches the smilies in a form ready to be executed.
  *
  * @param	bool	Whether HTML parsing is enabled
  *
  * @return	array	Reference to smilie cache (key: find text; value: replace text)
  */
 function &cache_smilies($do_html)
 {
     $key = $do_html ? 'html' : 'no_html';
     if (isset($this->smilie_cache["{$key}"])) {
         return $this->smilie_cache["{$key}"];
     }
     $sc =& $this->smilie_cache["{$key}"];
     $sc = array();
     if ($this->registry->smiliecache !== null) {
         // we can get the smilies from the smiliecache datastore
         DEVDEBUG('returning smilies from the datastore');
         foreach ($this->registry->smiliecache as $smilie) {
             if (!$do_html) {
                 $find = htmlspecialchars_uni(trim($smilie['smilietext']));
             } else {
                 $find = trim($smilie['smilietext']);
             }
             // if you change this HTML tag, make sure you change the smilie remover in code/php/html tag handlers!
             if ($this->is_wysiwyg()) {
                 $replace = "<img src=\"{$smilie['smiliepath']}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" smilieid=\"{$smilie['smilieid']}\" class=\"inlineimg\" />";
             } else {
                 $replace = "<img src=\"{$smilie['smiliepath']}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" class=\"inlineimg\" />";
             }
             $sc["{$find}"] = $replace;
         }
     } else {
         // we have to get the smilies from the database
         DEVDEBUG('querying for smilies');
         $this->registry->smiliecache = array();
         $smilies = $this->registry->db->query_read("\n\t\t\t\tSELECT *, LENGTH(smilietext) AS smilielen\n\t\t\t\tFROM " . TABLE_PREFIX . "smilie\n\t\t\t\tORDER BY smilielen DESC\n\t\t\t");
         while ($smilie = $this->registry->db->fetch_array($smilies)) {
             if (!$do_html) {
                 $find = htmlspecialchars_uni(trim($smilie['smilietext']));
             } else {
                 $find = trim($smilie['smilietext']);
             }
             // if you change this HTML tag, make sure you change the smilie remover in code/php/html tag handlers!
             if ($this->is_wysiwyg()) {
                 $replace = "<img src=\"{$smilie['smiliepath']}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" smilieid=\"{$smilie['smilieid']}\" class=\"inlineimg\" />";
             } else {
                 $replace = "<img src=\"{$smilie['smiliepath']}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" class=\"inlineimg\" />";
             }
             $sc["{$find}"] = $replace;
             $this->registry->smiliecache["{$smilie['smilieid']}"] = $smilie;
         }
     }
     return $sc;
 }
Example #10
0
function findItemsToWork($userids, $work = false, $allstatus = false, $query_hook = false)
{
    global $vbulletin, $kbank_active_items;
    if (!$vbulletin->kbank['itemEnabled']) {
        return false;
    }
    $didsomething = false;
    $userids_query = array();
    if ($query_hook['force']) {
        $userids_query[] = -1;
    }
    if (is_numeric($userids)) {
        $userids = array($userids);
    }
    if (is_array($userids)) {
        foreach ($userids as $userid) {
            if ($allstatus) {
                unset($kbank_active_items[$userid]);
            }
            if (is_numeric($userid) and $userid > 0 and !isset($kbank_active_items[$userid]) and !in_array($userid, $userids_query)) {
                $userids_query[] = intval($userid);
                $kbank_active_items[$userid] = array();
            }
        }
    }
    if (count($userids_query) > 0) {
        $items = $vbulletin->db->query_read("\n\t\t\tSELECT \n\t\t\t\titems.*\n\t\t\t\t,user.username AS username\n\t\t\t" . iif($query_hook['fulljoin'], $query_hook['fulljoin'], "FROM `" . TABLE_PREFIX . "kbank_items` AS items\n\t\t\t\t{$query_hook['join']}\n\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "user` AS user ON (user.userid = items.userid)") . "\n\t\t\tWHERE (\n\t\t\t\t" . iif($query_hook['idcheckfield'] !== false, iif($query_hook['idcheckfield'], $query_hook['idcheckfield'], 'items.userid') . " in (" . implode(',', $userids_query) . ")") . "\n\t\t\t\t{$query_hook['where']}\n\t\t\t\t)\n\t\t\t\tAND items.status > " . iif(!$allstatus, KBANK_ITEM_AVAILABLE, KBANK_ITEM_DELETED) . "\n\t\t\t\tAND (items.expire_time > " . TIMENOW . "\n\t\t\t\t\tOR items.expire_time < 0)\n\t\t\tORDER BY items.userid ASC, items.type ASC, items.expire_time DESC\n\t\t");
        DEVDEBUG('[kBank Item] findItemsToWorks query the database');
        $itemdatas = array();
        $itemtypeids = array();
        while ($itemdata = $vbulletin->db->fetch_array($items)) {
            $itemdatas[] = $itemdata;
            $itemtypeids[] = $itemdata['type'];
        }
        $vbulletin->db->free_result($items);
        unset($item);
        //Prepare itemtypes
        newItemType($itemtypeids, false, true);
        //Load items
        $userids2sort = array();
        foreach ($itemdatas as $itemdata) {
            $item =& newItem($itemdata['itemid'], $itemdata);
            $kbank_active_items[$itemdata['userid']][$itemdata['itemid']] = $item;
            if (!in_array($itemdata['userid'], $userids2sort)) {
                $userids2sort[] = $itemdata['userid'];
            }
        }
        //sorting
        foreach ($userids2sort as $userid) {
            if ($userid != -1 and is_array($kbank_active_items[$userid])) {
                usort($kbank_active_items[$userid], 'findItemsToWork_cmp');
                if (count($kbank_active_items[$userid]) > 1) {
                    //fix itemid, only work if more than 1 item
                    $items = array();
                    foreach ($kbank_active_items[$userid] as $item) {
                        if ($item) {
                            $items[$item->data['itemid']] = $item;
                        }
                    }
                    $kbank_active_items[$userid] = $items;
                }
            }
        }
    }
    if ($work) {
        foreach ($userids as $userid) {
            if (findItemToWork($userid)) {
                $didsomething = true;
            }
        }
    }
    return $didsomething;
}
Example #11
0
/**
* Determine moderator ability
*
* @param string		Permissions
* @param interger	Userid
* @param	string	Comma separated list of usergroups to which the user belongs
*
* @return	boolean
*/
function can_moderate_blog($do = '', $userinfo = null)
{
	global $vbulletin;

	$issupermod = false;
	$superpermissions = 0;

	if ($userinfo === null)
	{
		$modinfo =& $vbulletin->userinfo;
	}
	else
	{
		$modinfo =& $userinfo;
	}

	if ($modinfo['permissions']['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['ismoderator'])
	{
		DEVDEBUG('  USER IS A SUPER MODERATOR');
		$issupermod = true;
	}

	if (empty($do))
	{
		if ($issupermod)
		{
			return true;
		}
		else if (isset($modinfo['isblogmoderator']))
		{
			if ($modinfo['isblogmoderator'])
			{
				DEVDEBUG('	USER HAS ISBLOGMODERATOR SET');
				return true;
			}
			else
			{
				DEVDEBUG('	USER DOES NOT HAVE ISBLOGMODERATOR SET');
				return false;
			}
		}
	}

	cache_blog_moderators();
	$permissions = intval($vbulletin->vbblog['modcache']["$modinfo[userid]"]['normal']['permissions']);
	if ($issupermod)
	{
		if (isset($vbulletin->vbblog['modcache']["$modinfo[userid]"]['super']))
		{
			$permissions |= $vbulletin->vbblog['modcache']["$modinfo[userid]"]['super']['permissions'];
		}
		else
		{
			$permissions |= array_sum($vbulletin->bf_misc_vbblogmoderatorpermissions);
		}
	}

	if (empty($do) AND $permissions)
	{
		return true;
	}
	else if ($permissions & $vbulletin->bf_misc_vbblogmoderatorpermissions["$do"])
	{
		return true;
	}
	else
	{
		return false;
	}
}
 /**
  * Caches the smilies in a form ready to be executed.
  *
  * @param	bool	Whether HTML parsing is enabled
  *
  * @return	array	Reference to smilie cache (key: find text; value: replace text)
  */
 function &cache_smilies($do_html)
 {
     $key = $do_html ? 'html' : 'no_html';
     if (isset($this->smilie_cache["{$key}"])) {
         return $this->smilie_cache["{$key}"];
     }
     $sc =& $this->smilie_cache["{$key}"];
     $sc = array();
     if ($this->registry->smiliecache !== null) {
         // we can get the smilies from the smiliecache datastore
         DEVDEBUG('returning smilies from the datastore');
         foreach ($this->registry->smiliecache as $smilie) {
             if (!$do_html) {
                 $find = htmlspecialchars_uni(trim($smilie['smilietext']));
             } else {
                 $find = trim($smilie['smilietext']);
             }
             $smiliepath = preg_match('/^https?:\\/\\//', $smilie['smiliepath']) ? $smilie['smiliepath'] : vB::getDatastore()->getOption('bburl') . '/' . $smilie['smiliepath'];
             // if you change this HTML tag, make sure you change the smilie remover in code/php/html tag handlers!
             if ($this->is_wysiwyg()) {
                 $replace = "<img src=\"{$smiliepath}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" smilieid=\"{$smilie['smilieid']}\" class=\"inlineimg\" />";
             } else {
                 $replace = "<img src=\"{$smiliepath}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" class=\"inlineimg\" />";
             }
             $sc["{$find}"] = $replace;
         }
     } else {
         // we have to get the smilies from the database
         DEVDEBUG('querying for smilies');
         $this->registry->smiliecache = array();
         $smilies = vB::getDbAssertor()->getRows('fetchSmilies', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_STORED));
         foreach ($smilies as $smilie) {
             if (!$do_html) {
                 $find = htmlspecialchars_uni(trim($smilie['smilietext']));
             } else {
                 $find = trim($smilie['smilietext']);
             }
             $smiliepath = preg_match('/^https?:\\/\\//', $smilie['smiliepath']) ? $smilie['smiliepath'] : vB::getDatastore()->getOption('bburl') . '/' . $smilie['smiliepath'];
             // if you change this HTML tag, make sure you change the smilie remover in code/php/html tag handlers!
             if ($this->is_wysiwyg()) {
                 $replace = "<img src=\"{$smiliepath}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" smilieid=\"{$smilie['smilieid']}\" class=\"inlineimg\" />";
             } else {
                 $replace = "<img src=\"{$smiliepath}\" border=\"0\" alt=\"\" title=\"" . htmlspecialchars_uni($smilie['title']) . "\" class=\"inlineimg\" />";
             }
             $sc["{$find}"] = $replace;
             $this->registry->smiliecache["{$smilie['smilieid']}"] = $smilie;
         }
     }
     return $sc;
 }
/**
* Rebuilds the $vbulletin->usergroupcache
*/
function build_channel_permissions()
{
    global $vbulletin, $npermscache;
    $grouppermissions = array();
    $npermscache = array();
    $vbulletin->usergroupcache = array();
    // query usergroups
    $usergroups = vB::getDbAssertor()->assertQuery('usergroup', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT), 'title');
    foreach ($usergroups as $usergroup) {
        foreach ($usergroup as $key => $val) {
            if (is_numeric($val)) {
                $usergroup["{$key}"] += 0;
            }
        }
        $vbulletin->usergroupcache["{$usergroup['usergroupid']}"] = $usergroup;
        $vbulletin->usergroupcache["{$usergroup['usergroupid']}"] = get_disabled_perms($usergroup['usergroupid']) + $vbulletin->usergroupcache["{$usergroup['usergroupid']}"];
        // Legacy Hook 'admin_build_forum_perms_group' Removed //
        $grouppermissions["{$usergroup['usergroupid']}"] = $usergroup['forumpermissions'];
    }
    unset($usergroup);
    DEVDEBUG('updateChannelCache( ) - Queried Usergroups');
    // query forum permissions
    $permQry = vB::getDbAssertor()->assertQuery('vBForum:permission', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT));
    $permissions = array();
    foreach ($permQry as $cperm) {
        $permissions["{$cperm['groupid']}"]["{$cperm['nodeid']}"] = $cperm;
        $npermscache["{$cperm['nodeid']}"]["{$cperm['groupid']}"] = $cperm;
        // Legacy Hook 'admin_build_channel_perms_forum' Removed //
    }
    $userContext = vB::getUserContext();
    if ($userContext) {
        $userContext->rebuildGroupAccess();
    }
    DEVDEBUG('updateChannelCache( ) - Queried Channel Pemissions');
    // call the function that will work out the forum permissions
    cache_forum_permissions();
    // finally replace the existing cache templates
    $vbulletin->usergroupcache = vB::getDatastore()->buildUserGroupCache($vbulletin->usergroupcache);
}
\*======================================================================*/
global $vbulletin;
if (defined('VB_AREA') and $vbulletin->kbank['enabled'] and ($vbulletin->options['templateversion'] < '3.7.0' or $this->template_name == 'memberinfo_block_statistics')) {
    include_once DIR . '/kbank/functions.php';
    global $kbank, $userinfo;
    if ($vbulletin->kbank['profile_elements'] & $vbulletin->kbank['bitfield']['display_elements']['kbank_show_points']) {
        $showpoints = true;
        if ($vbulletin->kbank['profile_elements'] & $vbulletin->kbank['bitfield']['display_elements']['kbank_show_toprichest'] and $vbulletin->kbank_toprichest and isset($vbulletin->kbank_toprichest[$userinfo['userid']])) {
            $toprichest = construct_phrase($vbphrase['kbank_misc_toprichest_show'], $vbulletin->kbank_toprichest[$userinfo['userid']]['pos']);
        }
    }
    if ($vbulletin->kbank['profile_elements'] & $vbulletin->kbank['bitfield']['display_elements']['kbank_show_items']) {
        $showitems = true;
        //search for itemtype that user can produce
        $itemtypes = $vbulletin->db->query_read("SELECT *\n\t\t\tFROM `" . TABLE_PREFIX . "kbank_itemtypes` AS itemtypes\n\t\t\tWHERE userid LIKE '%,{$userinfo['userid']},%'");
        DEVDEBUG('[kBank Item] Query database for user itemtypes');
        if ($vbulletin->db->num_rows($itemtypes)) {
            $userinfo['kbank_itemtypes'] = '';
            while ($itemtypedata = $vbulletin->db->fetch_array($itemtypes)) {
                $userinfo['kbank_itemtypes'] .= '<li>' . "<a href=\"{$vbulletin->kbank['phpfile']}?do=shop&username={$userinfo['username']}&itemtypeid={$itemtypedata['itemtypeid']}\" target=\"_blank\">{$itemtypedata['name']}</a>" . '</li>';
            }
            unset($itemtypedata);
        }
        $vbulletin->db->free_result($itemtypes);
        //search for user items
        if ($vbulletin->userinfo['userid'] != $userinfo['userid']) {
            //skip 1 query if user is viewing his/her profile. Everything has been loaded!
            findItemToWork($userinfo['userid'], true);
        }
        global $kbank_active_items;
        if (count($kbank_active_items[$userinfo['userid']])) {
Example #15
0
function ap_doHistory($postid, $points, $reason)
{
    if (!is_numeric($postid) or $postid <= 0) {
        exit;
    }
    //Error free!
    global $vbulletin, $vbphrase, $messages;
    $more_query = array('to' => '', 'from' => '');
    //Get user's profile
    $user = $vbulletin->db->query_first("\n\t\tSELECT \n\t\t\tpost.userid AS userid, \n\t\t\tuser.username AS username,\n\t\t\tuser.{$vbulletin->kbank['field']} AS total, \n\t\t\tuser.usergroupid AS usergroupid,\n\t\t\tuser.membergroupids AS membergroupids,\n\t\t\tuser.displaygroupid AS displaygroupid,\n\t\t\tuser.usertitle AS usertitle,\n\t\t\tuser.customtitle AS customtitle\n\t\tFROM `" . TABLE_PREFIX . "post` AS post\n\t\tINNER JOIN `" . TABLE_PREFIX . "user` AS user ON (user.userid = post.userid)\n\t\tWHERE postid = '{$postid}';");
    DEVDEBUG('[kBank Award] ap_doHistory query the database');
    //Check for new usergroup moving
    $newug = 0;
    foreach ($vbulletin->kbank['award']['listMove2GroupIDs'] as $rule) {
        $tmp = explode(':', $rule);
        $result_tmp = 12345;
        @eval('$result_tmp = (' . ($user['total'] + $points) . $tmp[0] . ');');
        if ($result_tmp !== 12345) {
            if ($result_tmp !== true and $result_tmp !== false) {
                $result_tmp = 12345;
                @eval('$result_tmp = (' . ($user['total'] + $points) . '<' . $tmp[0] . ');');
                if ($result_tmp === 12345 or $result_tmp !== true or $result_tmp !== false) {
                    $result_tmp = false;
                }
            }
        } else {
            $result_tmp = false;
        }
        if ($result_tmp) {
            $newug = $tmp[1];
        }
    }
    if ($newug != 0 and !is_member_of($user, $vbulletin->kbank['award']['permCanRemoveGroupIDs']) and !is_member_of($user, $newug)) {
        $more_query['to'] .= " ,usergroupid = {$newug}";
    } else {
        $newug = 0;
    }
    //Done with finding new usergroup
    //Add ban record if needed (if new group is a ban group)
    if ($newug) {
        //Find 'is ban group' groups
        $querygroups = array();
        foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup) {
            if (!($usergroup['genericoptions'] & $vbulletin->bf_ugp_genericoptions['isnotbannedgroup'])) {
                $querygroups[] = $usergroupid;
            }
        }
        if (in_array($newug, $querygroups)) {
            $adminid = $vbulletin->userinfo['userid'];
            if (!$vbulletin->db->query_first("\n\t\t\t\t\tSELECT * FROM `" . TABLE_PREFIX . "userban`\n\t\t\t\t\tWHERE userid = {$user['userid']}\n\t\t\t\t")) {
                $vbulletin->db->query("\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "userban`\n\t\t\t\t\t(userid, usergroupid, displaygroupid, usertitle, customtitle, adminid, bandate, liftdate, reason)\n\t\t\t\t\tVALUES (\n\t\t\t\t\t\t{$user['userid']}\n\t\t\t\t\t\t,{$user['usergroupid']}\n\t\t\t\t\t\t,{$user['displaygroupid']}\n\t\t\t\t\t\t,'{$user['usertitle']}'\n\t\t\t\t\t\t,{$user['customtitle']}\n\t\t\t\t\t\t,{$adminid}\n\t\t\t\t\t\t," . TIMENOW . "\n\t\t\t\t\t\t,0\n\t\t\t\t\t\t,'{$vbphrase['kbank_award_bank_rupted']}'\n\t\t\t\t\t);");
                DEVDEBUG('[kBank Award] ap_doHistory query the database 2 times');
            }
            $more_query['to'] .= " ,usertitle = '{$vbphrase['kbank_award_bank_rupted']}'";
        }
    }
    //Adjust counter
    $more_query['to'] .= iif($reason != AWARD_REMOVE, " ,{$vbulletin->kbank['award']['awardedtimes']} = {$vbulletin->kbank['award']['awardedtimes']} + 1", " ,{$vbulletin->kbank['award']['awardedtimes']} = {$vbulletin->kbank['award']['awardedtimes']} - 1") . " ,{$vbulletin->kbank['award']['awardedamount']} = {$vbulletin->kbank['award']['awardedamount']} + {$points}";
    //Specified itemname for banklogs
    $more_query['banklogs'] = array('itemname' => 'post');
    //Update database
    $result = transferMoney(0, $user['userid'], $points, array('adminid' => $vbulletin->userinfo['userid'], 'comment' => $reason), null, true, false, KBANK_NO_TAX, false, $postid, $more_query);
    //Send PM to user (if action done successfully)
    if ($result === true and $vbulletin->kbank['award']['sendPM']) {
        //build title,message
        $url = $vbulletin->options['bburl'];
        if ($reason != AWARD_REMOVE) {
            $title = $vbphrase['kbank_award_PM_title'];
            $text = construct_phrase($vbphrase['kbank_award_PM_text'], "{$url}/showthread.php?p={$postid}", $points, $reason, "{$url}/member.php?u={$vbulletin->userinfo['userid']}", $vbulletin->userinfo['username'], $vbulletin->kbank['name']);
        } else {
            $title = $vbphrase['kbank_award_PM_title_deleted'];
            $text = construct_phrase($vbphrase['kbank_award_PM_text_deleted'], "{$url}/showthread.php?p={$postid}", "{$url}/member.php?u={$vbulletin->userinfo['userid']}", $vbulletin->userinfo['username']);
        }
        if ($newug != 0) {
            $text .= construct_phrase($vbphrase['kbank_award_usergroup_moved'], $newug);
            $messages[] = construct_phrase($vbphrase['kbank_award_usergroup_moved_for_admin'], $newug, $user['username']);
        }
        $result = kbank_sendPM($vbulletin->userinfo, $user, $title, $text, false);
    }
    return $result;
}
Example #16
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 #17
0
function fetch_iconinfo($iconid = 0)
{
    global $vbulletin, $vbphrase, $vbulletin;
    $iconid = intval($iconid);
    switch ($iconid) {
        case -1:
            DEVDEBUG('returning poll icon');
            return array('iconpath' => vB_Template_Runtime::fetchStyleVar('imgdir_misc') . "/poll_posticon.gif", 'title' => $vbphrase['poll']);
        case 0:
            if (!empty($vbulletin->options['showdeficon'])) {
                DEVDEBUG("returning default icon");
                return array('iconpath' => $vbulletin->options['showdeficon'], 'title' => '');
            } else {
                return false;
            }
        default:
            if ($vbulletin->iconcache !== null) {
                // we can get the icon info from the template cache
                DEVDEBUG("returning iconid:{$iconid} from the template cache");
                return $vbulletin->iconcache["{$iconid}"];
            } else {
                // we have to get the icon from a query
                DEVDEBUG("QUERYING iconid:{$iconid})");
                return $vbulletin->db->query_first_slave("\n\t\t\t\t\tSELECT title, iconpath\n\t\t\t\t\tFROM " . TABLE_PREFIX . "icon\n\t\t\t\t\tWHERE iconid = {$iconid}\n\t\t\t\t");
            }
    }
}
Example #18
0
function do_get_forum()
{
    global $vbulletin, $db, $show, $vbphrase, $foruminfo;
    $canpost = true;
    $vbulletin->input->clean_array_gpc('r', array('fid' => TYPE_INT, 'previewtype' => TYPE_INT));
    $previewtype = $vbulletin->GPC['previewtype'];
    if (!$previewtype) {
        $previewtype = 1;
    }
    if (empty($foruminfo['forumid'])) {
        $forumid = -1;
    } else {
        $vbulletin->input->clean_array_gpc('r', array('password' => TYPE_STR));
        // Check the forum password
        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);
            }
        }
        $perpage = $vbulletin->input->clean_gpc('r', 'perpage', TYPE_UINT);
        $pagenumber = $vbulletin->input->clean_gpc('r', 'pagenumber', TYPE_UINT);
        $daysprune = $vbulletin->input->clean_gpc('r', 'daysprune', TYPE_INT);
        $sortfield = $vbulletin->input->clean_gpc('r', 'sortfield', TYPE_STR);
        // get permission to view forum
        $_permsgetter_ = 'forumdisplay';
        $forumperms = fetch_permissions($foruminfo['forumid']);
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canview'])) {
            json_error(ERR_NO_PERMISSION);
        }
        // Check for forum password!
        if (!verify_forum_password($foruminfo['forumid'], $foruminfo['password'], false)) {
            json_error(ERR_NEED_PASSWORD, RV_NEED_FORUM_PASSWORD);
        }
        // Can we post in this forum?
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canpostnew'])) {
            $canpost = false;
        }
        $forumid = $foruminfo['forumid'];
    }
    // Can forum contain threads?
    $announcements_out = array();
    // These $_REQUEST values will get used in the sort template so they are assigned to normal variables
    $perpage = $vbulletin->input->clean_gpc('r', 'perpage', TYPE_UINT);
    $pagenumber = $vbulletin->input->clean_gpc('r', 'pagenumber', TYPE_UINT);
    $daysprune = $vbulletin->input->clean_gpc('r', 'daysprune', TYPE_INT);
    $sortfield = $vbulletin->input->clean_gpc('r', 'sortfield', TYPE_STR);
    // get permission to view forum
    $_permsgetter_ = 'forumdisplay';
    $forumperms = fetch_permissions($foruminfo['forumid']);
    if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canview'])) {
        json_error(ERR_NO_PERMISSION);
    }
    // disable thread preview if we can't view threads
    if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads'])) {
        $vbulletin->options['threadpreview'] = 0;
    }
    // check if there is a forum password and if so, ensure the user has it set
    verify_forum_password($foruminfo['forumid'], $foruminfo['password']);
    // verify that we are at the canonical SEO url
    // and redirect to this if not
    //verify_seo_url('forum', $foruminfo, array('pagenumber' => $_REQUEST['pagenumber']));
    // get vbulletin->iforumcache - for use by makeforumjump and forums list
    // fetch the forum even if they are invisible since its needed
    // for the title but we'll unset that further down
    // also fetch subscription info for $show['subscribed'] variable
    cache_ordered_forums(1, 1, $vbulletin->userinfo['userid']);
    $show['newthreadlink'] = iif(!$show['search_engine'] and $foruminfo['allowposting'], true, false);
    $show['threadicons'] = iif($foruminfo['allowicons'], true, false);
    $show['threadratings'] = iif($foruminfo['allowratings'], true, false);
    $show['subscribed_to_forum'] = $vbulletin->forumcache["{$foruminfo['forumid']}"]['subscribeforumid'] != '' ? true : false;
    if (!$daysprune) {
        if ($vbulletin->userinfo['daysprune']) {
            $daysprune = $vbulletin->userinfo['daysprune'];
        } else {
            $daysprune = iif($foruminfo['daysprune'], $foruminfo['daysprune'], 30);
        }
    }
    $daysprune = -1;
    // FRNR
    // ### GET FORUMS, PERMISSIONS, MODERATOR iCACHES ########################
    cache_moderators();
    // draw nav bar
    $navbits = array();
    $navbits[$vbulletin->options['forumhome'] . '.php' . $vbulletin->session->vars['sessionurl_q']] = $vbphrase['forum'];
    $parentlist = array_reverse(explode(',', substr($foruminfo['parentlist'], 0, -3)));
    foreach ($parentlist as $forumID) {
        $forumTitle = $vbulletin->forumcache["{$forumID}"]['title'];
        $navbits[fetch_seo_url('forum', array('forumid' => $forumID, 'title' => $forumTitle))] = $forumTitle;
    }
    // pop the last element off the end of the $nav array so that we can show it without a link
    array_pop($navbits);
    $navbits[''] = $foruminfo['title'];
    $navbits = construct_navbits($navbits);
    $navbar = render_navbar_template($navbits);
    $moderatorslist = '';
    $listexploded = explode(',', $foruminfo['parentlist']);
    $showmods = array();
    $show['moderators'] = false;
    $totalmods = 0;
    foreach ($listexploded as $parentforumid) {
        if (!$imodcache["{$parentforumid}"] or $parentforumid == -1) {
            continue;
        }
        foreach ($imodcache["{$parentforumid}"] as $moderator) {
            if ($showmods["{$moderator['userid']}"] === true) {
                continue;
            }
            $showmods["{$moderator['userid']}"] = true;
            $show['comma_leader'] = $moderatorslist != '';
            $show['moderators'] = true;
            $totalmods++;
        }
    }
    // ### BUILD FORUMS LIST #################################################
    // get an array of child forum ids for this forum
    $foruminfo['childlist'] = explode(',', $foruminfo['childlist']);
    // define max depth for forums display based on $vbulletin->options[forumhomedepth]
    define('MAXFORUMDEPTH', $vbulletin->options['forumdisplaydepth']);
    if (($vbulletin->options['showforumusers'] == 1 or $vbulletin->options['showforumusers'] == 2 or $vbulletin->options['showforumusers'] > 2 and $vbulletin->userinfo['userid']) and !$show['search_engine']) {
        $datecut = TIMENOW - $vbulletin->options['cookietimeout'];
        $forumusers = $db->query_read_slave("\n    \t\tSELECT user.username, (user.options & " . $vbulletin->bf_misc_useroptions['invisible'] . ") AS invisible, user.usergroupid,\n    \t\t\tsession.userid, session.inforum, session.lastactivity, session.badlocation,\n    \t\t\tIF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid\n    \t\tFROM " . TABLE_PREFIX . "session AS session\n    \t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = session.userid)\n    \t\tWHERE session.lastactivity > {$datecut}\n    \t\tORDER BY" . iif($vbulletin->options['showforumusers'] == 1 or $vbulletin->options['showforumusers'] == 3, " username ASC,") . " lastactivity DESC\n    \t");
        $numberregistered = 0;
        $numberguest = 0;
        $doneuser = array();
        if ($vbulletin->userinfo['userid']) {
            // fakes the user being in this forum
            $loggedin = array('userid' => $vbulletin->userinfo['userid'], 'username' => $vbulletin->userinfo['username'], 'invisible' => $vbulletin->userinfo['invisible'], 'invisiblemark' => $vbulletin->userinfo['invisiblemark'], 'inforum' => $foruminfo['forumid'], 'lastactivity' => TIMENOW, 'musername' => $vbulletin->userinfo['musername']);
            $numberregistered = 1;
            fetch_online_status($loggedin);
            $show['comma_leader'] = false;
            $doneuser["{$vbulletin->userinfo['userid']}"] = 1;
        }
        $inforum = array();
        // this require the query to have lastactivity ordered by DESC so that the latest location will be the first encountered.
        while ($loggedin = $db->fetch_array($forumusers)) {
            if ($loggedin['badlocation']) {
                continue;
            }
            if (empty($doneuser["{$loggedin['userid']}"])) {
                if (in_array($loggedin['inforum'], $foruminfo['childlist']) and $loggedin['inforum'] != -1) {
                    if (!$loggedin['userid']) {
                        // this is a guest
                        $numberguest++;
                        $inforum["{$loggedin['inforum']}"]++;
                    } else {
                        $numberregistered++;
                        $inforum["{$loggedin['inforum']}"]++;
                        if (fetch_online_status($loggedin)) {
                            fetch_musername($loggedin);
                            $show['comma_leader'] = $activeusers != '';
                        }
                    }
                }
                if ($loggedin['userid']) {
                    $doneuser["{$loggedin['userid']}"] = 1;
                }
            }
        }
        if (!$vbulletin->userinfo['userid']) {
            $numberguest = $numberguest == 0 ? 1 : $numberguest;
        }
        $totalonline = $numberregistered + $numberguest;
        unset($joingroupid, $key, $datecut, $invisibleuser, $userinfo, $userid, $loggedin, $index, $value, $forumusers, $parentarray);
        $show['activeusers'] = true;
    } else {
        $show['activeusers'] = false;
    }
    // #############################################################################
    // get read status for this forum and children
    $unreadchildforums = 0;
    foreach ($foruminfo['childlist'] as $val) {
        if ($val == -1 or $val == $foruminfo['forumid']) {
            continue;
        }
        if ($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) {
            $lastread_child = max($vbulletin->forumcache["{$val}"]['forumread'], TIMENOW - $vbulletin->options['markinglimit'] * 86400);
        } else {
            $lastread_child = max(intval(fetch_bbarray_cookie('forum_view', $val)), $vbulletin->userinfo['lastvisit']);
        }
        if ($vbulletin->forumcache["{$val}"]['lastpost'] > $lastread_child) {
            $unreadchildforums = 1;
            break;
        }
    }
    $forumbits = fr_construct_forum_bit($forumid);
    // admin tools
    $show['post_queue'] = can_moderate($foruminfo['forumid'], 'canmoderateposts');
    $show['attachment_queue'] = can_moderate($foruminfo['forumid'], 'canmoderateattachments');
    $show['mass_move'] = can_moderate($foruminfo['forumid'], 'canmassmove');
    $show['mass_prune'] = can_moderate($foruminfo['forumid'], 'canmassprune');
    $show['post_new_announcement'] = can_moderate($foruminfo['forumid'], 'canannounce');
    $show['addmoderator'] = $permissions['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel'];
    $show['adminoptions'] = ($show['post_queue'] or $show['attachment_queue'] or $show['mass_move'] or $show['mass_prune'] or $show['addmoderator'] or $show['post_new_announcement']);
    $navpopup = array('id' => 'forumdisplay_navpopup', 'title' => $foruminfo['title_clean'], 'link' => fetch_seo_url('forum', $foruminfo));
    construct_quick_nav($navpopup);
    /////////////////////////////////
    if ($foruminfo['cancontainthreads']) {
        /////////////////////////////////
        if ($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) {
            $foruminfo['forumread'] = $vbulletin->forumcache["{$foruminfo['forumid']}"]['forumread'];
            $lastread = max($foruminfo['forumread'], TIMENOW - $vbulletin->options['markinglimit'] * 86400);
        } else {
            $bbforumview = intval(fetch_bbarray_cookie('forum_view', $foruminfo['forumid']));
            $lastread = max($bbforumview, $vbulletin->userinfo['lastvisit']);
        }
        // Inline Moderation
        $show['movethread'] = can_moderate($forumid, 'canmanagethreads') ? true : false;
        $show['deletethread'] = (can_moderate($forumid, 'candeleteposts') or can_moderate($forumid, 'canremoveposts')) ? true : false;
        $show['approvethread'] = can_moderate($forumid, 'canmoderateposts') ? true : false;
        $show['openthread'] = can_moderate($forumid, 'canopenclose') ? true : false;
        $show['inlinemod'] = ($show['movethread'] or $show['deletethread'] or $show['approvethread'] or $show['openthread']) ? true : false;
        $show['spamctrls'] = ($show['inlinemod'] and $show['deletethread']);
        $url = $show['inlinemod'] ? SCRIPTPATH : '';
        // fetch popup menu
        if ($show['popups'] and $show['inlinemod']) {
        } else {
            $threadadmin_imod_thread_menu = '';
        }
        // get announcements
        $announcebits = '';
        if ($show['threadicons'] and $show['inlinemod']) {
            $announcecolspan = 6;
        } else {
            if (!$show['threadicons'] and !$show['inlinemod']) {
                $announcecolspan = 4;
            } else {
                $announcecolspan = 5;
            }
        }
        $mindate = TIMENOW - 2592000;
        // 30 days
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        $announcements = $db->query_read_slave("\n    \t\tSELECT\n    \t\t\tannouncement.announcementid, startdate, title, announcement.views,\n    \t\t\tuser.username, user.userid, user.usertitle, user.customtitle, user.usergroupid,\n    \t\t\tIF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid\n    \t\t\t" . ($vbulletin->userinfo['userid'] ? ", NOT ISNULL(announcementread.announcementid) AS readannounce" : "") . "\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "announcement AS announcement\n    \t\t" . ($vbulletin->userinfo['userid'] ? "LEFT JOIN " . TABLE_PREFIX . "announcementread AS announcementread ON (announcementread.announcementid = announcement.announcementid AND announcementread.userid = " . $vbulletin->userinfo['userid'] . ")" : "") . "\n    \t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = announcement.userid)\n    \t\t{$hook_query_joins}\n    \t\tWHERE startdate <= " . TIMENOW . "\n    \t\t\tAND enddate >= " . TIMENOW . "\n    \t\t\tAND " . fetch_forum_clause_sql($foruminfo['forumid'], 'forumid') . "\n    \t\t\t{$hook_query_where}\n    \t\tORDER BY startdate DESC, announcement.announcementid DESC\n    \t\t" . iif($vbulletin->options['oneannounce'], "LIMIT 1"));
        while ($announcement = $db->fetch_array($announcements)) {
            fetch_musername($announcement);
            $announcement['title'] = fetch_censored_text($announcement['title']);
            $announcement['postdate'] = vbdate($vbulletin->options['dateformat'], $announcement['startdate']);
            if ($announcement['readannounce'] or $announcement['startdate'] <= $mindate) {
                $announcement['statusicon'] = 'old';
            } else {
                $announcement['statusicon'] = 'new';
            }
            $announcement['views'] = vb_number_format($announcement['views']);
            $announcementidlink = iif(!$vbulletin->options['oneannounce'], "&amp;a={$announcement['announcementid']}");
            // FRNR START
            if ($pagenumber == 1) {
                $avatarurl = '';
                $userinfoavatar = fetch_userinfo($announcement['userid'], FETCH_USERINFO_AVATAR);
                fetch_avatar_from_userinfo($userinfoavatar, true, false);
                if ($userinfoavatar['avatarurl'] != '') {
                    $avatarurl = process_avatarurl($userinfoavatar['avatarurl']);
                }
                unset($userinfoavatar);
                $tmp = array('thread_id' => $foruminfo['forumid'], 'announcement' => 1, 'new_posts' => $announcement['readannounce'] ? 0 : 1, 'thread_title' => prepare_utf8_string(strip_tags($announcement['title'])), 'thread_preview' => prepare_utf8_string(preview_chop(html_entity_decode($announcement['pagetext']), FR_PREVIEW_LEN)), 'post_userid' => $announcement['userid'], 'post_lastposttime' => prepare_utf8_string(date_trunc($announcement['postdate'])), 'post_username' => prepare_utf8_string(strip_tags($announcement['username'])));
                if ($avatarurl != '') {
                    $tmp['avatarurl'] = $avatarurl;
                }
                $announcements_out[] = $tmp;
            }
            // FRNR END
        }
        // display threads
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewothers'])) {
            $limitothers = "AND postuserid = " . $vbulletin->userinfo['userid'] . " AND " . $vbulletin->userinfo['userid'] . " <> 0";
        } else {
            $limitothers = '';
        }
        if (can_moderate($foruminfo['forumid'])) {
            $redirectjoin = "LEFT JOIN " . TABLE_PREFIX . "threadredirect AS threadredirect ON(thread.open = 10 AND thread.threadid = threadredirect.threadid)";
        } else {
            $redirectjoin = '';
        }
        // filter out deletion notices if can't be seen
        if ($forumperms & $vbulletin->bf_ugp_forumpermissions['canseedelnotice'] or can_moderate($foruminfo['forumid'])) {
            $canseedelnotice = true;
            $deljoin = "LEFT JOIN " . TABLE_PREFIX . "deletionlog AS deletionlog ON(thread.threadid = deletionlog.primaryid AND deletionlog.type = 'thread')";
        } else {
            $canseedelnotice = false;
            $deljoin = '';
        }
        // remove threads from users on the global ignore list if user is not a moderator
        if ($Coventry = fetch_coventry('string') and !can_moderate($foruminfo['forumid'])) {
            $globalignore = "AND postuserid NOT IN ({$Coventry}) ";
        } else {
            $globalignore = '';
        }
        // look at thread limiting options
        $stickyids = '';
        $stickycount = 0;
        if ($daysprune != -1) {
            if ($vbulletin->userinfo['userid'] and in_coventry($vbulletin->userinfo['userid'], true)) {
                $tachyjoin = "LEFT JOIN " . TABLE_PREFIX . "tachythreadpost AS tachythreadpost ON " . "(tachythreadpost.threadid = thread.threadid AND tachythreadpost.userid = " . $vbulletin->userinfo['userid'] . ")";
                $datecut = " AND (thread.lastpost >= " . (TIMENOW - $daysprune * 86400) . " OR tachythreadpost.lastpost >= " . (TIMENOW - $daysprune * 86400) . ")";
            } else {
                $datecut = "AND lastpost >= " . (TIMENOW - $daysprune * 86400);
                $tachyjoin = "";
            }
            $show['noposts'] = false;
        } else {
            $tachyjoin = "";
            $datecut = "";
            $show['noposts'] = true;
        }
        // complete form fields on page
        $daysprunesel = iif($daysprune == -1, 'all', $daysprune);
        $daysprunesel = array($daysprunesel => 'selected="selected"');
        $vbulletin->input->clean_array_gpc('r', array('sortorder' => TYPE_NOHTML, 'prefixid' => TYPE_NOHTML));
        // prefix options
        $prefix_options = fetch_prefix_html($foruminfo['forumid'], $vbulletin->GPC['prefixid']);
        $prefix_selected = array('anythread', 'anythread' => '', 'none' => '');
        if ($vbulletin->GPC['prefixid']) {
            //no prefix id
            if ($vbulletin->GPC['prefixid'] == '-1') {
                $prefix_filter = "AND thread.prefixid = ''";
                $prefix_selected['none'] = ' selected="selected"';
            } else {
                if ($vbulletin->GPC['prefixid'] == '-2') {
                    $prefix_filter = "AND thread.prefixid <> ''";
                    $prefix_selected['anyprefix'] = ' selected="selected"';
                } else {
                    $prefix_filter = "AND thread.prefixid = '" . $db->escape_string($vbulletin->GPC['prefixid']) . "'";
                }
            }
        } else {
            $prefix_filter = '';
            $prefix_selected['anythread'] = ' selected="selected"';
        }
        // default sorting methods
        if (empty($sortfield)) {
            $sortfield = $foruminfo['defaultsortfield'];
        }
        if (empty($vbulletin->GPC['sortorder'])) {
            $vbulletin->GPC['sortorder'] = $foruminfo['defaultsortorder'];
        }
        // look at sorting options:
        if ('asc' != ($sortorder = $vbulletin->GPC['sortorder'])) {
            $sqlsortorder = 'DESC';
            $order = array('desc' => 'checked="checked"');
            $vbulletin->GPC['sortorder'] = 'desc';
        } else {
            $sqlsortorder = '';
            $order = array('asc' => 'checked="checked"');
        }
        $sqlsortfield2 = '';
        switch ($sortfield) {
            case 'title':
                $sqlsortfield = 'thread.title';
                break;
            case 'lastpost':
                $sqlsortfield = 'lastpost';
                break;
            case 'replycount':
            case 'views':
                $sqlsortfield = 'views';
            case 'postusername':
                $sqlsortfield = $sortfield;
                break;
            case 'voteavg':
                if ($foruminfo['allowratings']) {
                    $sqlsortfield = 'voteavg';
                    $sqlsortfield2 = 'votenum';
                    break;
                }
            case 'dateline':
                $sqlsortfield = 'thread.dateline';
                break;
                // else, use last post
            // else, use last post
            default:
                $handled = false;
                if (!$handled) {
                    $sqlsortfield = 'lastpost';
                    $sortfield = 'lastpost';
                }
        }
        $sort = array($sortfield => 'selected="selected"');
        $visiblethreads = " AND visible = 1";
        /*if (!can_moderate($forumid, 'canmoderateposts'))
            	{
            		if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canseedelnotice']))
            		{
            			$visiblethreads = " AND visible = 1 ";
            		}
            		else
            		{
            			$visiblethreads = " AND visible IN (1,2)";
            		}
            	}
            	else
            	{
            		$visiblethreads = " AND visible IN (0,1,2)";
        	}*/
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        # Include visible IN (0,1,2) in order to hit upon the 4 column index
        $threadscount = $db->query_first_slave("\n    \t\tSELECT COUNT(*) AS threads, SUM(IF(thread.lastpost > {$lastread} AND open <> 10, 1, 0)) AS newthread\n    \t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "thread AS thread\n    \t\t{$tachyjoin}\n    \t\t{$hook_query_joins}\n    \t\tWHERE forumid = {$foruminfo['forumid']}\n    \t\t\tAND sticky = 0\n    \t\t\t{$prefix_filter}\n    \t\t\t{$visiblethreads}\n    \t\t\t{$globalignore}\n    \t\t\t{$limitothers}\n    \t\t\t{$datecut}\n    \t\t\t{$hook_query_where}\n    \t");
        $totalthreads = $threadscount['threads'];
        $newthreads = $threadscount['newthread'];
        // set defaults
        sanitize_pageresults($totalthreads, $pagenumber, $perpage, 200, $vbulletin->options['maxthreads']);
        // get number of sticky threads for the first page
        // on the first page there will be the sticky threads PLUS the $perpage other normal threads
        // not quite a bug, but a deliberate feature!
        if ($pagenumber == 1) {
            $stickies = $db->query_read_slave("\n    \t\t\tSELECT thread.threadid, lastpost, open\n    \t\t\tFROM " . TABLE_PREFIX . "thread AS thread\n    \t\t\tWHERE forumid = {$foruminfo['forumid']}\n    \t\t\t\tAND sticky = 1\n    \t\t\t\t{$prefix_filter}\n    \t\t\t\t{$visiblethreads}\n    \t\t\t\t{$limitothers}\n    \t\t\t\t{$globalignore}\n    \t\t");
            while ($thissticky = $db->fetch_array($stickies)) {
                $stickycount++;
                if ($thissticky['lastpost'] >= $lastread and $thissticky['open'] != 10) {
                    $newthreads++;
                }
                $stickyids .= ",{$thissticky['threadid']}";
            }
            $db->free_result($stickies);
            unset($thissticky, $stickies);
        }
        $limitlower = ($pagenumber - 1) * $perpage;
        $limitupper = $pagenumber * $perpage;
        if ($limitupper > $totalthreads) {
            $limitupper = $totalthreads;
            if ($limitlower > $totalthreads) {
                $limitlower = $totalthreads - $perpage - 1;
            }
        }
        if ($limitlower < 0) {
            $limitlower = 0;
        }
        if ($foruminfo['allowratings']) {
            $vbulletin->options['showvotes'] = intval($vbulletin->options['showvotes']);
            $votequery = "\n    \t\t\tIF(votenum >= " . $vbulletin->options['showvotes'] . ", votenum, 0) AS votenum,\n    \t\t\tIF(votenum >= " . $vbulletin->options['showvotes'] . " AND votenum > 0, votetotal / votenum, 0) AS voteavg,\n    \t\t";
        } else {
            $votequery = '';
        }
        if ($previewtype == 1) {
            $previewfield = "post.pagetext AS preview, post.username AS lastpost_username, post.userid AS lastpost_userid,";
            $previewjoin = "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.firstpostid)";
        } else {
            $previewfield = "post.pagetext AS preview, post.username AS lastpost_username, post.userid AS lastpost_userid,";
            $previewjoin = "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.lastpostid)";
        }
        if ($vbulletin->userinfo['userid'] and in_coventry($vbulletin->userinfo['userid'], true)) {
            $tachyjoin = "\n    \t\t\tLEFT JOIN " . TABLE_PREFIX . "tachythreadpost AS tachythreadpost ON\n    \t\t\t\t(tachythreadpost.threadid = thread.threadid AND tachythreadpost.userid = " . $vbulletin->userinfo['userid'] . ")\n    \t\t\tLEFT JOIN " . TABLE_PREFIX . "tachythreadcounter AS tachythreadcounter ON\n    \t\t\t\t(tachythreadcounter.threadid = thread.threadid AND tachythreadcounter.userid = " . $vbulletin->userinfo['userid'] . ")\n    \t\t";
            $tachy_columns = "\n    \t\t\tIF(tachythreadpost.userid IS NULL, thread.lastpost, tachythreadpost.lastpost) AS lastpost,\n    \t\t\tIF(tachythreadpost.userid IS NULL, thread.lastposter, tachythreadpost.lastposter) AS lastposter,\n    \t\t\tIF(tachythreadpost.userid IS NULL, thread.lastposterid, tachythreadpost.lastposterid) AS lastposterid,\n    \t\t\tIF(tachythreadpost.userid IS NULL, thread.lastpostid, tachythreadpost.lastpostid) AS lastpostid,\n    \t\t\tIF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount) AS replycount,\n    \t\t\tIF(thread.views<=IF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount), IF(tachythreadcounter.userid IS NULL, thread.replycount, thread.replycount + tachythreadcounter.replycount)+1, thread.views) AS views\n    \t\t";
        } else {
            $tachyjoin = '';
            $tachy_columns = 'thread.lastpost, thread.lastposter, thread.lastposterid, thread.lastpostid, thread.replycount, IF(thread.views<=thread.replycount, thread.replycount+1, thread.views) AS views';
        }
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        $getthreadids = $db->query_read_slave("\n    \t\tSELECT " . iif($sortfield == 'voteavg', $votequery) . " thread.threadid,\n    \t\t\t{$tachy_columns}\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "thread AS thread\n    \t\t{$tachyjoin}\n    \t\t{$hook_query_joins}\n    \t\tWHERE forumid = {$foruminfo['forumid']}\n    \t\t\tAND sticky = 0\n    \t\t\t{$prefix_filter}\n    \t\t\t{$visiblethreads}\n    \t\t\t{$globalignore}\n    \t\t\t{$limitothers}\n    \t\t\t{$datecut}\n    \t\t\t{$hook_query_where}\n    \t\tORDER BY sticky DESC, {$sqlsortfield} {$sqlsortorder}" . (!empty($sqlsortfield2) ? ", {$sqlsortfield2} {$sqlsortorder}" : '') . "\n    \t\tLIMIT {$limitlower}, {$perpage}\n    \t");
        $ids = '';
        while ($thread = $db->fetch_array($getthreadids)) {
            $ids .= ',' . $thread['threadid'];
        }
        $ids .= $stickyids;
        $db->free_result($getthreadids);
        unset($thread, $getthreadids);
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        $threads = $db->query_read_slave("\n    \t\tSELECT {$votequery} {$previewfield}\n    \t\t\tthread.threadid, thread.title AS threadtitle, thread.forumid, pollid, open, postusername, postuserid, thread.iconid AS threadiconid,\n    \t\t\tthread.dateline, notes, thread.visible, sticky, votetotal, thread.attach, {$tachy_columns},\n    \t\t\tthread.prefixid, thread.taglist, hiddencount, deletedcount,\n    \t\t\tuser.usergroupid, user.homepage, user.options AS useroptions, IF(userlist.friend = 'yes', 1, 0) AS isfriend\n    \t\t\t" . (($vbulletin->options['threadsubscribed'] and $vbulletin->userinfo['userid']) ? ", NOT ISNULL(subscribethread.subscribethreadid) AS issubscribed" : "") . "\n    \t\t\t" . ($deljoin ? ", deletionlog.userid AS del_userid, deletionlog.username AS del_username, deletionlog.reason AS del_reason" : "") . "\n    \t\t\t" . (($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) ? ", threadread.readtime AS threadread" : "") . "\n    \t\t\t" . ($redirectjoin ? ", threadredirect.expires" : "") . "\n    \t\t\t{$hook_query_fields}\n    \t\tFROM " . TABLE_PREFIX . "thread AS thread\n    \t\t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON (user.userid = thread.lastposterid)\n    \t\t\tLEFT JOIN " . TABLE_PREFIX . "userlist AS userlist ON (userlist.relationid = user.userid AND userlist.type = 'buddy' AND userlist.userid = " . $vbulletin->userinfo['userid'] . ")\n    \t\t\t{$deljoin}\n    \t\t\t" . (($vbulletin->options['threadsubscribed'] and $vbulletin->userinfo['userid']) ? " LEFT JOIN " . TABLE_PREFIX . "subscribethread AS subscribethread ON(subscribethread.threadid = thread.threadid AND subscribethread.userid = " . $vbulletin->userinfo['userid'] . " AND canview = 1)" : "") . "\n    \t\t\t" . (($vbulletin->options['threadmarking'] and $vbulletin->userinfo['userid']) ? " LEFT JOIN " . TABLE_PREFIX . "threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = " . $vbulletin->userinfo['userid'] . ")" : "") . "\n    \t\t\t{$previewjoin}\n    \t\t\t{$tachyjoin}\n    \t\t\t{$redirectjoin}\n    \t\t\t{$hook_query_joins}\n    \t\tWHERE thread.threadid IN (0{$ids}) {$hook_query_where}\n    \t\tORDER BY sticky DESC, {$sqlsortfield} {$sqlsortorder}" . (!empty($sqlsortfield2) ? ", {$sqlsortfield2} {$sqlsortorder}" : '') . "\n    \t");
        unset($limitothers, $delthreadlimit, $deljoin, $datecut, $votequery, $sqlsortfield, $sqlsortorder, $threadids, $sqlsortfield2);
        // Get Dot Threads
        $dotthreads = fetch_dot_threads_array($ids);
        if ($vbulletin->options['showdots'] and $vbulletin->userinfo['userid']) {
            $show['dotthreads'] = true;
        } else {
            $show['dotthreads'] = false;
        }
        unset($ids);
        $pageinfo = array();
        if ($vbulletin->GPC['prefixid']) {
            $pageinfo['prefixid'] = $vbulletin->GPC['prefixid'];
        }
        if ($vbulletin->GPC['daysprune']) {
            $pageinfo['daysprune'] = $daysprune;
        }
        $show['fetchseo'] = true;
        $oppositesort = $vbulletin->GPC['sortorder'] == 'asc' ? 'desc' : 'asc';
        $pageinfo_voteavg = $pageinfo + array('sort' => 'voteavg', 'order' => 'voteavg' == $sortfield ? $oppositesort : 'desc');
        $pageinfo_title = $pageinfo + array('sort' => 'title', 'order' => 'title' == $sortfield ? $oppositesort : 'asc');
        $pageinfo_postusername = $pageinfo + array('sort' => 'postusername', 'order' => 'postusername' == $sortfield ? $oppositesort : 'asc');
        $pageinfo_flastpost = $pageinfo + array('sort' => 'lastpost', 'order' => 'lastpost' == $sortfield ? $oppositesort : 'asc');
        $pageinfo_replycount = $pageinfo + array('sort' => 'replycount', 'order' => 'replycount' == $sortfield ? $oppositesort : 'desc');
        $pageinfo_views = $pageinfo + array('sort' => 'views', 'order' => 'views' == $sortfield ? $oppositesort : 'desc');
        $pageinfo_sort = $pageinfo + array(sort => $sortfield, 'order' => $oppositesort, 'pp' => $perpage, 'page' => $pagenumber);
        if ($totalthreads > 0 or $stickyids) {
            if ($totalthreads > 0) {
                $limitlower++;
            }
            // check to see if there are any threads to display. If there are, do so, otherwise, show message
            if ($vbulletin->options['threadpreview'] > 0) {
                // Get Buddy List
                $buddy = array();
                if (trim($vbulletin->userinfo['buddylist'])) {
                    $buddylist = preg_split('/( )+/', trim($vbulletin->userinfo['buddylist']), -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($buddylist as $buddyuserid) {
                        $buddy["{$buddyuserid}"] = 1;
                    }
                }
                DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
                // Get Ignore Users
                $ignore = array();
                if (trim($vbulletin->userinfo['ignorelist'])) {
                    $ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($ignorelist as $ignoreuserid) {
                        if (!$buddy["{$ignoreuserid}"]) {
                            $ignore["{$ignoreuserid}"] = 1;
                        }
                    }
                }
                DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
            }
            $show['threads'] = true;
            $threadbits = '';
            $threadbits_sticky = '';
            $counter = 0;
            $toread = 0;
            while ($thread = $db->fetch_array($threads)) {
                // AND $counter++ < $perpage)
                // build thread data
                $thread = process_thread_array($thread, $lastread, $foruminfo['allowicons']);
                $realthreadid = $thread['realthreadid'];
                if ($thread['sticky']) {
                    $threadbit =& $threadbits_sticky;
                } else {
                    $threadbit =& $threadbits;
                }
                // Soft Deleted Thread
                if ($thread['visible'] == 2) {
                    $thread['deletedcount']++;
                    $show['threadtitle'] = (can_moderate($forumid) or $vbulletin->userinfo['userid'] != 0 and $vbulletin->userinfo['userid'] == $thread['postuserid']) ? true : false;
                    $show['deletereason'] = !empty($thread['del_reason']) ? true : false;
                    $show['viewthread'] = can_moderate($forumid) ? true : false;
                    $show['managethread'] = (can_moderate($forumid, 'candeleteposts') or can_moderate($forumid, 'canremoveposts')) ? true : false;
                    $show['moderated'] = ($thread['hiddencount'] > 0 and can_moderate($forumid, 'canmoderateposts')) ? true : false;
                    $show['deletedthread'] = $canseedelnotice;
                } else {
                    if (!$thread['visible']) {
                        $thread['hiddencount']++;
                    }
                    $show['moderated'] = ($thread['hiddencount'] > 0 and can_moderate($forumid, 'canmoderateposts')) ? true : false;
                    $show['deletedthread'] = ($thread['deletedcount'] > 0 and $canseedelnotice) ? true : false;
                    $pageinfo_lastpage = array();
                    if ($show['pagenavmore']) {
                        $pageinfo_lastpage['page'] = $thread['totalpages'];
                    }
                    $pageinfo_newpost = array('goto' => 'newpost');
                    $pageinfo_lastpost = array('p' => $thread['lastpostid']);
                    // prepare the member action drop-down menu
                    $memberaction_dropdown = construct_memberaction_dropdown(fetch_lastposter_userinfo($thread));
                }
                // FRNR Start
                $avatarurl = '';
                if ($thread['lastpost_userid'] > 0) {
                    $userinfoavatar = fetch_userinfo($thread['lastpost_userid'], FETCH_USERINFO_AVATAR);
                    fetch_avatar_from_userinfo($userinfoavatar, true, false);
                    if ($userinfoavatar['avatarurl'] != '') {
                        $avatarurl = process_avatarurl($userinfoavatar['avatarurl']);
                    }
                    unset($userinfoavatar);
                }
                $tmp = array('thread_id' => $thread['threadid'], 'new_posts' => $show['gotonewpost'] ? 1 : 0, 'forum_id' => $thread['forumid'], 'total_posts' => $thread['totalposts'] ? $thread['totalposts'] : 0, 'thread_title' => prepare_utf8_string(strip_tags($thread['threadtitle'])), 'thread_preview' => prepare_utf8_string(preview_chop(html_entity_decode($thread['preview']), FR_PREVIEW_LEN)), 'post_userid' => $thread['lastpost_userid'], 'post_lastposttime' => prepare_utf8_string(date_trunc($thread['lastpostdate']) . ' ' . $thread['lastposttime']), 'post_username' => prepare_utf8_string(strip_tags($thread['lastpost_username'])));
                if ($avatarurl != '') {
                    $tmp['avatarurl'] = $avatarurl;
                }
                if ($thread['prefixid']) {
                    $tmp['prefix'] = prepare_utf8_string(strip_tags($vbphrase["prefix_{$thread['prefixid']}_title_plain"]));
                }
                if ($thread['attach']) {
                    $tmp['attach'] = true;
                }
                if ($thread['pollid']) {
                    $tmp['poll'] = true;
                }
                if ($thread['open'] == 10) {
                    // Special case for redirect threads
                    $tmp = array_merge($tmp, array('post_userid' => $thread['postuserid'], 'post_username' => prepare_utf8_string(strip_tags($thread['postusername'])), 'poll' => false));
                }
                if ($thread['sticky']) {
                    $thread_data_sticky[] = $tmp;
                } else {
                    $thread_data[] = $tmp;
                }
                // FRNR Stop
            }
            $db->free_result($threads);
            unset($thread, $counter);
            $pageinfo_pagenav = array();
            if (!empty($vbulletin->GPC['perpage'])) {
                $pageinfo_pagenav['pp'] = $perpage;
            }
            if (!empty($vbulletin->GPC['prefixid'])) {
                $pageinfo_pagenav['prefixid'] = $vbulletin->GPC['prefixid'];
            }
            if (!empty($vbulletin->GPC['sortfield'])) {
                $pageinfo_pagenav['sort'] = $sortfield;
            }
            if (!empty($vbulletin->GPC['sortorder'])) {
                $pageinfo_pagenav['order'] = $vbulletin->GPC['sortorder'];
            }
            if (!empty($vbulletin->GPC['daysprune'])) {
                $pageinfo_pagenav['daysprune'] = $daysprune;
            }
            $pagenav = construct_page_nav($pagenumber, $perpage, $totalthreads, 'forumdisplay.php?' . $vbulletin->session->vars['sessionurl'] . "f={$foruminfo['forumid']}", '', '', 'forum', $foruminfo, $pageinfo_pagenav);
        }
        unset($threads, $dotthreads);
        // get colspan for bottom bar
        $foruminfo['bottomcolspan'] = 5;
        if ($foruminfo['allowicons']) {
            $foruminfo['bottomcolspan']++;
        }
        if ($show['inlinemod']) {
            $foruminfo['bottomcolspan']++;
        }
        $show['threadslist'] = true;
        /////////////////////////////////
    } else {
        $show['threadslist'] = false;
        $canpost = false;
        // FRNR
    }
    /////////////////////////////////
    if (!$vbulletin->GPC['prefixid'] and $newthreads < 1 and $unreadchildforums < 1) {
        mark_forum_read($foruminfo, $vbulletin->userinfo['userid'], TIMENOW);
    }
    // FNRN Below
    $out = array();
    if (is_array($thread_data) && count($thread_data) > 0) {
        $out['threads'] = $thread_data;
    } else {
        $out['threads'] = array();
    }
    if (is_array($thread_data_sticky) && count($thread_data_sticky) > 0) {
        $out['threads_sticky'] = $thread_data_sticky;
        $out['total_sticky_threads'] = count($thread_data_sticky);
    } else {
        $out['threads_sticky'] = array();
        $out['total_sticky_threads'] = 0;
    }
    // Announcements become #1 on the threads
    if (is_array($announcements_out) && count($announcements_out) == 1) {
        array_unshift($out['threads'], $announcements_out[0]);
        $totalthreads++;
    }
    $out['total_threads'] = $totalthreads ? $totalthreads : 0;
    if ($forumbits) {
        $out['forums'] = $forumbits;
    } else {
        $out['forums'] = array();
    }
    $out['canpost'] = $canpost ? 1 : 0;
    $out['canattach'] = ($forumperms & $vbulletin->bf_ugp_forumpermissions['canpostattachment'] and $vbulletin->userinfo['userid']);
    // Get thread prefixes for this forum (if any)
    $prefix_out = array();
    if ($prefixsets = fetch_prefix_array($forumid)) {
        foreach ($prefixsets as $prefixsetid => $prefixes) {
            $optgroup_options = '';
            foreach ($prefixes as $prefixid => $prefix) {
                if ($permcheck and !can_use_prefix($prefixid, $prefix['restrictions'])) {
                    continue;
                }
                $optionvalue = $prefixid;
                $optiontitle = htmlspecialchars_uni($vbphrase["prefix_{$prefixid}_title_plain"]);
                $prefix_out[] = array('prefixid' => $prefixid, 'prefixcaption' => prepare_utf8_string($optiontitle));
            }
        }
    }
    if ($foruminfo['options'] & $vbulletin->bf_misc_forumoptions['prefixrequired']) {
        $out['prefixrequired'] = true;
    } else {
        $out['prefixrequired'] = false;
    }
    $out['prefixes'] = $prefix_out;
    return $out;
}
Example #19
0
 /**
  * Returns an array of smilie information.
  *
  * @return array Smilie information corresponding to the data in the "smilie" field,
  *               with one extra column "smilielen".
  */
 public function fetchSmilies()
 {
     if ($smilies = vB::getDatastore()->get_value('smiliecache')) {
         // we can get the smilies from the smiliecache datastore
         DEVDEBUG('returning smilies from the datastore');
         return $smilies;
     } else {
         // we have to get the smilies from the database
         DEVDEBUG('querying for smilies');
         return vB::getDbAssertor()->getRows('fetchSmilies', array(vB_dB_Query::QUERYTYPE_KEY => vB_dB_Query::QUERY_STORED));
     }
 }
Example #20
0
            $show['hybridmode'] = false;
            $show['linearmode'] = false;
            break;
        case 2:
            $show['threadedmode'] = false;
            $show['hybridmode'] = true;
            $show['linearmode'] = false;
            break;
        default:
            $show['threadedmode'] = false;
            $show['hybridmode'] = false;
            $show['linearmode'] = true;
            break;
    }
} else {
    DEVDEBUG('Threadedmode disabled by admin');
    $threadedmode = 0;
}
($hook = vBulletinHook::fetch_hook('threadmanage_start')) ? eval($hook) : false;
// ############################### start do open / close thread ###############################
if ($_POST['do'] == 'openclosethread') {
    if ($threadinfo['isdeleted'] and !can_moderate($threadinfo['forumid'], 'candeleteposts') or !$threadinfo['visible'] and !can_moderate($threadinfo['forumid'], 'canmoderateposts')) {
        if (can_moderate($threadinfo['forumid'])) {
            print_no_permission();
        } else {
            eval(standard_error(fetch_error('invalidid', $idname, $vbulletin->options['contactuslink'])));
        }
    }
    // permission check
    if (!can_moderate($threadinfo['forumid'], 'canopenclose')) {
        if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canopenclose'])) {
Example #21
0
                $display['prefixes']["{$key}"] = '<b><u>' . htmlspecialchars_uni($vbphrase["prefix_{$prefixid}_title_plain"]) . '</u></b>';
            } else {
                unset($display['prefixes']["{$key}"]);
            }
        }
        $display_prefixes = implode(" {$vbphrase['or']} ", $display['prefixes']);
    } else {
        $display_prefixes = '';
    }
    $starteronly =& $display['options']['starteronly'];
    $childforums =& $display['options']['childforums'];
    $action =& $display['options']['action'];
    if ($vbulletin->options['fulltextsearch']) {
        DEVDEBUG('FULLTEXT Search');
    } else {
        DEVDEBUG('Default Search');
    }
    $searchminutes = floor((TIMENOW - $search['dateline']) / 60);
    if ($searchminutes >= 1) {
        $show['generated'] = true;
    }
    if ($display['options']['action'] != 'getnew' and $display['options']['action'] != 'getdaily' and $titlesearchurl = fetch_titleonly_url(unserialize($search['searchterms']))) {
        $show['titleonlysearch'] = true;
    }
    // select the correct part of the forum jump menu
    $frmjmpsel['search'] = 'class="fjsel" selected="selected"';
    construct_forum_jump();
    // add to the navbits
    $navbits[''] = $vbphrase['search_results'];
    $templatename = 'search_results';
}
Example #22
0
		$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,
Example #23
0
         foreach ($buddylist as $buddyuserid) {
             $buddy["{$buddyuserid}"] = 1;
         }
     }
     DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
     // Get Ignore Users
     $ignore = array();
     if (trim($vbulletin->userinfo['ignorelist'])) {
         $ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
         foreach ($ignorelist as $ignoreuserid) {
             if (!$buddy["{$ignoreuserid}"]) {
                 $ignore["{$ignoreuserid}"] = 1;
             }
         }
     }
     DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
 }
 $foruminfo['allowratings'] = true;
 $show['threadratings'] = true;
 $show['threadrating'] = true;
 while ($thread = $db->fetch_array($threads)) {
     // unset the thread preview if it can't be seen
     $forumperms = fetch_permissions($thread['forumid']);
     if ($vbulletin->options['threadpreview'] > 0 and !($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads'])) {
         $thread['preview'] = '';
     }
     $threadid = $thread['threadid'];
     // build thread data
     $thread = process_thread_array($thread, $lastread["{$thread['forumid']}"]);
     ($hook = vBulletinHook::fetch_hook('threadbit_display')) ? eval($hook) : false;
     // Soft Deleted Thread
Example #24
0
{
	$show['birthdays'] = false;
}

// ### TODAY'S EVENTS #################################################
if ($vbulletin->options['showevents'])
{
	require_once(DIR . '/includes/functions_calendar.php');

	$future = gmdate('n-j-Y' , TIMENOW + 86400 + 86400 * $vbulletin->options['showevents']);

	if (!is_array($vbulletin->eventcache) OR $future != $vbulletin->eventcache['date'])
	{
		// Need to update!
		$eventstore = build_events();
		DEVDEBUG('Updated Events');
	}
	else
	{
		$eventstore = $vbulletin->eventcache;
	}

	unset($eventstore['date']);
	$events = array();
	$eventcount = 0;
	$holiday_calendarid = 0;

	foreach ($eventstore AS $eventid => $eventinfo)
	{
		$offset = $eventinfo['dst'] ? $vbulletin->userinfo['timezoneoffset'] : $vbulletin->userinfo['tzoffset'];
		$eventstore["$eventid"]['dateline_from_user'] = $eventinfo['dateline_from_user'] = $eventinfo['dateline_from'] + $offset * 3600;
Example #25
0
<div class="tborder" style="width:90%; text-align:<?php 
    echo $stylevar['left'];
    ?>
">
<div class="tcat" style="padding:4px; text-align:center"><?php 
    echo $pagehelplink;
    ?>
<b><?php 
    echo $vbphrase['style_manager'];
    ?>
</b></div>
<div class="stylebg">

<?php 
    if (!empty($vbulletin->GPC['expandset'])) {
        DEVDEBUG("Querying master template ids");
        $masters = $db->query_read("\n\t\t\tSELECT templateid, title\n\t\t\tFROM " . TABLE_PREFIX . "template\n\t\t\tWHERE templatetype = 'template'\n\t\t\t\tAND styleid = -1\n\t\t\tORDER BY title\n\t\t");
        while ($master = $db->fetch_array($masters)) {
            $masterset["{$master['title']}"] = $master['templateid'];
        }
    } else {
        $masterset = array();
    }
    $LINKEXTRA = '';
    if (!empty($vbulletin->GPC['group'])) {
        $LINKEXTRA .= "&amp;group=" . $vbulletin->GPC['group'];
    }
    if (!empty($vbulletin->GPC['searchstring'])) {
        $LINKEXTRA .= "&amp;searchstring=" . urlencode($vbulletin->GPC['searchstring']) . "&amp;searchset=" . $vbulletin->GPC['searchset'];
    }
    if ($vbulletin->debug) {
Example #26
0
/**
* Returns whether or not the given user can perform a specific moderation action in the specified forum
*
* @param	integer	Forum ID
* @param	string	If you want to check a particular moderation permission, name it here
* @param	integer	User ID
* @param	string	Comma separated list of usergroups to which the user belongs
*
* @return	boolean
*/
function can_moderate($forumid = 0, $do = '', $userid = -1, $usergroupids = '')
{
	global $vbulletin, $imodcache;
	static $modcache;
	static $permissioncache;

	$userid = intval($userid);
	$forumid = intval($forumid);

	if ($do)
	{
			if (isset($vbulletin->bf_misc_moderatorpermissions["$do"]))
			{
					$permission =& $vbulletin->bf_misc_moderatorpermissions["$do"];
					$set = 'permissions';
			}
			else if (isset($vbulletin->bf_misc_moderatorpermissions2["$do"]))
			{
					$permission =& $vbulletin->bf_misc_moderatorpermissions2["$do"];
					$set = 'permissions2';
			}
	}

	if ($userid == -1)
	{
		$userid = $vbulletin->userinfo['userid'];
	}

	if ($userid == 0)
	{
		return false;
	}

	$issupermod = false;
	if ($userid == $vbulletin->userinfo['userid'])
	{
		if ($vbulletin->userinfo['permissions']['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['ismoderator'])
		{
			DEVDEBUG('  USER IS A SUPER MODERATOR');
			$issupermod = true;
		}
	}
	else
	{
		if (!$usergroupids)
		{
			$tempuser = $vbulletin->db->query_first_slave("SELECT usergroupid, membergroupids FROM " . TABLE_PREFIX . "user WHERE userid = $userid");
			if (!$tempuser)
			{
				return false;
			}
			$usergroupids = $tempuser['usergroupid'] . iif(trim($tempuser['membergroupids']), ",$tempuser[membergroupids]");
		}
		$supermodcheck = $vbulletin->db->query_first_slave("
			SELECT usergroupid
			FROM " . TABLE_PREFIX . "usergroup
			WHERE usergroupid IN ($usergroupids)
				AND (adminpermissions & " . $vbulletin->bf_ugp_adminpermissions['ismoderator'] . ") != 0
			LIMIT 1
		");
		if ($supermodcheck)
		{
			DEVDEBUG('  USER IS A SUPER MODERATOR');
			$issupermod = true;
		}

	}

	if ($forumid == 0)
	{ // just check to see if the user is a moderator of any forum
		if (isset($imodcache))
		{ // loop through imodcache to find user
			DEVDEBUG("looping through imodcache to find userid $userid");
			foreach ($imodcache AS $forummodid => $forummods)
			{
				if (isset($forummods["$userid"]) AND ($forummodid != -1 OR $issupermod))
				{
					if (!$do)
					{
						return true;
					}
					else if ($forummods["$userid"]["$set"] & $permission)
					{
						return true;
					}
				}
			}

			if ($issupermod AND !isset($imodcache['-1']["$userid"]))
			{
				// super mod without a record -- has all perms
				return true;
			}

			return false;
		}
		else
		{ // imodcache is not set - do a query

			if (isset($modcache["$userid"]["$do"]))
			{
				return $modcache["$userid"]["$do"];
			}

			if ($issupermod AND ($permissioncache["$userid"]['hassuperrecord'] === false))
			{
				$modcache["$userid"]["$do"] = 1;
				return $modcache["$userid"]["$do"];
			}

			if ($do AND isset($permissioncache["$userid"]["$set"]))
			{
				if ($set == 'permissions2')
				{
					$modcache["$userid"]["$do"] = $permissioncache["$userid"]["$set"] & $vbulletin->bf_misc_moderatorpermissions2["$do"];
					return $modcache["$userid"]["$do"];
				}
				else
				{
					$modcache["$userid"]["$do"] = $permissioncache["$userid"]["$set"] & $vbulletin->bf_misc_moderatorpermissions["$do"];
					return $modcache["$userid"]["$do"];
				}
			}

			$modcache["$userid"]["$do"] = 0;

			DEVDEBUG('QUERY: is the user a moderator (any forum)?');
			$ismod_all = $vbulletin->db->query_read_slave("
				SELECT forumid, moderatorid, permissions, permissions2
				FROM " . TABLE_PREFIX . "moderator
				WHERE userid = $userid" . (!$issupermod ? ' AND forumid != -1' : '')
			);

			if (!isset($permissioncache["$userid"]))
			{
				$permissioncache["$userid"]['permissions'] = 0;
				$permissioncache["$userid"]['permissions2'] = 0;
			}

			while ($ismod = $vbulletin->db->fetch_array($ismod_all))
			{
				$permissioncache["$userid"]['permissions'] = $permissioncache["$userid"]['permissions'] | $ismod['permissions'];
				$permissioncache["$userid"]['permissions2'] = $permissioncache["$userid"]['permissions2'] | $ismod['permissions2'];

				if ($ismod['forumid'] == '-1')
				{
					$permissioncache["$userid"]['hassuperrecord'] = true;
				}
				if ($do)
				{
					if ($ismod["$set"] & $permission)
					{
						$modcache["$userid"]["$do"] = 1;
					}
				}
				else
				{
					$modcache["$userid"]["$do"] = 1;
				}
			}
			$vbulletin->db->free_result($ismod_all);

			if ($issupermod AND !isset($permissioncache["$userid"]['hassuperrecord']))
			{
				$permissioncache["$userid"]['hassuperrecord'] = false;
				$modcache["$userid"]["$do"] = 1;
			}

			return $modcache["$userid"]["$do"];
		}
	}
	else
	{ // check to see if user is a moderator of specific forum
		$getmodperms = fetch_moderator_permissions($forumid, $userid, $issupermod);

		if (($getmodperms['permissions'] OR $getmodperms['permissions2']) AND empty($do))
		{ // check if user is a mod - no specific permission required
			return true;
		}
		else
		{ // check if user is a mod and has permissions to '$do'
			if ($getmodperms["$set"] & $permission)
			{
				return true;
			}
			else
			{
				$return = false;
				if (!isset($permission))
				{
					($hook = vBulletinHook::fetch_hook('can_moderate_forum')) ? eval($hook) : false;
				}
				return $return;
			}  // if has perms for this action
		}// if is mod for forum and no action set
	} // if forumid=0
}
Example #27
0
function do_get_subscriptions()
{
    global $vbulletin, $db, $show, $vbphrase, $permissions, $subscribecounters;
    $vbulletin->options['threadpreview'] = FR_PREVIEW_LEN;
    if (!$vbulletin->userinfo['userid']) {
        json_error(ERR_NO_PERMISSION);
    }
    if (!$vbulletin->userinfo['userid'] and $_REQUEST['do'] != 'removesubscription' or $vbulletin->userinfo['userid'] and !($permissions['forumpermissions'] & $vbulletin->bf_ugp_forumpermissions['canview']) or $vbulletin->userinfo['usergroupid'] == 4 or !($permissions['genericoptions'] & $vbulletin->bf_ugp_genericoptions['isnotbannedgroup'])) {
        json_error(ERR_NO_PERMISSION);
    }
    $thread_data = array();
    $unread_subs = 0;
    // vbulletin expects folderid, but we will just get them all
    $vbulletin->input->clean_array_gpc('r', array('folderid' => TYPE_NOHTML, 'perpage' => TYPE_UINT, 'pagenumber' => TYPE_UINT, 'sortfield' => TYPE_NOHTML, 'sortorder' => TYPE_NOHTML, 'previewtype' => TYPE_INT));
    $previewtype = $vbulletin->GPC['previewtype'];
    if (!$previewtype) {
        $previewtype = 1;
    }
    $vbulletin->GPC['folderid'] = 'all';
    // Values that are reused in templates
    $sortfield =& $vbulletin->GPC['sortfield'];
    $perpage =& $vbulletin->GPC['perpage'];
    $pagenumber =& $vbulletin->GPC['pagenumber'];
    $folderid =& $vbulletin->GPC['folderid'];
    if ($folderid == 'all') {
        $getallfolders = true;
        $show['allfolders'] = true;
    } else {
        $folderid = intval($folderid);
    }
    $folderselect["{$folderid}"] = 'selected="selected"';
    // Build folder jump
    require_once DIR . '/includes/functions_misc.php';
    $folders = construct_folder_jump(1, $folderid, false, '', true);
    $templater = vB_Template::create('subscribe_folder_jump');
    $templater->register('folders', $folders);
    $folderjump = $templater->render();
    // look at sorting options:
    if ($vbulletin->GPC['sortorder'] != 'asc') {
        $vbulletin->GPC['sortorder'] = 'desc';
        $sqlsortorder = 'DESC';
        $order = array('desc' => 'selected="selected"');
    } else {
        $sqlsortorder = '';
        $order = array('asc' => 'selected="selected"');
    }
    switch ($sortfield) {
        case 'title':
        case 'lastpost':
        case 'replycount':
        case 'views':
        case 'postusername':
            $sqlsortfield = 'thread.' . $sortfield;
            break;
        default:
            $handled = false;
            if (!$handled) {
                $sqlsortfield = 'thread.lastpost';
                $sortfield = 'lastpost';
            }
    }
    $sort = array($sortfield => 'selected="selected"');
    if ($getallfolders) {
        $totalallthreads = array_sum($subscribecounters);
    } else {
        $totalallthreads = $subscribecounters["{$folderid}"];
    }
    // set defaults
    sanitize_pageresults($totalallthreads, $pagenumber, $perpage, 200, $vbulletin->options['maxthreads']);
    // display threads
    $limitlower = ($pagenumber - 1) * $perpage + 1;
    $limitupper = $pagenumber * $perpage;
    if ($limitupper > $totalallthreads) {
        $limitupper = $totalallthreads;
        if ($limitlower > $totalallthreads) {
            $limitlower = $totalallthreads - $perpage;
        }
    }
    if ($limitlower <= 0) {
        $limitlower = 1;
    }
    $hook_query_fields = $hook_query_joins = $hook_query_where = '';
    $getthreads = $db->query_read_slave("\n\t\tSELECT thread.threadid, emailupdate, subscribethreadid, thread.forumid, thread.postuserid\n\t\t\t{$hook_query_fields}\n\t\tFROM " . TABLE_PREFIX . "subscribethread AS subscribethread\n\t\tLEFT JOIN " . TABLE_PREFIX . "thread AS thread ON(thread.threadid = subscribethread.threadid)\n\t\t{$hook_query_joins}\n\t\tWHERE subscribethread.userid = " . $vbulletin->userinfo['userid'] . "\n\t\t\tAND thread.visible = 1\n\t\t\tAND canview = 1\n\t\t" . iif(!$getallfolders, "\tAND folderid = {$folderid}") . "\n\t\t\t{$hook_query_where}\n\t\tORDER BY {$sqlsortfield} {$sqlsortorder}\n\t\tLIMIT " . ($limitlower - 1) . ", {$perpage}\n\t");
    if ($totalthreads = $db->num_rows($getthreads)) {
        $forumids = array();
        $threadids = array();
        $emailupdate = array();
        $killthreads = array();
        while ($getthread = $db->fetch_array($getthreads)) {
            $forumperms = fetch_permissions($getthread['forumid']);
            if (!($forumperms & $vbulletin->bf_ugp_forumpermissions['canview']) or !($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']) or $getthread['postuserid'] != $vbulletin->userinfo['userid'] and !($forumperms & $vbulletin->bf_ugp_forumpermissions['canviewothers'])) {
                $killthreads["{$getthread['subscribethreadid']}"] = $getthread['subscribethreadid'];
                $totalallthreads--;
                continue;
            }
            $forumids["{$getthread['forumid']}"] = true;
            $threadids[] = $getthread['threadid'];
            $emailupdate["{$getthread['threadid']}"] = $getthread['emailupdate'];
            $subscribethread["{$getthread['threadid']}"] = $getthread['subscribethreadid'];
        }
        $threadids = implode(',', $threadids);
    }
    unset($getthread);
    $db->free_result($getthreads);
    if (!empty($killthreads)) {
        // Update thread subscriptions
        $vbulletin->db->query_write("\n\t\t\tUPDATE " . TABLE_PREFIX . "subscribethread\n\t\t\tSET canview = 0\n\t\t\tWHERE subscribethreadid IN (" . implode(', ', $killthreads) . ")\n\t\t");
    }
    if (!empty($threadids)) {
        cache_ordered_forums(1);
        $colspan = 5;
        $show['threadicons'] = false;
        // get last read info for each thread
        $lastread = array();
        foreach (array_keys($forumids) as $forumid) {
            if ($vbulletin->options['threadmarking']) {
                $lastread["{$forumid}"] = max($vbulletin->forumcache["{$forumid}"]['forumread'], TIMENOW - $vbulletin->options['markinglimit'] * 86400);
            } else {
                $lastread["{$forumid}"] = max(intval(fetch_bbarray_cookie('forum_view', $forumid)), $vbulletin->userinfo['lastvisit']);
            }
            if ($vbulletin->forumcache["{$forumid}"]['options'] & $vbulletin->bf_misc_forumoptions['allowicons']) {
                $show['threadicons'] = true;
                $colspan = 6;
            }
        }
        if ($previewtype == 1) {
            $previewfield = "post.pagetext AS preview, post.username AS lastpost_username, post.userid AS lastpost_userid,";
            $previewjoin = "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.firstpostid)";
        } else {
            $previewfield = "post.pagetext AS preview, post.username AS lastpost_username, post.userid AS lastpost_userid,";
            $previewjoin = "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.lastpostid)";
        }
        $hasthreads = true;
        $threadbits = '';
        $pagenav = '';
        $counter = 0;
        $toread = 0;
        $vbulletin->options['showvotes'] = intval($vbulletin->options['showvotes']);
        if ($vbulletin->userinfo['userid'] and in_coventry($vbulletin->userinfo['userid'], true)) {
            $lastpost_info = "IF(tachythreadpost.userid IS NULL, thread.lastpost, tachythreadpost.lastpost) AS lastpost, " . "IF(tachythreadpost.userid IS NULL, thread.lastposter, tachythreadpost.lastposter) AS lastposter, " . "IF(tachythreadpost.userid IS NULL, thread.lastposterid, tachythreadpost.lastposterid) AS lastposterid, " . "IF(tachythreadpost.userid IS NULL, thread.lastpostid, tachythreadpost.lastpostid) AS lastpostid";
            $tachyjoin = "LEFT JOIN " . TABLE_PREFIX . "tachythreadpost AS tachythreadpost ON " . "(tachythreadpost.threadid = thread.threadid AND tachythreadpost.userid = " . $vbulletin->userinfo['userid'] . ')';
        } else {
            $lastpost_info = 'thread.lastpost, thread.lastposter, thread.lastposterid, thread.lastpostid';
            $tachyjoin = '';
        }
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        $threads = $db->query_read_slave("\n\t\t\tSELECT\n\t\t\t\tIF(thread.votenum >= " . $vbulletin->options['showvotes'] . ", thread.votenum, 0) AS votenum,\n\t\t\t\tIF(thread.votenum >= " . $vbulletin->options['showvotes'] . " AND thread.votenum > 0, thread.votetotal / thread.votenum, 0) AS voteavg,\n\t\t\t\tthread.votetotal,\n\t\t\t\t{$previewfield} thread.threadid, thread.title AS threadtitle, thread.forumid, thread.pollid,\n\t\t\t\tthread.open, thread.replycount, thread.postusername, thread.prefixid,\n\t\t\t\t{$lastpost_info}, thread.postuserid, thread.dateline, thread.views, thread.iconid AS threadiconid,\n\t\t\t\tthread.notes, thread.visible, thread.attach, thread.taglist\n\t\t\t\t" . ($vbulletin->options['threadmarking'] ? ", threadread.readtime AS threadread" : '') . "\n\t\t\t\t{$hook_query_fields}\n\t\t\tFROM " . TABLE_PREFIX . "thread AS thread\n\t\t\t{$previewjoin}\n\t\t\t" . ($vbulletin->options['threadmarking'] ? " LEFT JOIN " . TABLE_PREFIX . "threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = " . $vbulletin->userinfo['userid'] . ")" : '') . "\n\t\t\t{$tachyjoin}\n\t\t\t{$hook_query_joins}\n\t\t\tWHERE thread.threadid IN ({$threadids})\n\t\t\tORDER BY {$sqlsortfield} {$sqlsortorder}\n\t\t");
        unset($sqlsortfield, $sqlsortorder);
        require_once DIR . '/includes/functions_forumdisplay.php';
        // Get Dot Threads
        $dotthreads = fetch_dot_threads_array($threadids);
        if ($vbulletin->options['showdots'] and $vbulletin->userinfo['userid']) {
            $show['dotthreads'] = true;
        } else {
            $show['dotthreads'] = false;
        }
        if ($vbulletin->options['threadpreview'] and $vbulletin->userinfo['ignorelist']) {
            // Get Buddy List
            $buddy = array();
            if (trim($vbulletin->userinfo['buddylist'])) {
                $buddylist = preg_split('/( )+/', trim($vbulletin->userinfo['buddylist']), -1, PREG_SPLIT_NO_EMPTY);
                foreach ($buddylist as $buddyuserid) {
                    $buddy["{$buddyuserid}"] = 1;
                }
            }
            DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
            // Get Ignore Users
            $ignore = array();
            if (trim($vbulletin->userinfo['ignorelist'])) {
                $ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
                foreach ($ignorelist as $ignoreuserid) {
                    if (!$buddy["{$ignoreuserid}"]) {
                        $ignore["{$ignoreuserid}"] = 1;
                    }
                }
            }
            DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
        }
        $foruminfo['allowratings'] = true;
        $show['notificationtype'] = true;
        $show['threadratings'] = true;
        $show['threadrating'] = true;
        while ($thread = $db->fetch_array($threads)) {
            $threadid = $thread['threadid'];
            // build thread data
            $thread = process_thread_array($thread, $lastread["{$thread['forumid']}"]);
            switch ($emailupdate["{$thread['threadid']}"]) {
                case 0:
                    $thread['notification'] = $vbphrase['none'];
                    break;
                case 1:
                    $thread['notification'] = $vbphrase['instant'];
                    break;
                case 2:
                    $thread['notification'] = $vbphrase['daily'];
                    break;
                case 3:
                    $thread['notification'] = $vbphrase['weekly'];
                    break;
                default:
                    $thread['notification'] = $vbphrase['n_a'];
            }
            $avatarurl = '';
            if ($thread['lastpost_userid'] > 0) {
                $userinfoavatar = fetch_userinfo($thread['lastpost_userid'], FETCH_USERINFO_AVATAR);
                fetch_avatar_from_userinfo($userinfoavatar, true, false);
                if ($userinfoavatar['avatarurl'] != '') {
                    $avatarurl = process_avatarurl($userinfoavatar['avatarurl']);
                }
                unset($userinfoavatar);
            }
            $tmp = array('thread_id' => $thread['threadid'], 'new_posts' => $show['gotonewpost'] ? true : false, 'forum_id' => $thread['forumid'], 'total_posts' => $thread['totalposts'] ? $thread['totalposts'] : 0, 'forum_title' => prepare_utf8_string($thread['forumtitle']), 'thread_title' => prepare_utf8_string($thread['threadtitle']), 'thread_preview' => prepare_utf8_string(preview_chop(html_entity_decode($thread['preview']), FR_PREVIEW_LEN)), 'post_userid' => $thread['lastpost_userid'], 'post_lastposttime' => prepare_utf8_string(date_trunc($thread['lastpostdate']) . ' ' . $thread['lastposttime']), 'post_username' => prepare_utf8_string(strip_tags($thread['lastpost_username'])));
            if ($avatarurl != '') {
                $tmp['avatarurl'] = $avatarurl;
            }
            if ($thread['attach']) {
                $tmp['attach'] = true;
            }
            if ($thread['pollid']) {
                $tmp['poll'] = true;
            }
            $thread_data[] = $tmp;
        }
        $db->free_result($threads);
        unset($threadids);
    } else {
        $totalallthreads = 0;
    }
    $out = array('threads' => $thread_data, 'total_threads' => $totalallthreads);
    return $out;
}
Example #28
0
function convert_ids_to_titles()
{

	global $vbulletin;
	global $albumids, $attachmentids, $calendarids, $eventids, $forumids,
		$infractionids, $pmids, $postids, $searchids, $socialgroupids, $threadids, $userids;
	global $wol_album, $wol_attachment, $wol_calendar, $wol_event, $wol_inf, $wol_pm,
		$wol_post, $wol_search, $wol_socialgroup, $wol_thread, $wol_user;

/*
	if ($attachmentids)
	{
		$postidquery = $vbulletin->db->query_read_slave("
			SELECT postid, attachmentid
			FROM " . TABLE_PREFIX . "attachment
			WHERE attachmentid IN (0$attachmentids)
		");
		while ($postidqueryr = $vbulletin->db->fetch_array($postidquery))
		{
			$postids .= ',' . $postidqueryr['postid'];
			$wol_attachment["$postidqueryr[attachmentid]"] = $postidqueryr['postid'];
		}
	}
*/

	if ($postids)
	{
		$postidquery = $vbulletin->db->query_read_slave("
			SELECT threadid, postid
			FROM " . TABLE_PREFIX . "post
			WHERE postid IN (0$postids)
		");
		while ($postidqueryr = $vbulletin->db->fetch_array($postidquery))
		{
			$threadids .= ',' . $postidqueryr['threadid'];
			$wol_post["$postidqueryr[postid]"] = $postidqueryr['threadid'];
		}
	}

	if ($socialgroupids)
	{
		$socialgroups = $vbulletin->db->query_read_slave("
			SELECT name, groupid
			FROM " . TABLE_PREFIX . "socialgroup
			WHERE groupid IN (0$socialgroupids)
		");

		while ($socialgroup = $vbulletin->db->fetch_array($socialgroups))
		{
			$wol_socialgroup["$socialgroup[groupid]"]['name'] = $socialgroup['name'];
		}
	}

	if ($albumids)
	{
		$albums = $vbulletin->db->query_read_slave("
			SELECT album.title, album.albumid, album.state, album.userid
			FROM " . TABLE_PREFIX . "album AS album
			LEFT JOIN " . TABLE_PREFIX . "profileblockprivacy AS profileblockprivacy ON
				(profileblockprivacy.userid = album.userid AND profileblockprivacy.blockid = 'albums')
			WHERE album.albumid IN (0$albumids)
				AND (profileblockprivacy.requirement = 0 OR profileblockprivacy.requirement IS NULL)
		");

		while ($album = $vbulletin->db->fetch_array($albums))
		{
			$wol_album["$album[albumid]"] = $album;
		}
	}

	if ($threadids)
	{
		$threadresults = $vbulletin->db->query_read_slave("
			SELECT thread.title, thread.prefixid, thread.threadid, thread.forumid, thread.postuserid, thread.visible
			" . iif($vbulletin->options['threadpreview'] > 0, ",post.pagetext AS preview") . "
			" . iif($vbulletin->options['threadsubscribed'] AND $vbulletin->userinfo['userid'], ", NOT ISNULL(subscribethread.subscribethreadid) AS issubscribed") . "
			FROM " . TABLE_PREFIX . "thread AS thread
			" . iif($vbulletin->options['threadpreview'] > 0, "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.firstpostid)") . "
			" . iif($vbulletin->options['threadsubscribed'] AND $vbulletin->userinfo['userid'], " LEFT JOIN " . TABLE_PREFIX . "subscribethread AS subscribethread ON(subscribethread.threadid = thread.threadid AND subscribethread.userid = " . $vbulletin->userinfo['userid'] . " AND canview = 1)") . "
			WHERE thread.threadid IN (0$threadids)
		");
		while ($threadresult = $vbulletin->db->fetch_array($threadresults))
		{
			$wol_thread["$threadresult[threadid]"]['title'] = $threadresult['title'];
			$wol_thread["$threadresult[threadid]"]['prefixid'] = $threadresult['prefixid'];
			$wol_thread["$threadresult[threadid]"]['forumid'] = $threadresult['forumid'];
			$wol_thread["$threadresult[threadid]"]['postuserid'] = $threadresult['postuserid'];
			$wol_thread["$threadresult[threadid]"]['isdeleted'] = ($threadresult['visible'] == 2) ? true : false;
			$wol_thread["$threadresult[threadid]"]['visible'] = ($threadresult['visible'] == 1) ? true : false;
			$wol_thread["$threadresult[threadid]"]['issubscribed'] = $threadresult['issubscribed'];

			// format thread preview if there is one
			$userperms = fetch_permissions($threadresult['forumid']);
			if (!empty($threadresult['preview']) AND $vbulletin->options['threadpreview'] > 0 AND ($userperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']))
			{
				// Get Buddy List
				$buddy = array();
				if (trim($vbulletin->userinfo['buddylist']))
				{
					$buddylist = preg_split('/( )+/', trim($vbulletin->userinfo['buddylist']), -1, PREG_SPLIT_NO_EMPTY);
					foreach ($buddylist AS $buddyuserid)
					{
						$buddy["$buddyuserid"] = 1;
					}
				}
				DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
				// Get Ignore Users
				$ignore = array();
				if (trim($vbulletin->userinfo['ignorelist']))
				{
					$ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
					foreach ($ignorelist AS $ignoreuserid)
					{
						if (!$buddy["$ignoreuserid"])
						{
							$ignore["$ignoreuserid"] = 1;
						}
					}
				}
				DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));

				if (!$ignore["$threadresult[postuserid]"])
				{
					$threadresult['preview'] = strip_quotes($threadresult['preview']);
					$threadresult['preview'] = htmlspecialchars_uni(strip_bbcode(fetch_trimmed_title($threadresult['preview'], $vbulletin->options['threadpreview']), false, true));
					$wol_thread["$threadresult[threadid]"]['preview'] = $threadresult['preview'];
				}
			}
		}
	}

	if ($calendarids)
	{
		$calendarresults = $vbulletin->db->query_read_slave("
			SELECT calendarid, title
			FROM " . TABLE_PREFIX . "calendar
			WHERE calendarid IN (0$calendarids)
		");
		while ($calendarresult = $vbulletin->db->fetch_array($calendarresults))
		{
			$wol_calendar["$calendarresult[calendarid]"] = $calendarresult['title'];
		}
	}

	if ($infractionids)
	{
		$infractions = $vbulletin->db->query_read_slave("
			SELECT infractionid, userid
			FROM " . TABLE_PREFIX . "infraction
			WHERE infractionid IN (0$infractionids)
		");
		while ($infraction = $vbulletin->db->fetch_array($infractions))
		{
			$wol_inf["$infraction[infractionid]"]['userid'] = $infraction['userid'];
			$userids .= ',' . $infraction['userid'];
		}
	}

	if ($eventids)
	{
		$eventresults = $vbulletin->db->query_read_slave("
			SELECT eventid, title, userid, calendarid
			FROM " . TABLE_PREFIX . "event
			WHERE eventid IN (0$eventids)
		");
		while ($eventresult = $vbulletin->db->fetch_array($eventresults))
		{
			$wol_event["$eventresult[eventid]"]['title'] = $eventresult['title'];
			$wol_event["$eventresult[eventid]"]['calendarid'] = $eventresult['calendarid'];
			$wol_event["$eventresult[eventid]"]['postuserid'] = $eventresult['userid'];
		}
	}

	if ($pmids AND ($vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']))
	{
		$pmresults = $vbulletin->db->query_read_slave("
			SELECT pmtext.fromuserid, pm.pmid
			FROM " . TABLE_PREFIX . "pm AS pm
			LEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pm.pmtextid = pmtext.pmtextid)
			WHERE pmid IN (0$pmids)
			");
		while ($pmresult = $vbulletin->db->fetch_array($pmresults))
		{
			$wol_pm["$pmresult[pmid]"] = $pmresult['fromuserid'];

			$userids .= ',' . intval($pmresult['fromuserid']);
		}
	}

	if ($searchids AND ($vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']))
	{
		//rework this to get what the code assumes the array looks like from the new search code.
		//in particular the searchuser value has been changed from a string to a bool based on usage
		//and the fact that we don't really have it.
		require_once(DIR . "/vb/search/core.php");
		require_once(DIR . '/vb/search/criteria.php');
		$searchresults = $vbulletin->db->query_read_slave("
			SELECT searchlog.searchlogid AS searchid, searchlog.userid, searchlog.criteria
			FROM " . TABLE_PREFIX . "searchlog AS searchlog
			WHERE searchlog.searchlogid IN (0$searchids)
		");
		while ($searchresult = $vbulletin->db->fetch_array($searchresults))
		{
			if ($searchresult['criteria'])
			{
				$criteria = unserialize($searchresult['criteria']);

				$targetuserid = $criteria->get_target_userid();
				if ($targetuserid)
				{
					$userids .= ",userid";
				}

				$searchresult['targetuserid'] = $targetuserid;
				$searchresult['searchuser'] = (bool) $targetuserid;
				$searchresult['query'] = $criteria->get_raw_keywords();
				unset($searchresult['criteria']);
			}
			$wol_search["$searchresult[searchid]"] = $searchresult;
		}
	}

	if ($userids AND ($vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']))
	{
		$userresults = $vbulletin->db->query_read_slave("
			SELECT userid, username, IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid
			FROM " . TABLE_PREFIX . "user AS user
			WHERE userid IN (0$userids)
		");
		while ($userresult = $vbulletin->db->fetch_array($userresults))
		{
			fetch_musername($userresult);
			$wol_user["$userresult[userid]"]['musername'] = $userresult['musername'];
			$wol_user["$userresult[userid]"]['username'] = $userresult['username'];
		}
	}

	($hook = vBulletinHook::fetch_hook('online_ids_titles')) ? eval($hook) : false;
}
Example #29
0
function convert_ids_to_titles()
{
    global $vbulletin;
    global $albumids, $attachmentids, $calendarids, $eventids, $forumids, $infractionids, $pmids, $postids, $searchids, $socialgroupids, $threadids, $userids;
    global $wol_album, $wol_attachment, $wol_calendar, $wol_event, $wol_inf, $wol_pm, $wol_post, $wol_search, $wol_socialgroup, $wol_thread, $wol_user;
    if ($attachmentids) {
        $postidquery = $vbulletin->db->query_read_slave("\n\t\t\tSELECT postid, attachmentid\n\t\t\tFROM " . TABLE_PREFIX . "attachment\n\t\t\tWHERE attachmentid IN (0{$attachmentids})\n\t\t");
        while ($postidqueryr = $vbulletin->db->fetch_array($postidquery)) {
            $postids .= ',' . $postidqueryr['postid'];
            $wol_attachment["{$postidqueryr['attachmentid']}"] = $postidqueryr['postid'];
        }
    }
    if ($postids) {
        $postidquery = $vbulletin->db->query_read_slave("\n\t\t\tSELECT threadid, postid\n\t\t\tFROM " . TABLE_PREFIX . "post\n\t\t\tWHERE postid IN (0{$postids})\n\t\t");
        while ($postidqueryr = $vbulletin->db->fetch_array($postidquery)) {
            $threadids .= ',' . $postidqueryr['threadid'];
            $wol_post["{$postidqueryr['postid']}"] = $postidqueryr['threadid'];
        }
    }
    if ($socialgroupids) {
        $socialgroups = $vbulletin->db->query_read_slave("\n\t\t\tSELECT name, groupid\n\t\t\tFROM " . TABLE_PREFIX . "socialgroup\n\t\t\tWHERE groupid IN (0{$socialgroupids})\n\t\t");
        while ($socialgroup = $vbulletin->db->fetch_array($socialgroups)) {
            $wol_socialgroup["{$socialgroup['groupid']}"]['name'] = $socialgroup['name'];
        }
    }
    if ($albumids) {
        $albums = $vbulletin->db->query_read_slave("\n\t\t\tSELECT title, albumid, state, userid\n\t\t\tFROM " . TABLE_PREFIX . "album\n\t\t\tWHERE albumid IN (0{$albumids})\n\t\t");
        while ($album = $vbulletin->db->fetch_array($albums)) {
            $wol_album["{$album['albumid']}"] = $album;
        }
    }
    if ($threadids) {
        $threadresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT thread.title, thread.prefixid, thread.threadid, thread.forumid, thread.postuserid, thread.visible\n\t\t\t" . iif($vbulletin->options['threadpreview'] > 0, ",post.pagetext AS preview") . "\n\t\t\t" . iif($vbulletin->options['threadsubscribed'] and $vbulletin->userinfo['userid'], ", NOT ISNULL(subscribethread.subscribethreadid) AS issubscribed") . "\n\t\t\tFROM " . TABLE_PREFIX . "thread AS thread\n\t\t\t" . iif($vbulletin->options['threadpreview'] > 0, "LEFT JOIN " . TABLE_PREFIX . "post AS post ON(post.postid = thread.firstpostid)") . "\n\t\t\t" . iif($vbulletin->options['threadsubscribed'] and $vbulletin->userinfo['userid'], " LEFT JOIN " . TABLE_PREFIX . "subscribethread AS subscribethread ON(subscribethread.threadid = thread.threadid AND subscribethread.userid = " . $vbulletin->userinfo['userid'] . " AND canview = 1)") . "\n\t\t\tWHERE thread.threadid IN (0{$threadids})\n\t\t");
        while ($threadresult = $vbulletin->db->fetch_array($threadresults)) {
            $wol_thread["{$threadresult['threadid']}"]['title'] = $threadresult['title'];
            $wol_thread["{$threadresult['threadid']}"]['prefixid'] = $threadresult['prefixid'];
            $wol_thread["{$threadresult['threadid']}"]['forumid'] = $threadresult['forumid'];
            $wol_thread["{$threadresult['threadid']}"]['postuserid'] = $threadresult['postuserid'];
            $wol_thread["{$threadresult['threadid']}"]['isdeleted'] = $threadresult['visible'] == 2 ? true : false;
            $wol_thread["{$threadresult['threadid']}"]['visible'] = $threadresult['visible'] == 1 ? true : false;
            $wol_thread["{$threadresult['threadid']}"]['issubscribed'] = $threadresult['issubscribed'];
            // format thread preview if there is one
            $userperms = fetch_permissions($threadresult['forumid']);
            if (!empty($threadresult['preview']) and $vbulletin->options['threadpreview'] > 0 and $userperms & $vbulletin->bf_ugp_forumpermissions['canviewthreads']) {
                // Get Buddy List
                $buddy = array();
                if (trim($vbulletin->userinfo['buddylist'])) {
                    $buddylist = preg_split('/( )+/', trim($vbulletin->userinfo['buddylist']), -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($buddylist as $buddyuserid) {
                        $buddy["{$buddyuserid}"] = 1;
                    }
                }
                DEVDEBUG('buddies: ' . implode(', ', array_keys($buddy)));
                // Get Ignore Users
                $ignore = array();
                if (trim($vbulletin->userinfo['ignorelist'])) {
                    $ignorelist = preg_split('/( )+/', trim($vbulletin->userinfo['ignorelist']), -1, PREG_SPLIT_NO_EMPTY);
                    foreach ($ignorelist as $ignoreuserid) {
                        if (!$buddy["{$ignoreuserid}"]) {
                            $ignore["{$ignoreuserid}"] = 1;
                        }
                    }
                }
                DEVDEBUG('ignored users: ' . implode(', ', array_keys($ignore)));
                if (!$ignore["{$threadresult['postuserid']}"]) {
                    $threadresult['preview'] = strip_quotes($threadresult['preview']);
                    $threadresult['preview'] = htmlspecialchars_uni(strip_bbcode(fetch_trimmed_title($threadresult['preview'], $vbulletin->options['threadpreview']), false, true));
                    $wol_thread["{$threadresult['threadid']}"]['preview'] = $threadresult['preview'];
                }
            }
        }
    }
    if ($calendarids) {
        $calendarresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT calendarid, title\n\t\t\tFROM " . TABLE_PREFIX . "calendar\n\t\t\tWHERE calendarid IN (0{$calendarids})\n\t\t");
        while ($calendarresult = $vbulletin->db->fetch_array($calendarresults)) {
            $wol_calendar["{$calendarresult['calendarid']}"] = $calendarresult['title'];
        }
    }
    if ($infractionids) {
        $infractions = $vbulletin->db->query_read_slave("\n\t\t\tSELECT infractionid, userid\n\t\t\tFROM " . TABLE_PREFIX . "infraction\n\t\t\tWHERE infractionid IN (0{$infractionids})\n\t\t");
        while ($infraction = $vbulletin->db->fetch_array($infractions)) {
            $wol_inf["{$infraction['infractionid']}"]['userid'] = $infraction['userid'];
            $userids .= ',' . $infraction['userid'];
        }
    }
    if ($eventids) {
        $eventresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT eventid, title, userid, calendarid\n\t\t\tFROM " . TABLE_PREFIX . "event\n\t\t\tWHERE eventid IN (0{$eventids})\n\t\t");
        while ($eventresult = $vbulletin->db->fetch_array($eventresults)) {
            $wol_event["{$eventresult['eventid']}"]['title'] = $eventresult['title'];
            $wol_event["{$eventresult['eventid']}"]['calendarid'] = $eventresult['calendarid'];
            $wol_event["{$eventresult['eventid']}"]['postuserid'] = $eventresult['userid'];
        }
    }
    if ($pmids and $vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']) {
        $pmresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT pmtext.fromuserid, pm.pmid\n\t\t\tFROM " . TABLE_PREFIX . "pm AS pm\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON (pm.pmtextid = pmtext.pmtextid)\n\t\t\tWHERE pmid IN (0{$pmids})\n\t\t\t");
        while ($pmresult = $vbulletin->db->fetch_array($pmresults)) {
            $wol_pm["{$pmresult['pmid']}"] = $pmresult['fromuserid'];
            $userids .= ',' . intval($pmresult['fromuserid']);
        }
    }
    if ($searchids and $vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']) {
        $searchresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT searchid, search.userid, query, searchuser, user.userid AS targetuserid\n\t\t\tFROM " . TABLE_PREFIX . "search AS search\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "user AS user ON (user.username = search.searchuser)\n\t\t\tWHERE searchid IN (0{$searchids})\n\t\t");
        while ($searchresult = $vbulletin->db->fetch_array($searchresults)) {
            if ($searchresult['searchuser']) {
                if (!$searchresult['targetuserid']) {
                    $result = $vbulletin->db->query_first_slave("\n\t\t\t\t\t\tSELECT userid AS targetuserid\n\t\t\t\t\t\tFROM " . TABLE_PREFIX . "user\n\t\t\t\t\t\tWHERE username = '******'searchuser'])) . "'\n\t\t\t\t\t");
                }
                if ($result['targetuserid']) {
                    $searchresult['targetuserid'] = $result['targetuserid'];
                }
                if ($searchresult['targetuserid']) {
                    $userids .= ",{$searchresult['targetuserid']}";
                }
            }
            $wol_search["{$searchresult['searchid']}"] = $searchresult;
        }
    }
    if ($userids and $vbulletin->userinfo['permissions']['wolpermissions'] & $vbulletin->bf_ugp_wolpermissions['canwhosonlinefull']) {
        $userresults = $vbulletin->db->query_read_slave("\n\t\t\tSELECT userid, username, IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid\n\t\t\tFROM " . TABLE_PREFIX . "user AS user\n\t\t\tWHERE userid IN (0{$userids})\n\t\t");
        while ($userresult = $vbulletin->db->fetch_array($userresults)) {
            fetch_musername($userresult);
            $wol_user["{$userresult['userid']}"] = $userresult['musername'];
        }
    }
    ($hook = vBulletinHook::fetch_hook('online_ids_titles')) ? eval($hook) : false;
}
Example #30
0
function newItem($itemid, $itemdata = false)
{
    global $kbank_items, $vbulletin;
    if (!$vbulletin->kbank['itemEnabled'] and VB_AREA != 'AdminCP') {
        return false;
    }
    if ($itemid === 0) {
        //Creating new item
        if ($itemtype =& newItemType($itemdata['type'], false, true) and $itemtype->classname) {
            $item =& new $itemtype->classname($itemdata);
        } else {
            return false;
        }
    } else {
        $itemids = array();
        $itemdatas = array();
        if (is_array($itemid)) {
            //There are many itemids
            foreach ($itemid as $id) {
                if (is_numeric($id) and $id > 0 and !isset($kbank_items[$id])) {
                    //Itemid okay and it hasn't been cached
                    $itemids[] = intval($id);
                }
            }
            if (count($itemids)) {
                $itemdata_cache = $vbulletin->db->query_read("\n\t\t\t\t\tSELECT \n\t\t\t\t\t\titems.* \n\t\t\t\t\t\t,user.username AS username\n\t\t\t\t\tFROM `" . TABLE_PREFIX . "kbank_items` AS items\n\t\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "user` AS user ON (user.userid = items.userid)\n\t\t\t\t\tWHERE items.itemid IN (" . implode(',', $itemids) . ")\n\t\t\t\t");
                DEVDEBUG('[kBank Item] newItem query the database');
                $itemids = array();
                //Reset
                $itemtypeids = array();
                while ($itemdata = $vbulletin->db->fetch_array($itemdata_cache)) {
                    $itemdatas[$itemdata['itemid']] = $itemdata;
                    $itemids[] = $itemdata['itemid'];
                    $itemtypeids[] = $itemdata['type'];
                }
                //Prepair itemtypes
                if (count($itemtypeids) > 1) {
                    //Only prepair if there are more than 1 itemtype
                    newItemType($itemtypeids, false, true);
                }
            }
        } else {
            if (is_numeric($itemid) and $itemid > 0) {
                //Only 1 itemid is passed in
                if (!isset($kbank_items[$itemid])) {
                    //It has not been initialized, we can do it!
                    $itemids[] = $itemid;
                    if ($itemdata) {
                        $itemdatas[$itemid] = $itemdata;
                    } else {
                        $itemdatas[$itemid] = $vbulletin->db->query_first("\n\t\t\t\t\t\tSELECT \n\t\t\t\t\t\t\titems.* \n\t\t\t\t\t\t\t,user.username AS username\n\t\t\t\t\t\tFROM `" . TABLE_PREFIX . "kbank_items` AS items\n\t\t\t\t\t\tLEFT JOIN `" . TABLE_PREFIX . "user` AS user ON (user.userid = items.userid)\n\t\t\t\t\t\tWHERE itemid = {$itemid}\n\t\t\t\t\t");
                        DEVDEBUG('[kBank Item] newItem query the database');
                        if (!$itemdatas[$itemid]) {
                            return false;
                        }
                    }
                } else {
                    //Nothing to do!
                    $item =& $kbank_items[$itemid];
                }
            }
        }
        if (count($itemids) > 0 and count($itemids) == count($itemdatas)) {
            foreach ($itemids as $itemid) {
                $itemdata =& $itemdatas[$itemid];
                if ($itemtype =& newItemType($itemdata['type'], false, true) and $itemtype->classname) {
                    $kbank_items[$itemid] =& new $itemtype->classname($itemdata);
                } else {
                    $kbank_items[$itemid] = false;
                }
            }
            if (count($itemids) == 1) {
                //Only return if passed in 1 itemid
                $item =& $kbank_items[$itemids[0]];
            }
        }
    }
    if ($item) {
        return $item;
    } else {
        return false;
    }
}