Exemplo n.º 1
0
function process_showgroups_userinfo($user)
{
    global $vbulletin, $permissions, $stylevar, $show;
    $post =& $user;
    $datecut = TIMENOW - $vbulletin->options['cookietimeout'];
    require_once DIR . '/includes/functions_bigthree.php';
    fetch_online_status($user, true);
    if (!$user['invisible'] or $permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canseehidden']) {
        $user['lastonline'] = vbdate($vbulletin->options['dateformat'], $user['lastactivity'], 1);
    } else {
        $user['lastonline'] = ' ';
    }
    fetch_musername($user);
    return $user;
}
Exemplo n.º 2
0
function process_showgroups_userinfo($user)
{
    global $vbulletin, $permissions, $stylevar, $show;
    $user = array_merge($user, convert_bits_to_array($user['options'], $vbulletin->bf_misc_useroptions));
    $user = array_merge($user, convert_bits_to_array($user['adminoptions'], $vbulletin->bf_misc_adminoptions));
    cache_permissions($user, false);
    fetch_online_status($user, true);
    if (!$user['invisible'] or $permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canseehidden']) {
        $user['lastonline'] = vbdate($vbulletin->options['dateformat'], $user['lastactivity'], 1);
    } else {
        $user['lastonline'] = ' ';
    }
    fetch_musername($user);
    return $user;
}
Exemplo n.º 3
0
 /**
  * Prepares the user's online status
  *
  */
 function prepare_onlinestatus()
 {
     if (!isset($this->prepared['onlinestatus'])) {
         require_once DIR . '/includes/functions_bigthree.php';
         fetch_online_status($this->userinfo, true);
         $this->prepared['onlinestatus'] = $this->userinfo['onlinestatus'];
     }
 }
Exemplo n.º 4
0
	/**
	* Processes this post's user info assuming the user is registered.
	*/
	function process_registered_user()
	{
		global $show, $vbphrase;
		$post =& $this->post; // this is a stopgap required for rank's eval code

		fetch_musername($this->post);

		// get online status -- function call also sets values in $this->post
		$this->post['online_status_code'] = fetch_online_status($this->post, true);

		if (empty($this->cache['perms'][$this->post['userid']]))
		{
			$this->cache['perms'][$this->post['userid']] = cache_permissions($this->post, false);
		}

		// get avatar
		if ($this->post['avatarid'])
		{
			$this->post['avatarurl'] = $this->post['avatarpath'];
		}
		else
		{
			if ($this->post['hascustomavatar'] AND $this->registry->options['avatarenabled'])
			{
				if ($this->registry->options['usefileavatar'])
				{
					$this->post['avatarurl'] = $this->registry->options['avatarurl'] . '/avatar' . $this->post['userid'] . '_' . $this->post['avatarrevision'] . '.gif';
				}
				else
				{
					$this->post['avatarurl'] = 'image.php?' . $this->registry->session->vars['sessionurl'] . 'u=' . $this->post['userid'] . '&dateline=' . $this->post['avatardateline'];
				}
				if ($this->post['avwidth'] AND $this->post['avheight'])
				{
					$this->post['avwidth'] = 'width="' . $this->post['avwidth'] . '"';
					$this->post['avheight'] = 'height="' . $this->post['avheight'] . '"';
				}
				else
				{
					$this->post['avwidth'] = '';
					$this->post['avheight'] = '';
				}
			}
			else
			{
				$this->post['avatarurl'] = '';
			}
		}

		if ( // no avatar defined for this user
			empty($this->post['avatarurl'])
			OR // visitor doesn't want to see avatars
			($this->registry->userinfo['userid'] > 0 AND !$this->registry->userinfo['showavatars'])
			OR // user has a custom avatar but no permission to display it
			(!$this->post['avatarid'] AND !($this->cache['perms'][$this->post['userid']]['genericpermissions'] & $this->registry->bf_ugp_genericpermissions['canuseavatar']) AND !$this->post['adminavatar']) //
		)
		{
			$show['avatar'] = false;
		}
		else
		{
			$show['avatar'] = true;
		}

		// Generate Reputation Power
		if ($this->registry->options['postelements'] & POST_SHOW_REPPOWER AND $this->registry->options['reputationenable'])
		{
			if (!empty($this->cache['reppower'][$this->post['userid']]))
			{
				$this->post['reppower'] = $this->cache['reppower'][$this->post['userid']];
			}
			else
			{
				$this->post['reppower'] = fetch_reppower($this->post, $this->cache['perms'][$this->post['userid']]);
				$this->cache['reppower'][$this->post['userid']] = $this->post['reppower'];
			}
			$show['reppower'] = true;
		}
		else
		{
			$show['reppower'] = false;
		}

		// get reputation
		if ($this->registry->options['reputationenable'])
		{
			fetch_reputation_image($this->post, $this->cache['perms'][$this->post['userid']]);
			$show['reputation'] = true;
		}
		else
		{
			$show['reputation'] = false;
		}

		// get join date & posts per day
		$jointime = (TIMENOW - $this->post['joindate']) / 86400; // Days Joined
		if ($jointime < 1)
		{
			// User has been a member for less than one day.
			$this->post['postsperday'] = $this->post['posts'];
		}
		else
		{
			$this->post['postsperday'] = vb_number_format($this->post['posts'] / $jointime, 2);
		}
		$this->post['joindate'] = vbdate($this->registry->options['registereddateformat'], $this->post['joindate']);

		// format posts number
		$this->post['posts'] = vb_number_format($this->post['posts']);

		$show['profile'] = true;
		$show['search'] = true;
		$show['buddy'] = true;
		$show['emaillink'] = (
			$this->post['showemail'] AND $this->registry->options['displayemails'] AND (
				!$this->registry->options['secureemail'] OR (
					$this->registry->options['secureemail'] AND $this->registry->options['enableemail']
				)
			) AND $this->registry->userinfo['permissions']['genericpermissions'] & $this->registry->bf_ugp_genericpermissions['canemailmember']
			AND $this->registry->userinfo['userid']
		);
		$show['homepage'] = ($this->post['homepage'] != '' AND $this->post['homepage'] != 'http://');
		$show['pmlink'] = ($this->registry->options['enablepms'] AND $this->registry->userinfo['permissions']['pmquota'] AND ($this->registry->userinfo['permissions']['adminpermissions'] & $this->registry->bf_ugp_adminpermissions['cancontrolpanel']
	 					OR ($this->post['receivepm'] AND $this->cache['perms'][$this->post['userid']]['pmquota'])
	 				)) ? true : false;

		// Generate Age
		if ($this->registry->options['postelements'] & POST_SHOW_AGE AND ($this->post['showbirthday'] == 1 OR $this->post['showbirthday'] == 2))
		{
			if (!$this->cache['year'])
			{
				$this->cache['year'] = vbdate('Y', TIMENOW, false, false);
				$this->cache['month'] = vbdate('n', TIMENOW, false, false);
				$this->cache['day'] = vbdate('j', TIMENOW, false, false);
			}
			if (empty($this->cache['age'][$this->post['userid']]))
			{
				$date = explode('-', $this->post['birthday']);
				if ($this->cache['year'] > $date[2] AND $date[2] != '0000')
				{
					$this->post['age'] = $this->cache['year'] - $date[2];
					if ($this->cache['month'] < $date[0] OR ($this->cache['month'] == $date[0] AND $this->cache['day'] < $date[1]))
					{
						$this->post['age']--;
					}

					if ($this->post['age'] < 101)
					{
						$this->cache['age'][$this->post['userid']] = $this->post['age'];
					}
					else
					{
						unset($this->post['age']);
					}
				}
			}
			else
			{
				$this->post['age'] = $this->cache['age'][$this->post['userid']];
			}
		}

		// Display infractions
		$show['infraction'] = ($this->post['userid'] AND ($this->registry->options['postelements'] & POST_SHOW_INFRACTION) AND (
			$this->post['ipoints'] OR $this->post['warnings'] OR $this->post['infractions']) AND (
			$this->registry->userinfo['permissions']['genericpermissions'] & $this->registry->bf_ugp_genericpermissions['canreverseinfraction']
			OR $this->registry->userinfo['permissions']['genericpermissions'] & $this->registry->bf_ugp_genericpermissions['canseeinfraction']
			OR $this->registry->userinfo['permissions']['genericpermissions'] & $this->registry->bf_ugp_genericpermissions['cangiveinfraction']
			OR ($this->post['userid'] == $this->registry->userinfo['userid'] /*AND $this->registry->options['canseeown']*/)
		));

		// Moved to a function to allow child overriding, i.e. announcements
		$this->process_signature();
	}
Exemplo n.º 5
0
 /**
  * * This gets the information needed for a user's profile. Only public information unless this is an admin or the user.
  */
 public function fetchProfileInfo($userid = false)
 {
     $options = vB::getDatastore()->getValue('options');
     $currentUserid = vB::getCurrentSession()->get('userid');
     if (empty($userid)) {
         $userid = $currentUserid;
     } else {
         $userid = intval($userid);
     }
     if ($userid < 1) {
         throw new vB_Exception_Api('invalid_data_w_x_y_z', array($userid, 'userid', __CLASS__, __FUNCTION__));
     }
     $hashKey = 'vBProfileUser_' . $userid;
     $fastCache = vB_Cache::instance(vB_Cache::CACHE_FAST);
     $userInfo = $fastCache->read($hashKey);
     if (empty($userInfo)) {
         $userInfo = vB_User::fetchUserinfo($userid, array(vB_Api_User::USERINFO_AVATAR, vB_Api_User::USERINFO_PROFILEPIC, vB_Api_User::USERINFO_ADMIN, vB_Api_User::USERINFO_SIGNPIC));
         // Some things even admins shouldn't see
         foreach (array('token', 'scheme', 'secret', 'coppauser', 'securitytoken_raw', 'securitytoken', 'logouthash', 'fbaccesstoken') as $field) {
             unset($userInfo[$field]);
         }
         try {
             $this->checkHasAdminPermission('canadminusers');
             // If this doesn't throw an exception, the other data is visible to an admin.
         } catch (Exception $e) {
             if (vB::getCurrentSession()->get('userid') != $userid) {
                 foreach (array('passworddate', 'parentemail', 'logintype', 'ipaddress', 'passworddate', 'email', 'referrerid', 'ipoints', 'infractions', 'warnings', 'infractiongroupids', 'infractiongroupid') as $field) {
                     $userInfo[$field] = '';
                 }
             }
         }
         /**
          * * Fields for the user's profile pages
          */
         $assertor = vB::getDbAssertor();
         //see if we have a cached userfield
         $fields = vB_Cache::instance(vB_Cache::CACHE_FAST)->read("userFields_{$userid}");
         if ($fields == false) {
             $fields = $assertor->getRow('vBForum:userfield', array('userid' => $userid));
             vB_Cache::instance(vB_Cache::CACHE_FAST)->write("userFields_{$userid}", $fields, 1440, "userData_{$userid}");
         }
         $customFields = array();
         if (!empty($fields)) {
             // Show hidden fields only if the user views his own profile or if it has the permission to see them
             $hidden = array(0);
             $showHidden = ($currentUserid == $userid or vB_Api::instanceInternal('user')->hasPermissions('genericpermissions', 'canseehiddencustomfields'));
             $fieldsInfo = vB::getDatastore()->getValue('profilefield');
             if (is_array($fieldsInfo) and array_key_exists('all', $fieldsInfo)) {
                 $fieldsInfo = $fieldsInfo['all'];
             } else {
                 $fieldsInfo = array();
             }
             foreach ($fieldsInfo as $customField) {
                 if ($customField['hidden'] == 0 or $showHidden) {
                     $catNameString = $customField['profilefieldcategoryid'] ? 'category' . $customField['profilefieldcategoryid'] . '_title' : 'default';
                     $fieldNameString = 'field' . $customField['profilefieldid'] . '_title';
                     $customFields[$catNameString][$fieldNameString] = array('val' => $this->getCustomFieldValue($customField, $fields), 'hidden' => $customField['hidden']);
                 }
             }
         }
         $userInfo['customFields'] = $customFields;
         /**
          * Check whether user has permission to use friends list (follow users)
          */
         $userInfo['canusefriends'] = vB::getUserContext($userid)->hasPermission('genericpermissions2', 'canusefriends');
         $userInfo['canviewmembers'] = vB::getUserContext($userid)->hasPermission('genericpermissions', 'canviewmembers');
         /**
          * * User counts
          */
         $followApi = vB_Api::instanceInternal('follow');
         if ($currentUserid == $userid or $userInfo['canusefriends']) {
             $follows = $followApi->getFollowing($userid);
             $userInfo['followsCount'] = $follows['paginationInfo']['totalcount'];
         }
         $followers = $followApi->getFollowers($userid);
         $userInfo['followersCount'] = $followers['paginationInfo']['totalcount'];
         $userInfo['socialGroupsCount'] = 10;
         if (isset($this->referrals[$userid])) {
             $referrals = $this->referrals[$userid];
         } else {
             $referrals = $assertor->getRow('vBForum:getReferralsCount', array('userid' => $userid));
             $this->referrals[$userid] = $referrals;
         }
         $userInfo['birthdayTimestamp'] = 0;
         $userInfo['referralsCount'] = $referrals['referrals'];
         if ($userInfo['birthday_search']) {
             list($year, $month, $day) = explode("-", $userInfo['birthday_search']);
             $userInfo['birthdayTimestamp'] = mktime(0, 0, 0, $month, $day, $year);
             $userInfo['age'] = date("md") < $month . $day ? date("Y") - $year - 1 : date("Y") - $year;
         }
         /**
          * Get vms info
          */
         $vms = $assertor->getRows('vBForum:node', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, 'setfor' => $userid), array('field' => 'publishdate', 'direction' => vB_dB_Query::SORT_DESC));
         vB_Library_Content::writeToCache($vms, vB_Library_Content::CACHELEVEL_NODE);
         $userInfo['vmCount'] = count($vms);
         $userInfo['vmMostRecent'] = $userInfo['vmCount'] ? $vms[0]['publishdate'] : 0;
         /**
          * Let's get posts per day
          */
         $timeIn = (vB::getRequest()->getTimeNow() - $userInfo['joindate']) / (24 * 60 * 60);
         if ($timeIn >= 1 and $userInfo['posts'] > 0) {
             $userInfo['postPerDay'] = vb_number_format($userInfo['posts'] / $timeIn, 2);
         } else {
             $userInfo['postPerDay'] = $userInfo['posts'];
         }
         $fastCache->write($hashKey, $userInfo, 1440, 'userChg_' . $userid);
     }
     // add current user flags
     // if user is the profile owner..
     $userInfo['showAvatar'] = 1;
     if ($currentUserid == $userid) {
         if (vB::getUserContext()->hasPermission('genericpermissions', 'canuseavatar')) {
             $userInfo['canuseavatar'] = 1;
             $userInfo['avatarmaxwidth'] = vB::getUserContext()->getLimit('avatarmaxwidth');
             $userInfo['avatarmaxheight'] = vB::getUserContext()->getLimit('avatarmaxheight');
             $userInfo['avatarmaxsize'] = vB::getUserContext()->getLimit('avatarmaxsize') / 1024;
         } else {
             $userInfo['canuseavatar'] = 0;
         }
         //Are there any default avatars this user could assign?
         $avatars = vB_Api::instanceInternal('profile')->getDefaultAvatars();
         $userInfo['defaultAvatarCount'] = count($avatars);
         if ($userInfo['defaultAvatarCount'] or $userInfo['canuseavatar'] > 0) {
             $userInfo['showAvatarOptions'] = 1;
         } else {
             $userInfo['showAvatarOptions'] = 0;
         }
         if ($userInfo['profilepic']) {
             if ($options['usefileavatar']) {
                 $userInfo['profilepicturepath'] = $options['bburl'] . '/' . $options['profilepicurl'] . "/profilepic{$currentUserid}" . '_' . $userInfo['profilepicrevision'] . '.gif';
             } else {
                 $userInfo['profilepicturepath'] = $options['bburl'] . "/image.php?u={$currentUserid}&type=profile&dateline=" . $userInfo['profilepicdateline'];
             }
         }
     } else {
         $userInfo['canuseavatar'] = $userInfo['showAvatarOptions'] = 0;
         //Check the privacy settings and see if this user has hidden his
         if ($userInfo['privacy_options'] and vB::getUserContext($userid)->hasPermission('usercsspermissions', 'caneditprivacy')) {
             switch ($userInfo['privacy_options']['profile_picture']) {
                 case 1:
                     //visible only if the current user is a subscriber.
                     if ($currentUserid == 0 or vB_Api::instanceInternal('follow')->isFollowingUser($userid) != vB_Api_Follow::FOLLOWING_YES) {
                         $userInfo['showAvatar'] = 0;
                     }
                     break;
                 case 2:
                     //visible only if the current user is a registered user.
                     if ($currentUserid == 0) {
                         $userInfo['showAvatar'] = 0;
                     }
                     break;
             }
             // switch
         }
         $userInfo['profilepicturepath'] = '';
     }
     $this->setCurrentUserFlags($userInfo);
     // Add online status
     require_once DIR . '/includes/functions_bigthree.php';
     fetch_online_status($userInfo);
     return $userInfo;
 }
Exemplo n.º 6
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;
}
Exemplo n.º 7
0
if ($_REQUEST['do'] == 'viewmembers') {
    $vbulletin->input->clean_array_gpc('r', array('perpage' => TYPE_UINT, 'pagenumber' => TYPE_UINT));
    $perpage = $vbulletin->GPC['perpage'];
    $pagenumber = $vbulletin->GPC['pagenumber'];
    $totalmembers = $group['members'];
    sanitize_pageresults($totalmembers, $pagenumber, $perpage);
    $groupmembers = $vbulletin->db->query_read("\n\t\tSELECT userfield.*, usertextfield.*, user.*, UNIX_TIMESTAMP(passworddate) AS passworddate,\n\t\t\tIF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, (user.options & " . $vbulletin->bf_misc_useroptions['invisible'] . ") AS invisible,\n\t\t\t" . ($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\tcustomprofilepic.userid AS profilepic, customprofilepic.dateline AS profilepicdateline, customprofilepic.width AS ppwidth, customprofilepic.height AS ppheight,\n\t\t\tuser.icq AS icq, user.aim AS aim, user.yahoo AS yahoo, user.msn AS msn, user.skype AS skype\n\t\tFROM " . TABLE_PREFIX . "socialgroupmember AS socialgroupmember\n\t\tINNER JOIN " . TABLE_PREFIX . "user AS user ON (user.userid = socialgroupmember.userid)\n\t\tLEFT JOIN " . TABLE_PREFIX . "userfield AS userfield ON (user.userid = userfield.userid)\n\t\tLEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON (usertextfield.userid = user.userid)\n\t\t" . ($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\tLEFT JOIN " . TABLE_PREFIX . "customprofilepic AS customprofilepic ON (user.userid = customprofilepic.userid)\n\t\tWHERE socialgroupmember.groupid = " . $vbulletin->GPC['groupid'] . " AND socialgroupmember.type = 'member'\n\t\tORDER BY user.username\n\t\tLIMIT " . ($pagenumber - 1) * $perpage . ", {$perpage}\n\t");
    require_once DIR . '/includes/functions_bigthree.php';
    while ($groupmember = $vbulletin->db->fetch_array($groupmembers)) {
        $width = 0;
        $height = 0;
        $alt = exec_switch_bg();
        fetch_avatar_from_userinfo($groupmember, true);
        fetch_musername($groupmember);
        $user =& $groupmember;
        fetch_online_status($user, true);
        construct_im_icons($user, true);
        ($hook = vBulletinHook::fetch_hook('group_memberbit')) ? eval($hook) : false;
        eval('$member_list .= "' . fetch_template('memberinfo_small') . '";');
    }
    $navbits = array('group.php' . $vbulletin->session->vars['sessionurl_q'] => $vbphrase['social_groups'], 'group.php?' . $vbulletin->session->vars['sessionurl'] . 'groupid=' . $group['groupid'] => $group['name'], '' => $vbphrase['member_list']);
    $custompagetitle = $group['name'] . ' - ' . $vbphrase['member_list'];
    $pagenav = construct_page_nav($pagenumber, $perpage, $totalmembers, 'group.php?' . $vbulletin->session->vars['sessionurl'] . 'do=viewmembers&amp;groupid=' . $group['groupid'] . ($perpage ? "&amp;pp={$perpage}" : ''));
    eval('$memberinfo_css = "' . fetch_template('memberinfo_css') . '";');
    $templatename = 'socialgroups_memberlist';
}
// #######################################################################
if ($_REQUEST['do'] == 'search') {
    $navbits = array('group.php' . $vbulletin->session->vars['sessionurl_q'] => $vbphrase['social_groups'], '' => $vbphrase['advanced_search']);
    $templatename = 'socialgroups_search';
}
Exemplo n.º 8
0
/**
* Returns the HTML for the member dwop-down pop-up menu
*
* @param	array	user information for the drop-down context
* @param	array	template hook, if we dont want to use the global one (like in postbit)
* @param	string	class name to apply to the div for context specific stylings
*
* @return	string	Member Drop-Down HTML
*/
function construct_memberaction_dropdown($memberinfo, $template_hook = array(), $page_class = null)
{
	global $show, $vbulletin;

	$memberperm = cache_permissions($memberinfo, false);

	// display the private messgage link?
	$show['pmlink']=
	(
		$vbulletin->options['enablepms']
			AND
		$vbulletin->userinfo['permissions']['pmquota']
			AND
		(
			$vbulletin->userinfo['permissions']['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel']
				OR
			($memberinfo['receivepm'] AND $memberperm['pmquota'])
		)
	);

	// display the user's homepage link?
	$show['homepage'] = ($memberinfo['homepage'] != '' AND $memberinfo['homepage'] != 'http://');

	// display the add as friend link?
	$show['addfriend']=
	(
		$vbulletin->options['socnet'] & $vbulletin->bf_misc_socnet['enable_friends']
		AND $vbulletin->userinfo['userid']
		AND $memberinfo['userid'] != $vbulletin->userinfo['userid']
		AND $vbulletin->userinfo['permissions']['genericpermissions2'] & $vbulletin->bf_ugp_genericpermissions2['canusefriends']
		AND $memberperm['genericpermissions2'] & $vbulletin->bf_ugp_genericpermissions2['canusefriends']
		AND !$memberinfo['isfriend']
	);

	// Check if blog is installed, and show link if so
	$show['viewblog'] = $vbulletin->products['vbblog'];

	// Check if CMS is installed, and show link if so
	$show['viewarticles'] = $vbulletin->products['vbcms'];

	// display the email link?
	$show['emaillink'] = (
		$memberinfo['showemail'] AND $vbulletin->options['displayemails'] AND
		(
			!$vbulletin->options['secureemail']
				OR
			($vbulletin->options['secureemail'] AND $vbulletin->options['enableemail'])
		)
		AND $vbulletin->userinfo['permissions']['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canemailmember']
		AND $vbulletin->userinfo['userid']
	);

	if (!$memberinfo['onlinestatusphrase'])
	{
		require_once(DIR . '/includes/functions_bigthree.php');
		fetch_online_status($memberinfo);
	}

	// execute memberaction hook
	($hook = vBulletinHook::fetch_hook('memberaction_dropdown')) ? eval($hook) : false;

	$templater = vB_Template::create('memberaction_dropdown');
	$templater->register('memberinfo', $memberinfo);
	$templater->register('template_hook', $template_hook);
	if (!empty($page_class))
	{
		$templater->register('page_class', $page_class);
	}

	return $templater->render();
}
Exemplo n.º 9
0
 /**
  * Assembles the response for detailed content
  *
  *	@param	Array	$content	getRawContent() response array. Each element is a nodeid-keyed array. Each
  *								subarray must have the following data at minimum: nodeid, channelid,
  *								contenttypeid, starter, showopen, userid, setfor (if VM), nodeoptions
  *
  *	@return	Array	Nodeid-keyed array of the $content data, plus additional data such as contenttypeclass,
  *					createpermissions, moderatorperms, channeltype, permissions, etc, @TODO: complete this list
  *					Also the expanded nodeoptions of:
  *						allow_post, moderate_comments, approve_membership, invite_only, autoparselinks,
  *						disablesmilies, disable_bbcode, hide_title, hide_author, hide_publishdate,
  *						display_fullincategory, display_pageviews, hide_comment_count
  */
 public function assembleContent(&$content)
 {
     // get the class name for this content type to add to results
     $contentTypeClass = vB_Types::instance()->getContentTypeClass($this->contenttypeid);
     $userContext = vB::getUserContext();
     $languageid = vB::getCurrentSession()->get('languageid');
     //We can save some time by saving, for a page load, the list of
     // channels we already know the current user can't post.
     static $noComment = array();
     $results = array();
     $needUserRep = array();
     $cache = vB_Cache::instance(vB_Cache::CACHE_STD);
     $fastCache = vB_Cache::instance(vB_Cache::CACHE_FAST);
     $thisUserid = vB::getCurrentSession()->get('userid');
     //pre-cache channels
     $channelids = $nodeids = array();
     $canUseRep = $userContext->hasPermission('genericpermissions', 'canuserep');
     foreach ($content as $key => $record) {
         if (!$this->checkComplete($record)) {
             unset($content[$key]);
         }
         if (!empty($record['channelid'])) {
             $channelids[$record['channelid']] = $record['channelid'];
         } else {
             if ($record['contenttypeid'] == $this->channelTypeId) {
                 $content[$key]['channelid'] = $record['nodeid'];
                 $channelids[$record['nodeid']] = $record['nodeid'];
             } else {
                 $starter = vB_Library::instance('node')->getNodeBare($record['starter']);
                 $content[$key]['channelid'] = $starter['parentid'];
                 $channelids[$starter['parentid']] = $starter['parentid'];
             }
         }
         $nodeids[] = $record['nodeid'];
     }
     // preload closure
     vB_Library::instance('node')->fetchClosureParent($nodeids);
     $channels = vB_Library::instance('node')->getNodes($channelids);
     //and preload channel permission data
     $channelPerms = vB::getUserContext()->fetchPermsForChannels($channelids);
     $needOnlineStatus = array();
     $needReputation = array();
     $contentUserids = array();
     $channelTypes = vB::getDatastore()->getValue('vBChannelTypes');
     //we can comment if there is at least one content type we can create, and the channel (in case this is a blog or
     //social group) doesn't have comments disabled, and either it's your and you have canreply
     $userid = vB::getCurrentSession()->get('userid');
     $commentsEnabled = vB::getDatastore()->getOption('postcommentthreads');
     $canmanageownprofile = $channelPerms['global']['canmanageownprofile'];
     foreach ($content as $key => $record) {
         $record['contenttypeclass'] = $contentTypeClass;
         $channelid = $record['channelid'];
         $thisChannelPerms = $channelPerms[$channelid];
         //$record['createpermissions'] = $thisChannelPerms['cancreate'];
         /*
          *	I'm making the assumption that the 'createpermissions' here is only used in the templates to check
          *	whether a REPLY to this specific node can be created or not. For an example, refer to their use in
          *	the contententry template. Note that if what we need is NOT supposed to be permissions to reply to
          *	this node, we need to fetch the correct permissions at that time. For an example, refer to the
          *	createcontent controller's loadEditor(), where it calls getCreatepermissionsForEdit().
          *	Since the permissions for replying to this node might be different from replying to the channel,
          *	we don't want to rely on the channel perm's 'cancreate'.
          *	PS. Never use these for "real" permission checking ("real" permission checking is in content api's validate())
          */
         $record['createpermissions'] = vB::getUserContext()->getCanCreate($record['nodeid']);
         $record['moderatorperms'] = $thisChannelPerms['moderate'];
         //channeltype
         if (isset($channelTypes[$channelid])) {
             $record['channeltype'] = $channelTypes[$channelid];
         } else {
             $record['channeltype'] = '';
         }
         $thisChannelPerms['global'] = $channelPerms['global'];
         if ($this->getCanEdit($record, $userContext, $thisChannelPerms)) {
             $record['canedit'] = 1;
         } else {
             $record['canedit'] = 0;
         }
         $record['canview'] = $thisChannelPerms['canview'];
         //There are four moderator-like permissions. Let's start setting them to zero. If the user has that
         // permissions we'll enable it soon.
         foreach (array('canmove', 'candeleteposts', 'candeletethread', 'canopenclose') as $permName) {
             $record[$permName] = 0;
         }
         if ($record['contenttypeid'] == $this->channelTypeId) {
             $record['canundeleteposts'] = $record['canremove'] = false;
             // TODO: GET RID OF $record['canremove']
         } else {
             $record['canremove'] = $thisChannelPerms['canremoveposts'];
             // TODO: GET RID OF $record['canremove']
             // Only the soft-delete mod permission grants undelete permission.
             // A user could get soft-delete permissions *without* undelete, which is why we leave
             // candeleteposts to be set by getCanDelete() below
             $record['canundeleteposts'] = $thisChannelPerms['moderate']['candeleteposts'];
             // TODO, update above with the new, real moderator permission when we work on VBV-12234
         }
         // showUnpublishedNotice is used by display_Topics_item template to show the X Unpublished notice
         // in channel view. Because we muck around with the "moderator-like" permissions, including
         // candeleteposts, we can't rely on just that in the templates, so we have to do this.
         // For reference, VBV-12177
         $record['showUnpublishedNotice'] = $thisChannelPerms['moderate']['candeleteposts'];
         // Hard delete & soft delete permissions can be independent.
         // For ex. canremoveposts doesn't give you soft-delete permissions, but does allow you to physically delete
         // The following values may be determined here in addition to 'candeletethread' & 'candeleteposts':
         $record['canharddeleteposts'] = 0;
         $record['moderatorperms']['canremoveposts'] = 0;
         // hard delete
         if ($this->getCanDelete($record, $userContext, $thisChannelPerms, true)) {
             // can hard delete
             $record['canharddeleteposts'] = 1;
             $record['moderatorperms']['canremoveposts'] = 1;
             // is this node a starter? That means they can delete the thread.
             if ($record['starter'] == $record['nodeid']) {
                 $record['candeletethread'] = 1;
             }
         }
         // soft delete
         if ($this->getCanDelete($record, $userContext, $thisChannelPerms, false)) {
             // can soft delete
             $record['candeleteposts'] = 1;
             // 'cansoftdeleteposts' is used just to ensure $record['canmoderate'] will be set to 1 below
             // so that topics will have a checkbox in channel view, VBV-12183. It's not used for anything else.
             // we can't just set $record['moderatorperms']['canremoveposts'], because that value is used for
             // physical-delete specific things in the templates.
             $record['moderatorperms']['cansoftdeleteposts'] = 1;
             // is this node a starter? That means they can delete the thread.
             if ($record['starter'] == $record['nodeid']) {
                 $record['candeletethread'] = 1;
             }
         }
         $record['moderate']['candeleteposts'] = $thisChannelPerms['moderate']['canundeleteposts'] = 0;
         // TODO: figure out what this does and remove if it does nothing
         $thisChannelPerms['canmoderateposts'] = $this->getCanModerate($record, $userContext, $thisChannelPerms);
         if ($thisChannelPerms['canmoderateposts']) {
             $record['canmoderate'] = $record['canmoderateposts'] = 1;
             $record['moderate']['canmoderateposts'] = $thisChannelPerms['moderate']['canmoderateposts'] = 1;
             // TODO: figure out what this does and remove if it does nothing
         } else {
             $record['canmoderate'] = 0;
         }
         //check the four 'my own' moderator-like permissions
         if ($record['showopen'] and $record['userid'] == $thisUserid) {
             //and the four moderator-like permissions for node owners.
             //move is for the topic, not replies & comments
             if ($record['nodeid'] == $record['starter'] and $thisChannelPerms['canmove']) {
                 $record['moderatorperms']['canmove'] = 1;
                 $record['moderatorperms']['canmovethread'] = 1;
             }
             if ($record['nodeid'] == $record['starter'] and $thisChannelPerms['canopenclose']) {
                 $record['moderatorperms']['canopenclose'] = 1;
             }
             // TODO: figure out a way to combine this & the following if blocks into the
             // getCanDelete() checks we do above.
             // Note, this is probably redundant due to 'cansoftdeleteposts' above.
             if ($record['nodeid'] == $record['starter'] and $thisChannelPerms['candeleteownthread']) {
                 // I don't think user_candeleteownpost is actually used in any templates. It seems to be used
                 // just so that $record['canmoderate'] will be set to 1 below, so that inline mod will be enabled.
                 // I'm leaving this alone for now, but there's probably a better way to do this.
                 $record['moderatorperms']['user_candeleteownpost'] = 1;
             }
             if ($record['nodeid'] != $record['starter'] and $thisChannelPerms['candeleteownpost']) {
                 $record['moderatorperms']['candeleteposts'] = 1;
             }
             if ($thisChannelPerms['caneditown']) {
                 $record['moderatorperms']['caneditpost'] = 1;
             }
         }
         // allow the receiver to manage their VMs if they have permission
         if (!empty($record['setfor']) and $record['setfor'] == $userid and $canmanageownprofile) {
             $record['canmoderateposts'] = 1;
             $record['candeleteposts'] = 1;
             $thisChannelPerms['moderate']['canmoderateposts'] = 1;
             // TODO: figure out what this does and remove if it does nothing
         }
         if ($this->textCountChange > 0 and $this->isPublished($record)) {
             $record['textcount_1'] = $record['textcount'] + 1;
             $record['totalcount_1'] = $record['totalcount'] + 1;
             if ($record['canmoderate']) {
                 $record['textcount_1'] += $record['textunpubcount'];
                 $record['totalcount_1'] += $record['totalunpubcount'];
             }
         } else {
             $record['textcount_1'] = $record['textcount'];
             $record['totalcount_1'] = $record['totalcount'];
         }
         // Add userinfo for reputation - is there a cached version?
         if ($record['userid'] > 0 and $record['contenttypeid'] != $this->channelTypeId) {
             $needReputation['vBUserRep_' . $record['userid']] = 'vBUserRep_' . $record['userid'];
         }
         $record['allow_post'] = $record['nodeoptions'] & vB_Api_Node::OPTION_ALLOW_POST ? 1 : 0;
         $record['moderate_comments'] = $record['nodeoptions'] & vB_Api_Node::OPTION_MODERATE_COMMENTS ? 1 : 0;
         $record['approve_membership'] = $record['nodeoptions'] & vB_Api_Node::OPTION_AUTOAPPROVE_MEMBERSHIP ? 1 : 0;
         $record['invite_only'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_INVITEONLY ? 1 : 0;
         $record['autoparselinks'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_PARSELINKS ? 1 : 0;
         $record['disablesmilies'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_DISABLE_SMILIES ? 1 : 0;
         $record['disable_bbcode'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_DISABLE_BBCODE ? 1 : 0;
         $record['hide_title'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_HIDE_TITLE ? 1 : 0;
         $record['hide_author'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_HIDE_AUTHOR ? 1 : 0;
         $record['hide_publishdate'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_HIDE_PUBLISHDATE ? 1 : 0;
         $record['display_fullincategory'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_DISPLAY_FULL_IN_CATEGORY ? 1 : 0;
         $record['display_pageviews'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_DISPLAY_PAGEVIEWS ? 1 : 0;
         $record['hide_comment_count'] = $record['nodeoptions'] & vB_Api_Node::OPTION_NODE_HIDE_COMMENT_COUNT ? 1 : 0;
         $record['can_flag'] = intval($userid) ? 1 : 0;
         //If this is not a channel, we need the user information to check reputation.
         if ($record['contenttypeid'] != $this->channelTypeId) {
             $contentUserids[] = $record['userid'];
             // these cache keys are set by vB_Library_User::preloadUserInfo
             $needOnlineStatus[$record['userid']] = "vb_UserInfo_{$record['userid']}_{$languageid}";
             //Now the moderator-type permissions
             if (!empty($record['moderatorperms'])) {
                 foreach ($record['moderatorperms'] as $key => $perm) {
                     if ($perm > 0 and $key != 'caneditpost') {
                         $record['canmoderate'] = 1;
                         break;
                     }
                 }
             }
         }
         $infractionLibrary = vB_Library::instance('content_infraction');
         $record['caninfract'] = $infractionLibrary->canInfractNode($record['nodeid'], $record) ? 1 : 0;
         $record['canviewnodeinfraction'] = $infractionLibrary->canViewNodeInfraction($record['nodeid'], $record) ? 1 : 0;
         $record['canseewholiked'] = $userContext->hasPermission('genericpermissions', 'canseewholiked') ? 1 : 0;
         // Let's make sure that these two are always set, so we don't run into undefine indices downstream somewhere.
         // Note that 'createpermissions' is instantiated above, near the beginning of this foreach body
         $record['can_comment'] = 0;
         $record['canreply'] = 0;
         //the channel permissions don't seem to use  vB_Api_Node::OPTION_ALLOW_POST and it appears to have
         //some special meaning for channels regarding comments so we'll handle channels seperately
         //If this is a channel we need to check canpostnew is the proper permission for channels
         if ($record['contenttypeid'] == $this->channelTypeId) {
             if (!$thisChannelPerms['canpostnew']) {
                 $record['createpermissions'] = false;
             }
             if (($record['nodeoptions'] & vB_Api_Node::OPTION_ALLOW_POST) > 0) {
                 $record['can_comment'] = (int) ($thisChannelPerms['cancomment'] and $commentsEnabled);
                 $record['canreply'] = $thisChannelPerms['canreply'];
             }
         } else {
             if ($record['starter'] == $record['nodeid']) {
                 $record['canreply'] = 0;
                 if (!$thisChannelPerms['canreply']) {
                     $record['createpermissions'] = false;
                 } else {
                     $record['canreply'] = ($record['nodeoptions'] & vB_Api_Node::OPTION_ALLOW_POST) > 0 ? 1 : 0;
                 }
             } else {
                 // per VBV-4523, commenting requires BOTH cancomment AND canreply
                 if (!($thisChannelPerms['cancomment'] and $thisChannelPerms['canreply'])) {
                     $record['createpermissions'] = false;
                 }
                 //if comments are disabled, then ... don't allow comments.
                 if (($record['nodeoptions'] & vB_Api_Node::OPTION_ALLOW_POST) > 0 and $commentsEnabled) {
                     $record['can_comment'] = ($thisChannelPerms['cancomment'] and $thisChannelPerms['canreply']) ? 1 : 0;
                     if ($thisChannelPerms['cancomment'] and !empty($record['starter'])) {
                         //If we were called with fullcontent then we already have the channel.
                         if (empty($record['channelid'])) {
                             $thisParent = $this->nodeApi->getNode($record['starter']);
                             $record['channelid'] = $thisParent['parentid'];
                         }
                         if (empty($channels[$record['channelid']])) {
                             $channels[$record['channelid']] = $this->nodeApi->getNode($record['channelid']);
                         }
                         //special interpretation of vB_Api_Node::OPTION_ALLOW_POST) for channels if that's not
                         //set then replies in this channel shouldn't allow comments.
                         //We need to check the nodeoptions field.
                         if (($channels[$record['channelid']]['nodeoptions'] & vB_Api_Node::OPTION_ALLOW_POST) == 0) {
                             $record['can_comment'] = 0;
                         }
                     }
                 }
             }
         }
         /*
          * Note 2014-02-19: We should remove 'canremove'. It doesn't really do anything outside of unit tests
          *	currently. Not to confuse this with the 'canremove' checked in editor_contenttype_Text_comment template.
          *	That's set in the createcontent controller.
          *	I haven't removed it yet because it would cause a bunch of unit test failures, since they still check for
          *	this even though it's not used anymore.
          */
         $record['permissions'] = array('canedit' => $record['canedit'], 'canmoderate' => $record['canmoderate'], 'canvote' => $thisChannelPerms['canvote'] ? 1 : 0, 'canuserep' => $canUseRep ? 1 : 0, 'canremove' => $record['canremove'], 'can_flag' => $record['can_flag'], 'canviewthreads' => $thisChannelPerms['canviewthreads'], 'canviewothers' => $thisChannelPerms['canviewothers'], 'caninfract' => $record['caninfract'], 'canviewnodeinfraction' => $record['canviewnodeinfraction'], 'canseewholiked' => $record['canseewholiked'], 'can_comment' => $record['can_comment']);
         // can't like an infraction
         if ($record['permissions']['canuserep'] and $this->contenttype == 'vBForum_Infraction') {
             $record['permissions']['canuserep'] = 0;
         }
         $record['moderatorperms']['canharddeleteposts'] = (int) $record['canharddeleteposts'];
         $record['moderatorperms']['candeleteposts'] = (int) $record['candeleteposts'];
         $record['moderatorperms']['canundeleteposts'] = (int) $record['canundeleteposts'];
         $record['moderatorperms']['candeletethread'] = empty($record['candeletethread']) ? 0 : 1;
         $record['moderatorperms']['canmoderateposts'] = empty($record['canmoderateposts']) ? 0 : 1;
         $results[$record['nodeid']] = $record;
     }
     if (!empty($contentUserids)) {
         vB_Library::instance('user')->preloadUserInfo($contentUserids);
         // Add online status
         require_once DIR . '/includes/functions_bigthree.php';
         // we just preloaded this info, so there must be a cache hit
         $cached = $fastCache->read($needOnlineStatus);
         $loadedSigPerm = array();
         foreach ($results as $key => $record) {
             if ($record['userid'] == 0) {
                 continue;
             }
             $cache_key = "vb_UserInfo_{$record['userid']}_{$languageid}";
             $authorInfo = $cached[$cache_key];
             $results[$key]['signature'] = $authorInfo['signature'];
             if (!empty($authorInfo['signature'])) {
                 if (empty($loadedSigPerm[$record['userid']])) {
                     $loadedSigPerm[$record['userid']] = vB::getUserContext($record['userid'])->hasPermission('genericpermissions', 'canusesignature');
                 }
                 $results[$key]['canSign'] = $loadedSigPerm[$record['userid']] ? 1 : 0;
             }
             $results[$key]['musername'] = vB_Api::instanceInternal("user")->fetchMusername($authorInfo);
             if (!isset($authorInfo['online'])) {
                 fetch_online_status($authorInfo);
             }
             $results[$key]['online'] = $authorInfo['online'];
             $options = vB::getDatastore()->getValue('options');
             if (!empty($options['postelements']) and $options['postelements'] == 4 and ($authorInfo['ipoints'] or $authorInfo['warnings'] or $authorInfo['infractions']) and ($userContext->hasPermission('genericpermissions', 'canreverseinfraction') or $userContext->hasPermission('genericpermissions', 'canseeinfraction') or $userContext->hasPermission('genericpermissions', 'cangiveinfraction') or vB::getCurrentSession()->get('userid') == $authorInfo['userid'])) {
                 $results[$key]['postelements'] = $options['postelements'];
                 $results[$key]['ipoints'] = $authorInfo['ipoints'];
                 $results[$key]['warnings'] = $authorInfo['warnings'];
                 $results[$key]['infractions'] = $authorInfo['infractions'];
             }
         }
     }
     if (!empty($needReputation)) {
         $cached = $cache->read($needReputation);
         foreach ($content as $record) {
             // Add userinfo for reputation - is there a cached version?
             if ($record['userid'] > 0 and $record['contenttypeid'] != $this->channelTypeId) {
                 if ($cached['vBUserRep_' . $record['userid']] !== false) {
                     $cacheitem = $cached['vBUserRep_' . $record['userid']];
                     $results[$record['nodeid']]['reputation'] = $cacheitem['reputation'];
                     $results[$record['nodeid']]['showreputation'] = $cacheitem['showreputation'];
                     $results[$record['nodeid']]['reputationlevelid'] = $cacheitem['reputationlevelid'];
                     $results[$record['nodeid']]['reputationpower'] = $cacheitem['reputationpower'];
                     $results[$record['nodeid']]['reputationimg'] = $cacheitem['reputationimg'];
                 } else {
                     $needUserRep[$record['nodeid']] = $record['userid'];
                 }
             }
         }
     }
     //Now add reputation for any users for which we didn't have a cached value.
     if (!empty($needUserRep)) {
         $reputationLib = vB_Library::instance('reputation');
         $userInfo = $this->assertor->assertQuery('user', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, 'userid' => $needUserRep));
         $bf_misc_useroptions = vB::getDatastore()->getValue('bf_misc_useroptions');
         $userReps = array();
         //build the reputation information
         foreach ($userInfo as $authorInfo) {
             $userid = $authorInfo['userid'];
             $userReps[$userid] = array();
             $userReps[$userid]['reputation'] = $authorInfo['reputation'];
             $userReps[$userid]['showreputation'] = $authorInfo['options'] & $bf_misc_useroptions['showreputation'];
             $userReps[$userid]['reputationlevelid'] = $authorInfo['reputationlevelid'];
             $userReps[$userid]['reputationpower'] = $reputationLib->fetchReppower($authorInfo);
             $userReps[$userid]['reputationimg'] = $reputationLib->fetchReputationImageInfo($authorInfo);
             //cache this for a day
             $cache->write('vBUserRep_' . $userid, $userReps[$userid], 1440, array("fUserContentChg_{$userid}", "userChg_{$userid}"));
         }
         foreach ($needUserRep as $nodeid => $userid) {
             if (!empty($userReps[$userid])) {
                 foreach ($userReps[$userid] as $field => $val) {
                     $results[$nodeid][$field] = $val;
                 }
             }
         }
     }
     // censor textual node items
     vB_Library_Node::censorNodes($results);
     return $results;
 }
Exemplo n.º 10
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;
}
Exemplo n.º 11
0
function do_stats()
{
    global $vbulletin, $db;
    $activeusers = '';
    if (($vbulletin->options['displayloggedin'] == 1 or $vbulletin->options['displayloggedin'] == 2 or $vbulletin->options['displayloggedin'] > 2 and $vbulletin->userinfo['userid']) and !$show['search_engine']) {
        $datecut = TIMENOW - $vbulletin->options['cookietimeout'];
        $numbervisible = 0;
        $numberregistered = 0;
        $numberguest = 0;
        $hook_query_fields = $hook_query_joins = $hook_query_where = '';
        ($hook = vBulletinHook::fetch_hook('forumhome_loggedinuser_query')) ? eval($hook) : false;
        $forumusers = $db->query_read_slave("\n\t    SELECT\n\t    user.username, (user.options & " . $vbulletin->bf_misc_useroptions['invisible'] . ") AS invisible, user.usergroupid, user.lastvisit,\n\t    session.userid, session.inforum, session.lastactivity, session.badlocation,\n\t    IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid\n\t    {$hook_query_fields}\n\t    FROM " . TABLE_PREFIX . "session AS session\n\t    LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = session.userid)\n\t    {$hook_query_joins}\n\t    WHERE session.lastactivity > {$datecut}\n\t    {$hook_query_where}\n\t    " . iif($vbulletin->options['displayloggedin'] == 1 or $vbulletin->options['displayloggedin'] == 3, "ORDER BY username ASC") . "\n\t    ");
        if ($vbulletin->userinfo['userid']) {
            // fakes the user being online for an initial page view of index.php
            $vbulletin->userinfo['joingroupid'] = iif($vbulletin->userinfo['displaygroupid'], $vbulletin->userinfo['displaygroupid'], $vbulletin->userinfo['usergroupid']);
            $userinfos = array($vbulletin->userinfo['userid'] => array('userid' => &$vbulletin->userinfo['userid'], 'username' => &$vbulletin->userinfo['username'], 'invisible' => &$vbulletin->userinfo['invisible'], 'inforum' => 0, 'lastactivity' => TIMENOW, 'lastvisit' => &$vbulletin->userinfo['lastvisit'], 'usergroupid' => &$vbulletin->userinfo['usergroupid'], 'displaygroupid' => &$vbulletin->userinfo['displaygroupid'], 'infractiongroupid' => &$vbulletin->userinfo['infractiongroupid']));
        } else {
            $userinfos = array();
        }
        $inforum = array();
        while ($loggedin = $db->fetch_array($forumusers)) {
            $userid = $loggedin['userid'];
            if (!$userid) {
                // Guest
                $numberguest++;
                if (!isset($inforum["{$loggedin['inforum']}"])) {
                    $inforum["{$loggedin['inforum']}"] = 0;
                }
                if (!$loggedin['badlocation']) {
                    $inforum["{$loggedin['inforum']}"]++;
                }
            } else {
                if (empty($userinfos["{$userid}"]) or $userinfos["{$userid}"]['lastactivity'] < $loggedin['lastactivity']) {
                    $userinfos["{$userid}"] = $loggedin;
                }
            }
        }
        if (!$vbulletin->userinfo['userid'] and $numberguest == 0) {
            $numberguest++;
        }
        foreach ($userinfos as $userid => $loggedin) {
            $numberregistered++;
            if ($userid != $vbulletin->userinfo['userid'] and !$loggedin['badlocation']) {
                if (!isset($inforum["{$loggedin['inforum']}"])) {
                    $inforum["{$loggedin['inforum']}"] = 0;
                }
                $inforum["{$loggedin['inforum']}"]++;
            }
            fetch_musername($loggedin);
            ($hook = vBulletinHook::fetch_hook('forumhome_loggedinuser')) ? eval($hook) : false;
            if (fetch_online_status($loggedin)) {
                $numbervisible++;
            }
        }
        // memory saving
        unset($userinfos, $loggedin);
        $db->free_result($forumusers);
        $totalonline = $numberregistered + $numberguest;
        $numberinvisible = $numberregistered - $numbervisible;
        // ### MAX LOGGEDIN USERS ################################
        if (intval($vbulletin->maxloggedin['maxonline']) <= $totalonline) {
            $vbulletin->maxloggedin['maxonline'] = $totalonline;
            $vbulletin->maxloggedin['maxonlinedate'] = TIMENOW;
            build_datastore('maxloggedin', serialize($vbulletin->maxloggedin), 1);
        }
        $recordusers = vb_number_format($vbulletin->maxloggedin['maxonline']);
        $recorddate = vbdate($vbulletin->options['dateformat'], $vbulletin->maxloggedin['maxonlinedate'], true);
        $recordtime = vbdate($vbulletin->options['timeformat'], $vbulletin->maxloggedin['maxonlinedate']);
        $showloggedinusers = true;
    } else {
        $showloggedinusers = false;
    }
    cache_ordered_forums(1, 1);
    // get total threads & posts from the forumcache
    $totalthreads = 0;
    $totalposts = 0;
    if (is_array($vbulletin->forumcache)) {
        foreach ($vbulletin->forumcache as $forum) {
            $totalthreads += $forum['threadcount'];
            $totalposts += $forum['replycount'];
        }
    }
    $totalthreads = vb_number_format($totalthreads);
    $totalposts = vb_number_format($totalposts);
    // get total members and newest member from template
    $numbermembers = vb_number_format($vbulletin->userstats['numbermembers']);
    $newuserinfo = array('userid' => $vbulletin->userstats['newuserid'], 'username' => $vbulletin->userstats['newusername']);
    $activemembers = vb_number_format($vbulletin->userstats['activemembers']);
    $showactivemembers = ($vbulletin->options['activememberdays'] > 0 and $vbulletin->options['activememberoptions'] & 2) ? true : false;
    $out = array('threads' => $totalthreads, 'posts' => $totalposts, 'members' => $numbermembers, 'newuser' => $newuserinfo['username']);
    $out = array_merge($out, array('record_users' => $recordusers, 'record_date' => $recorddate . ' ' . $recordtime, 'online_members' => $numberregistered, 'online_guests' => $numberguest));
    $top = $db->query_first_slave("SELECT username FROM " . TABLE_PREFIX . "user ORDER BY posts DESC LIMIT 1");
    if ($top['username']) {
        $out['top_poster'] = $top['username'];
    } else {
        $out['top_poster'] = 'N/A';
    }
    if ($showactivemembers) {
        $out['active_members'] = $activemembers;
    } else {
        $out['active_members'] = 'N/A';
    }
    return $out;
    return array('top_poster' => '');
}
Exemplo n.º 12
0
 /** This preloads information for a list of userids, so it will be available for userContext and other data loading
 
 	@param 	mixed	array of integers
 
 	 */
 public function preloadUserInfo($userids)
 {
     if (empty($userids) or !is_array($userids)) {
         //no harm here. Just nothing to do.
         return;
     }
     $userids = array_unique($userids);
     //first we can remove anything that already has been loaded.
     $fastCache = vB_Cache::instance(vB_Cache::CACHE_FAST);
     $languageid = vB::getCurrentSession()->get('languageid');
     $cacheKeys = array();
     foreach ($userids as $key => $userid) {
         //If we already have userinfo in cache we'll have the others
         $infoKey = "vb_UserInfo_{$userid}" . '_' . $languageid;
         if ($fastCache->read($infoKey)) {
             unset($userids[$key]);
             continue;
         }
         //See if we have a cached version we can use.
         $cacheKeys[$userid] = "vb_UserWPerms_{$userid}" . '_' . $languageid;
     }
     //Now let's see what we can get from large cache
     if (!empty($cacheKeys)) {
         $cached = vB_Cache::instance(vB_Cache::CACHE_LARGE)->read($cacheKeys);
         $needLast = array();
         foreach ($cacheKeys as $userid => $cacheKey) {
             if (!empty($cached[$cacheKey])) {
                 $needLast[] = $userid;
             }
         }
         if (!empty($needLast)) {
             $lastData = array();
             $lastActivityQuery = vB::getDbAssertor()->assertQuery('user', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, vB_dB_Query::COLUMNS_KEY => array('userid', 'lastactivity'), vB_dB_Query::CONDITIONS_KEY => array('userid' => $needLast)));
             foreach ($lastActivityQuery as $lastRecord) {
                 $lastData[$lastRecord['userid']] = $lastRecord['lastactivity'];
             }
             foreach ($cacheKeys as $userid => $cacheKey) {
                 if (!empty($cached[$cacheKey])) {
                     /* VBV-10856: fetchUserWithPerms() expects true/false as its third parameter.
                        $lastData[$userid] was being passed to it below, which triggered a PHP notice
                        (Undefined offset) if it wasnt set. I have altered it to send true/false instead. */
                     $this->fetchUserWithPerms($userid, $languageid, isset($lastData[$userid]));
                     unset($cacheKeys[$userid]);
                 }
             }
         }
     }
     //Now let's see what's left
     if (!empty($cacheKeys)) {
         $assertor = vB::getDbAssertor();
         //First get userinfo. We cannot use a table query since we also need signature
         $userQry = $assertor->assertQuery('fetchUserinfo', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_METHOD, 'userid' => array_keys($cacheKeys)));
         if (!$userQry->valid()) {
             return;
         }
         foreach ($userQry as $userInfo) {
             $userid = $userInfo['userid'];
             fetch_online_status($userInfo);
             $primary_group_id = $userInfo['usergroupid'];
             $secondary_group_ids = !empty($userInfo['membergroupids']) ? explode(',', str_replace(' ', '', $userInfo['membergroupids'])) : array();
             $infraction_group_ids = !empty($userInfo['infractiongroupids']) ? explode(',', str_replace(' ', '', $userInfo['infractiongroupids'])) : array();
             $usergroups = array('groupid' => $primary_group_id, 'secondary' => $secondary_group_ids, 'infraction' => $infraction_group_ids);
             $fastCache->write("vb_UserInfo_{$userid}" . '_' . $languageid, $userInfo, 5, "userChg_{$userid}");
         }
     }
 }
Exemplo n.º 13
0
function do_get_profile()
{
    global $vbulletin, $db, $show, $vbphrase, $permissions, $imodcache;
    $vbulletin->input->clean_array_gpc('r', array('userid' => TYPE_UINT));
    if (!$vbulletin->userinfo['userid'] && !$vbulletin->GPC['userid']) {
        json_error(ERR_INVALID_LOGGEDIN, RV_NOT_LOGGED_IN);
    }
    if (!($permissions['forumpermissions'] & $vbulletin->bf_ugp_forumpermissions['canview']) or !($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canviewmembers'])) {
        json_error(ERR_NO_PERMISSION);
    }
    if (!$vbulletin->GPC['userid']) {
        $vbulletin->GPC['userid'] = $vbulletin->userinfo['userid'];
    }
    $fetch_userinfo_options = FETCH_USERINFO_AVATAR | FETCH_USERINFO_LOCATION | FETCH_USERINFO_PROFILEPIC | FETCH_USERINFO_SIGPIC | FETCH_USERINFO_USERCSS | FETCH_USERINFO_ISFRIEND;
    $userinfo = verify_id('user', $vbulletin->GPC['userid'], 1, $fetch_userinfo_options);
    if ($userinfo['usergroupid'] == 4 and !($permissions['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel'])) {
        json_error(ERR_NO_PERMISSION);
    }
    $posts = $userinfo['posts'];
    $joindate = vbdate($vbulletin->options['dateformat'], $userinfo['joindate']);
    $out = array('username' => html_entity_decode($userinfo['username']), 'online' => fetch_online_status($userinfo, false), 'avatar_upload' => $vbulletin->options['avatarenabled'] && $permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['canuseavatar'], 'posts' => $posts, 'joindate' => $joindate);
    $avatarurl_info = fetch_avatar_url($userinfo['userid']);
    if ($avatarurl_info) {
        $out['avatarurl'] = process_avatarurl($avatarurl_info[0]);
    }
    cache_moderators();
    $canbanuser = ($vbulletin->userinfo['permissions']['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel'] or can_moderate(0, 'canbanusers'));
    if ($canbanuser) {
        $out['ban'] = true;
    }
    $groups = array();
    // About
    $out_group = array('name' => 'about', 'values' => array(array('name' => prepare_utf8_string($vbphrase['posts']), 'value' => strval(vb_number_format($userinfo['posts']))), array('name' => prepare_utf8_string($vbphrase['join_date']), 'value' => vbdate($vbulletin->options['dateformat'], $userinfo['joindate']))));
    if (function_exists('itrader_user')) {
        itrader_user($userinfo);
        $out_group['values'][] = array('name' => 'iTrader', 'value' => vb_number_format($userinfo['tradescore']) . ', ' . $userinfo['tradepcnt'] . '%');
        $out += array('itrader_score' => vb_number_format($userinfo['tradescore']), 'itrader_percent' => $userinfo['tradepcnt'] . '%');
    }
    $groups[] = $out_group;
    $profileobj = new vB_UserProfile($vbulletin, $userinfo);
    $blockfactory = new vB_ProfileBlockFactory($vbulletin, $profileobj);
    $profileblock =& $blockfactory->fetch('ProfileFields');
    $profileblock->build_field_data(false);
    $profile = $profileblock->categories[0];
    // Additional information
    if (count($profile)) {
        $out_group = array('name' => 'additional');
        foreach ($profile as $profilefield) {
            $field_value = $userinfo["field{$profilefield['profilefieldid']}"];
            fetch_profilefield_display($profilefield, $field_value);
            if (!strlen(trim($field_value))) {
                continue;
            }
            $out_group['values'][] = array('name' => prepare_utf8_string($profilefield['title']), 'value' => prepare_utf8_string($profilefield['value']));
        }
        if (count($out_group['values'])) {
            $groups[] = $out_group;
        }
    }
    $out['groups'] = $groups;
    return $out;
}
Exemplo n.º 14
0
function do_get_pm()
{
    global $vbulletin, $db;
    require_once DIR . '/includes/class_postbit.php';
    require_once DIR . '/includes/functions_bigthree.php';
    $vbulletin->input->clean_array_gpc('r', array('pmid' => TYPE_UINT, 'showhistory' => TYPE_BOOL));
    ($hook = vBulletinHook::fetch_hook('private_showpm_start')) ? eval($hook) : false;
    $pm = $db->query_first_slave("\n\t\tSELECT\n\t\t\tpm.*, pmtext.*,\n\t\t\t" . iif($vbulletin->options['privallowicons'], "icon.title AS icontitle, icon.iconpath,") . "\n\t\t\tIF(ISNULL(pmreceipt.pmid), 0, 1) AS receipt, pmreceipt.readtime, pmreceipt.denied,\n\t\t\tsigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline, sigpic.width AS sigpicwidth, sigpic.height AS sigpicheight\n\t\tFROM " . TABLE_PREFIX . "pm AS pm\n\t\tLEFT JOIN " . TABLE_PREFIX . "pmtext AS pmtext ON(pmtext.pmtextid = pm.pmtextid)\n\t\t" . iif($vbulletin->options['privallowicons'], "LEFT JOIN " . TABLE_PREFIX . "icon AS icon ON(icon.iconid = pmtext.iconid)") . "\n\t\tLEFT JOIN " . TABLE_PREFIX . "pmreceipt AS pmreceipt ON(pmreceipt.pmid = pm.pmid)\n\t\tLEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON(sigpic.userid = pmtext.fromuserid)\n\t\tWHERE pm.userid=" . $vbulletin->userinfo['userid'] . " AND pm.pmid=" . $vbulletin->GPC['pmid'] . "\n\t");
    if (!$pm) {
        json_error(strip_tags(fetch_error('invalidid', $vbphrase['private_message'], $vbulletin->options['contactuslink'])));
    }
    $folderjump = construct_folder_jump(0, $pm['folderid']);
    // do read receipt
    $show['receiptprompt'] = $show['receiptpopup'] = false;
    if ($pm['receipt'] == 1 and $pm['readtime'] == 0 and $pm['denied'] == 0) {
        if ($permissions['pmpermissions'] & $vbulletin->bf_ugp_pmpermissions['candenypmreceipts']) {
            // set it to denied just now as some people might have ad blocking that stops the popup appearing
            $show['receiptprompt'] = $show['receiptpopup'] = true;
            $receipt_question_js = addslashes_js(construct_phrase($vbphrase['x_has_requested_a_read_receipt'], unhtmlspecialchars($pm['fromusername'])), '"');
            $db->shutdown_query("UPDATE " . TABLE_PREFIX . "pmreceipt SET denied = 1 WHERE pmid = {$pm['pmid']}");
        } else {
            // they can't deny pm receipts so do not show a popup or prompt
            $db->shutdown_query("UPDATE " . TABLE_PREFIX . "pmreceipt SET readtime = " . TIMENOW . " WHERE pmid = {$pm['pmid']}");
        }
    } else {
        if ($pm['receipt'] == 1 and $pm['denied'] == 1) {
            $show['receiptprompt'] = true;
        }
    }
    $postbit_factory = new vB_Postbit_Factory();
    $postbit_factory->registry =& $vbulletin;
    $postbit_factory->cache = array();
    $postbit_factory->bbcode_parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
    $postbit_obj =& $postbit_factory->fetch_postbit('pm');
    $pm_postbit = $pm;
    $postbit = $postbit_obj->construct_postbit($pm_postbit);
    // update message to show read
    if ($pm['messageread'] == 0) {
        $db->shutdown_query("UPDATE " . TABLE_PREFIX . "pm SET messageread=1 WHERE userid=" . $vbulletin->userinfo['userid'] . " AND pmid={$pm['pmid']}");
        if ($pm['folderid'] >= 0) {
            $userdm =& datamanager_init('User', $vbulletin, ERRTYPE_SILENT);
            $userdm->set_existing($vbulletin->userinfo);
            $userdm->set('pmunread', 'IF(pmunread >= 1, pmunread - 1, 0)', false);
            $userdm->save(true, true);
            unset($userdm);
        }
    }
    $cclist = array();
    $bcclist = array();
    $ccrecipients = '';
    $bccrecipients = '';
    $touser = unserialize($pm['touserarray']);
    if (!is_array($touser)) {
        $touser = array();
    }
    foreach ($touser as $key => $item) {
        if (is_array($item)) {
            foreach ($item as $subkey => $subitem) {
                $userinfo = array('userid' => $subkey, 'username' => $subitem);
                $templater = vB_Template::create('pm_messagelistbit_user');
                $templater->register('userinfo', $userinfo);
                ${$key . 'list'}[] = $templater->render();
            }
        } else {
            $userinfo = array('username' => $item, 'userid' => $key);
            $templater = vB_Template::create('pm_messagelistbit_user');
            $templater->register('userinfo', $userinfo);
            $bcclist[] = $templater->render();
        }
    }
    if (count($cclist) > 1 or is_array($touser['cc']) and !in_array($vbulletin->userinfo['username'], $touser['cc']) or $vbulletin->userinfo['userid'] == $pm['fromuserid'] and $pm['folderid'] == -1) {
        if (!empty($cclist)) {
            $ccrecipients = implode("\r\n", $cclist);
        }
        if (!empty($bcclist) and $vbulletin->userinfo['userid'] == $pm['fromuserid'] and $pm['folderid'] == -1) {
            if (empty($cclist) and count($bcclist == 1)) {
                $ccrecipients = implode("\r\n", $bcclist);
            } else {
                $bccrecipients = implode("\r\n", $bcclist);
            }
        }
        $show['recipients'] = true;
    }
    $pm['senddate'] = vbdate($vbulletin->options['dateformat'], $pm['dateline']);
    $pm['sendtime'] = vbdate($vbulletin->options['timeformat'], $pm['dateline']);
    list($text, $nuked_quotes, $images) = parse_post($pm['message'], $vbulletin->options['privallowsmilies'] && $usesmiles);
    $fr_images = array();
    foreach ($images as $image) {
        $fr_images[] = array('img' => $image);
    }
    // Avatar work
    $avatarurl = '';
    if ($pm_postbit['avatarurl']) {
        $avatarurl = process_avatarurl($pm_postbit['avatarurl']);
    }
    $to_users = unserialize($pm['touserarray']);
    $users = array();
    if ($to_users !== false) {
        if ($to_users['cc']) {
            $users = $to_users['cc'];
        } else {
            $users = $to_users;
        }
    }
    $out = array('id' => $pm['pmid'], 'pm_unread' => $pm['messageread'] == 0, 'username' => prepare_utf8_string(strip_tags($pm['fromusername'])), 'to_usernames' => prepare_utf8_string(implode('; ', $users)), 'userid' => $pm['fromuserid'], 'title' => prepare_utf8_string($pm['title']), 'online' => fetch_online_status(fetch_userinfo($pm['fromuserid']), false), 'message' => $text, 'quotable' => $nuked_quotes, 'fr_images' => $fr_images, 'pm_timestamp' => prepare_utf8_string(date_trunc($pm['senddate'] . ' ' . $pm['sendtime'])));
    if ($avatarurl != '') {
        $out['avatarurl'] = $avatarurl;
    }
    return $out;
}
Exemplo n.º 15
0
     $activeusers[$numberregistered] = $loggedin;
     $doneuser["{$vbulletin->userinfo['userid']}"] = 1;
 }
 // this requires the query to have lastactivity ordered by DESC so that the latest location will be the first encountered.
 while ($loggedin = $db->fetch_array($threadusers)) {
     if ($loggedin['badlocation']) {
         continue;
     }
     if (empty($doneuser["{$loggedin['userid']}"])) {
         if ($loggedin['inthread'] == $threadinfo['threadid']) {
             if ($loggedin['userid'] == 0) {
                 $numberguest++;
             } else {
                 $numberregistered++;
                 ($hook = vBulletinHook::fetch_hook('showthread_loggedinuser')) ? eval($hook) : false;
                 if (fetch_online_status($loggedin)) {
                     $numbervisible++;
                     fetch_musername($loggedin);
                     $loggedin['comma'] = $vbphrase['comma_space'];
                     $activeusers[$numbervisible] = $loggedin;
                 }
             }
         }
         if ($loggedin['userid']) {
             $doneuser["{$loggedin['userid']}"] = 1;
         }
     }
 }
 // Last element
 if ($numbervisible) {
     $activeusers[$numbervisible]['comma'] = '';
Exemplo n.º 16
0
 /**
  * Prepare any data needed for the output
  *
  * @param	string	The id of the block
  * @param	array	Options specific to the block
  */
 function prepare_output($id = '', $options = array())
 {
     global $show, $vbphrase;
     if ($this->profile->userinfo['friendcount'] != 0) {
         require_once DIR . '/includes/functions_bigthree.php';
         $this->block_data = array();
         if (is_array($options)) {
             $options = array_merge($this->option_defaults, $options);
         } else {
             $options = $this->option_defaults;
         }
         switch ($options['fetchorder']) {
             case 'asc':
                 $friendorder = 'user.username ASC';
                 break;
             case 'desc':
                 $friendorder = 'user.username DESC';
                 break;
             case 'rand':
             default:
                 $friendorder = 'RAND()';
         }
         $pagenumber = $options['pagenumber'];
         if (isset($options['perpage'])) {
             $perpage = $options['perpage'];
         } else {
             $perpage = $options['fetchamount'];
         }
         if (!$pagenumber or $options['tab'] != $id or empty($options['tab'])) {
             $pagenumber = 1;
         } else {
             if ($pagenumber > ceil($this->profile->userinfo['friendcount'] / $perpage)) {
                 $pagenumber = ceil($this->profile->userinfo['friendcount'] / $perpage);
             }
         }
         $limitstart = ($pagenumber - 1) * $perpage;
         $limitamount = max(1, min($perpage, $this->profile->userinfo['friendcount'] - $limitstart));
         $hook_query_fields = $hook_query_joins = $hook_query_where = '';
         ($hook = vBulletinHook::fetch_hook('member_profileblock_friends_query')) ? eval($hook) : false;
         $friends_sql = $this->registry->db->query_read_slave("\n\t\t\t\tSELECT user.*, (user.options & " . $this->registry->bf_misc_useroptions['invisible'] . ") AS invisible " . ($this->registry->options['avatarenabled'] ? ", avatar.avatarpath, NOT ISNULL(customavatar.userid) AS hascustom, customavatar.dateline AS avatardateline, customavatar.filedata_thumb, customavatar.height AS avheight, customavatar.width AS avwidth, customavatar.width_thumb AS avwidth_thumb, customavatar.height_thumb AS avheight_thumb" : "") . "\n\t\t\t\t\t{$hook_query_fields}\n\t\t\t\tFROM " . TABLE_PREFIX . "userlist AS userlist\n\t\t\t\tINNER JOIN " . TABLE_PREFIX . "user AS user ON (user.userid = userlist.relationid)" . ($this->registry->options['avatarenabled'] ? "\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON (avatar.avatarid = user.avatarid)\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON (customavatar.userid = user.userid) " : '') . "\n\t\t\t\t{$hook_query_joins}\n\t\t\t\tWHERE userlist.userid = " . $this->profile->userinfo['userid'] . "\n\t\t\t\t\tAND userlist.type = 'buddy'\n\t\t\t\t\tAND userlist.friend = 'yes'\n\t\t\t\t\t{$hook_query_where}\n\t\t\t\tORDER BY {$friendorder}\n\t\t\t\tLIMIT {$limitstart}, {$limitamount}\n\t\t\t");
         $friendbits = '';
         $alt = 'alt2';
         while ($user = $this->registry->db->fetch_array($friends_sql)) {
             fetch_avatar_from_userinfo($user, true);
             fetch_musername($user);
             $alt = $alt == 'alt1' ? 'alt2' : 'alt1';
             fetch_online_status($user, true);
             construct_im_icons($user, true);
             if ($user['userid'] == $this->registry->userinfo['userid'] or $this->profile->userinfo['userid'] == $this->registry->userinfo['userid']) {
                 if ($user['userid'] == $this->registry->userinfo['userid']) {
                     $show['return'] = true;
                     $remove = array('userid' => $this->profile->userinfo['userid'], 'return' => 1);
                 } else {
                     $remove = array('userid' => $user['userid']);
                 }
                 $show['breakfriendship'] = true;
             } else {
                 $show['breakfriendship'] = false;
             }
             ($hook = vBulletinHook::fetch_hook('member_profileblock_friendbit')) ? eval($hook) : false;
             $templater = vB_Template::create($options['membertemplate']);
             $templater->register('remove', $remove);
             $templater->register('user', $user);
             $friendbits .= $templater->render();
         }
         $pageinfo = array('tab' => $id);
         if ($perpage != $this->registry->options['friends_perpage']) {
             $paginfo['pp'] = $perpage;
         }
         $this->block_data['start_friends'] = $limitstart + 1;
         $this->block_data['friendbits'] = $friendbits;
         $this->block_data['showtotal'] = vb_number_format($this->registry->db->num_rows($friends_sql));
         $this->block_data['end_friends'] = $limitstart + $this->block_data['showtotal'];
         sanitize_pageresults($this->profile->userinfo['friendcount'], $pagenumber, $perpage, 100, 5);
         $this->block_data['pagenav'] = construct_page_nav($pagenumber, $perpage, $this->profile->userinfo['friendcount'], '', '', $id, 'member', $this->profile->userinfo, $pageinfo);
     }
 }
Exemplo n.º 17
0
 $offlineusers = '';
 $newusersound = '';
 $lastonline = array();
 if (isset($buddies)) {
     $buddies = urldecode($buddies);
     $lastonline = explode(' ', $buddies);
 }
 $buddies = '0 ';
 $show['playsound'] = false;
 require_once DIR . '/includes/functions_bigthree.php';
 while ($buddy = $db->fetch_array($buddys)) {
     if ($doneuser["{$buddy['userid']}"]) {
         continue;
     }
     $doneuser["{$buddy['userid']}"] = true;
     if ($onlineresult = fetch_online_status($buddy)) {
         if ($onlineresult == 1) {
             $buddy['statusicon'] = 'online';
         } else {
             $buddy['statusicon'] = 'invisible';
         }
         $buddies .= $buddy['userid'] . ' ';
     } else {
         $buddy['statusicon'] = 'offline';
     }
     $show['highlightuser'] = false;
     ($hook = vBulletinHook::fetch_hook('misc_buddylist_bit')) ? eval($hook) : false;
     if ($buddy['statusicon'] != 'offline') {
         if (!in_array($buddy['userid'], $lastonline) and !empty($lastonline)) {
             $show['playsound'] = true;
             $show['highlightuser'] = true;
Exemplo n.º 18
0
 require_once DIR . '/includes/class_bbcode.php';
 $bbcode_parser =& new vB_BbCodeParser($vbulletin, fetch_tag_list());
 $photoplog_userid_list = 0;
 while ($photoplog_rate_info = $db->fetch_array($photoplog_rate_infos)) {
     $photoplog_userid_list .= ', ' . intval($photoplog_rate_info['userid']);
 }
 $photoplog_userid_list = implode(", ", array_unique(explode(", ", $photoplog_userid_list)));
 $photoplog_hook_query_fields = '';
 $photoplog_hook_query_joins = '';
 ($hook = vBulletinHook::fetch_hook('photoplog_index_userinfo')) ? eval($hook) : false;
 $photoplog_vbuser_infos = $db->query_read("SELECT user.userid, user.username,\r\n\t\t\t\t\tuser.usertitle, user.joindate, user.posts,\r\n\t\t\t\t\tuser.avatarid, user.avatarrevision, user.photoplog_filecount, user.photoplog_commentcount,\r\n\t\t\t\t\tuser.usergroupid, user.membergroupids, user.infractiongroupids, user.lastactivity,\r\n\t\t\t\t\tIF(user.displaygroupid = 0, user.usergroupid, user.displaygroupid) AS displaygroupid,\r\n\t\t\t\t\tIF(user.options & " . intval($vbulletin->bf_misc_useroptions['invisible']) . ", 1, 0) AS invisible,\r\n\t\t\t\t\tavatar.avatarpath AS avpath, customavatar.userid AS avuserid, customavatar.dateline AS avdateline,\r\n\t\t\t\t\tusertextfield.signature, sigparsed.signatureparsed, sigparsed.hasimages AS sighasimages,\r\n\t\t\t\t\tsigpic.userid AS sigpic, sigpic.dateline AS sigpicdateline,\r\n\t\t\t\t\tsigpic.width AS sigpicwidth, sigpic.height AS sigpicheight\r\n\t\t\t\t\t{$photoplog_hook_query_fields}\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "user AS user\r\n\t\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON (avatar.avatarid = user.avatarid)\r\n\t\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "customavatar AS customavatar ON (customavatar.userid = user.userid)\r\n\t\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "usertextfield AS usertextfield ON (usertextfield.userid = user.userid)\r\n\t\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "sigparsed AS sigparsed ON\r\n\t\t\t\t\t(\r\n\t\t\t\t\t\tsigparsed.userid = user.userid\r\n\t\t\t\t\t\t\tAND\r\n\t\t\t\t\t\tsigparsed.styleid = " . intval(STYLEID) . "\r\n\t\t\t\t\t\t\tAND\r\n\t\t\t\t\t\tsigparsed.languageid = " . intval(LANGUAGEID) . "\r\n\t\t\t\t\t)\r\n\t\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "sigpic AS sigpic ON (sigpic.userid = user.userid)\r\n\t\t\t\t\t{$photoplog_hook_query_joins}\r\n\t\t\t\t\tWHERE user.userid IN (" . $photoplog_userid_list . ")\r\n\t\t\t\t");
 $photoplog_rates_array = array();
 while ($photoplog_vbuser_info = $db->fetch_array($photoplog_vbuser_infos)) {
     $photoplog_rates_userid = $photoplog_vbuser_info['userid'];
     if (!isset($photoplog_rates_array[$photoplog_rates_userid])) {
         fetch_online_status($photoplog_vbuser_info, true);
         if (!$vbulletin->userinfo['userid'] || $vbulletin->userinfo['showsignatures']) {
             $photoplog_vbuser_perms = cache_permissions($photoplog_vbuser_info, false, false);
             $bbcode_parser->set_parse_userinfo($photoplog_vbuser_info, $photoplog_vbuser_perms);
             $photoplog_vbuser_info['signature'] = $bbcode_parser->parse($photoplog_vbuser_info['signature'], 'signature', true, false, $photoplog_vbuser_info['signatureparsed'], $photoplog_vbuser_info['sighasimages'], true);
             $bbcode_parser->set_parse_userinfo(array());
             unset($photoplog_vbuser_perms);
         } else {
             $photoplog_vbuser_info['signature'] = '';
         }
         $photoplog_rates_array[$photoplog_rates_userid] = array('photoplog_rate_usertitle' => $photoplog_vbuser_info['usertitle'], 'photoplog_rate_joindate' => $photoplog_vbuser_info['joindate'], 'photoplog_rate_numposts' => $photoplog_vbuser_info['posts'], 'photoplog_rate_username' => $photoplog_vbuser_info['username'], 'photoplog_rate_musername' => $photoplog_vbuser_info, 'photoplog_rate_avatarid' => $photoplog_vbuser_info['avatarid'], 'photoplog_rate_avatarrevision' => $photoplog_vbuser_info['avatarrevision'], 'photoplog_rate_filecount' => $photoplog_vbuser_info['photoplog_filecount'], 'photoplog_rate_commentcount' => $photoplog_vbuser_info['photoplog_commentcount'], 'photoplog_rate_onlinestatus' => $photoplog_vbuser_info['onlinestatus'], 'photoplog_rate_avpath' => $photoplog_vbuser_info['avpath'], 'photoplog_rate_avuserid' => $photoplog_vbuser_info['avuserid'], 'photoplog_rate_avdateline' => $photoplog_vbuser_info['avdateline'], 'photoplog_rate_signature' => $photoplog_vbuser_info['signature']);
         ($hook = vBulletinHook::fetch_hook('photoplog_index_ratesarray')) ? eval($hook) : false;
     }
 }
 $db->free_result($photoplog_vbuser_infos);
 $db->data_seek($photoplog_rate_infos, 0);