<?php if (!defined('VB_ENTRY')) die('Access denied.');
/*======================================================================*\
|| #################################################################### ||
|| # vBulletin 4.0.0 Alpha 5
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2000-2009 Jelsoft Enterprises Ltd. All Rights Reserved. ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/

/**
 * vBCms_Comments
 *
 * @package
 * @author ebrown
 * @copyright Copyright (c) 2009
 * @version $Id: comments.php 32453 2009-10-09 17:35:26Z ksours $
 * @access public
 */
class vBCms_Comments
{
	/*Properties====================================================================*/

	/**
	 * A package identifier.
	 * This is used to resolve any related class names.
	 */
	protected $package = 'vBCms';

	/**
	 * A class identifier.
	 */
	protected $class = 'Comments';

	protected static $static_cache_ttl = 5;
	/*Render========================================================================*/


	/** This function gets the configuration from the database, if the records are there.***/
	private function getConfig()
	{
		//first let's set the default.
		$config = array('comments_perpage' => 10,
			'comments_show_threaded' => 1,
			'comments_max_level' => 4,
			'comments_indent_per_level' => 3);

		$in_values = '';
		if ($rst = vB::$vbulletin->db->query_read("SELECT name, value FROM " .TABLE_PREFIX .
		"cms_nodeconfig WHERE nodeid = 0 AND name in ('comments_perpage', 'comments_show_threaded',
			'comments_max_level', 'comments_indent_per_level');" ))
		{
			while($record = vB::$vbulletin->db->fetch_array($rst) )
			{
				$config[$record['name']] = intval($record['value']);
			}
		}
		return $config;
	}
	/**
	 * Fetches the standard page view .
	 * @param integer $nodeid - node for which we are displaying comments
	 *
	 * @return vBCms_View				- The resolved view, or array of views
	 */
	public function getPageView($nodeid)
	{
		global $vbphrase;

		require_once DIR . '/includes/functions_editor.php';

			vB::$vbulletin->input->clean_array_gpc('r', array(
			'nodeid'     => vB_Input::TYPE_INT,
			'commentpage' => vB_Input::TYPE_STR,
			'direction' => vB_Input::TYPE_STR,
			'nocache' => vB_Input::TYPE_INT
			));

		if (! $row = vB::$vbulletin->db->query_first("SELECT nodeinfo.associatedthreadid FROM "
			. TABLE_PREFIX . "cms_nodeinfo AS nodeinfo
			WHERE	nodeinfo.nodeid = $nodeid LIMIT 1;" ))
		{
			return false;
		}
		$config = $this->getConfig();

		//We need to get the current page's location, stripped of "page=" if it
		//exists. We know that we need to pull it off because if it's there, we
		// put it there for our own use.
		$base_url = $_SERVER['REQUEST_URI'];

		if ($page_loc = strpos($base_url, '&commentpage='))
		{
			$base_url = substr($base_url, 0, $page_loc);
		}

		if ($page_loc = strpos($base_url, '&nocache='))
		{
			$base_url = substr($base_url, 0, $page_loc);
		}

		// Create view
		$view = new vB_View('vbcms_comments_page');
		$view->nodeid = $nodeid;
		$view->threadid = $row['associatedthreadid'];
		$view->per_page = $config['comments_perpage'];
		$view->this_url = $base_url;

		$this_user = new vB_Legacy_CurrentUser();

		$pageno = vB::$vbulletin->GPC_exists['commentpage'] ?
			vB::$vbulletin->GPC['commentpage'] : 1;
		$view->pageno = $pageno;

		$view->node_comments = self::showComments($view->nodeid,
			$this_user, $pageno, $config['comments_perpage'], $base_url,
			$config['comments_max_level'], $config['comments_indent_per_level']);

		if (intval($this_user->get_field('userid')))
		{
			$view->show_comment_editor = true;
			global $messagearea;
			$editor_name = construct_edit_toolbar($text = $vbphrase['post_comment']);
			$view->messagearea = $messagearea;//
			$view->editor_name = $editor_name;
		}
		else
		{
			$view->show_comment_editor = false;
		}

		return $view;
	}

	/*******
	* This function gets a list of comment ids and caches the list.
	***/
	private static function getComments($nodeid, $userinfo, $max_level = 4)
	{
		require_once DIR . '/vb/cache.php';
		global $vbulletin;

		if (!$vbulletin->GPC_exists['nocache'] and $comments = vB_Cache::instance()->read(
			self::getStaticHash($nodeid), true))
		{
			return $comments;
		}
/****
* format of the sql is
		 * SELECT distinct post0.threadid, post0.postid, post1.postid, post2.postid, post3.postid, post4.postid,

		 LEFT JOIN dev_post AS post1 ON post1.parentid = post0.postid
		 LEFT JOIN dev_post AS post2 ON post2.parentid = post1.postid
		 LEFT JOIN dev_post AS post3 ON post3.parentid = post2.postid
		 LEFT JOIN dev_post AS post4 ON post4.parentid = post3.postid
		 WHERE nodeinfo.nodeid = 3 AND post.parentid = 0
		 ORDER BY post.dateline, post1.dateline, post2.dateline, post3.dateline, post4.dateline
		 ASC LIMIT 1000;
		 *
*/
		$sql = "SELECT distinct post0.threadid ";

		for ($i = 1;$i <= $max_level; $i++)
		{
			$sql .= ", post$i.postid AS post$i" . "id";
		}
		$sql .= "\n FROM " . TABLE_PREFIX . "cms_nodeinfo AS nodeinfo
		 INNER JOIN " . TABLE_PREFIX . "post AS post0 ON nodeinfo.associatedthreadid = post0.threadid \n";

		for ($i = 1;$i <= $max_level; $i++)
		{
			$sql .= "LEFT JOIN " . TABLE_PREFIX . "post AS post$i on post$i.parentid = post" . intval($i - 1) . ".postid\n";

		}

		$sql .= "WHERE nodeinfo.nodeid = $nodeid AND post0.parentid = 0
		ORDER BY post0.dateline";

		for ($i = 1;$i <= $max_level; $i++)
		{
			$sql .= ", post$i.dateline";

		}
		$sql .= "\nASC LIMIT 1000";

		if (! $rst = $vbulletin->db->query_read($sql))
		{
			return false;
		}

		//we just want an array post id => level
		//We will get a series of rows with a field count which is one
		// more than the maximum level. So we need to parse it out.
		// We keep an array that represents the previous row, and by comparing the
		// new row with the previous we can see what level has changed.

		$prev_row = array_fill(0, $max_level, 0);

		$ids = array();

		//Now we compare the fields. We need to check fields from the third
		// to the end of the row. If the value is different from the previous row,
		// we add a record.
		while($row = $vbulletin->db->fetch_row($rst))
		{
			for ($i = 1; $i <= $max_level; $i++)
			if (intval($row[$i]) != intval($prev_row[$i]) )
			{
				$ids[] = array('postid' => $row[$i], 'level' => $i, 'html' => '');
			}
		}
		//Now we have a tree with each record identified by its level in the hierarchy.
		vB_Cache::instance()->write(self::getStaticHash($nodeid),
			   $ids, self::$static_cache_ttl);
		return $ids;

	}

	/**********
	* To determine if we can display the results, there are two
	* checks- first we check to see our rights at the thread level.
	* Then we check each post. Here's the first function
	* Note that in the future I expect to call this from ajax, and
	* in that case we don't have an item. So these function have to be
	* callable as static.
	*
	* @param nodeid integer : The node.
	*
	* @return mixed :  can be false, or an array of privileges
	***/
	public static function canViewThread($nodeid, $user)
	{
		require_once DIR . '/vb/legacy/thread.php';

		if (! $row = vB::$vbulletin->db->query_first("SELECT nodeinfo.associatedthreadid
		AS threadid FROM " . TABLE_PREFIX . "cms_nodeinfo
		AS nodeinfo WHERE	nodeinfo.nodeid = $nodeid;" ))
		{
			return false;
		}
		$thread = vB_Legacy_Thread::create_from_id($row['threadid']);
		if (!$thread)
		{
			return false;
		}

		if (!$thread->can_view($user))
		{
			return false;
		}

		$can_moderate_forums = $user->canModerateForum($thread->get_field('forumid'));
		$can_moderate_posts = $user->canModerateForum($thread->get_field('forumid'), 'canmoderateposts');
		$is_coventry = false;

		if (!$can_moderate_forums)
		{
			//this is cached.  Should be fast.
			require_once (DIR . '/includes/functions_bigthree.php');
			$conventry = fetch_coventry();

			$is_coventry = (in_array($user->get_field('userid'), $conventry));

		}

		if (! $can_moderate_forums AND $is_coventry)
		{
			return false;
		}

		// If we got here, the user can at least see the thread. We still have
		// to check the individual records;
		return array('can_moderate_forums' => $can_moderate_forums,
		'is_coventry' => $is_coventry,
		'can_moderate_posts' => $can_moderate_posts);
	}

	/******
	* Here we check each post, using the thread privileges we got from
	* canViewThread.
	*
	* @param $postid  integer  	The post
	* @param $privileges array		from canViewThread
	* @return boolean
	***/
	private function canViewPost($post, $privileges)
	{

		if (!$privileges['can_moderate_forums'] )
		{
			if ( $privileges['is_coventry'] OR ($post['visible'] == 2))
			{
				return false;
			}
		}

		// post/thread is deleted by moderator and we don't have permission to see it
		return ($post['visible'] OR $privileges['can_moderate_posts']);
	}

	/*****
	* We create a nav bar using html links. This is a standard function
	* @param integer perpage : the number of comments per page
	* @param integer record_count : the total number of records to display
	* @param integer this_page : the current page;
	* @target_url
	*
	* returns string : the navigation to get to whatever page is needed.
	***/
	private static function makeNav($perpage, $record_count, $this_page, $target_url)
	{
		//The rules for buttons are:
		//we have steps of 1,2,3,10,20,50,100,200, from where we are, in each direction

		//check the left side
		require_once DIR . '/includes/functions.php';
		$pagecount = intval(($record_count + $perpage -1)/$perpage);
		return  vBCms_ContentManager::getNav($perpage, $record_count, $this_page,
			false, $width_pct = 90, 'commentpage', false);;
	}

	/**********************
	* This function just gets the thread id for a given post
	* @param integer $postid
	* @return integer $threadid
	*
	****/
	private static function getThreadId($postid)
	{
		if ($record = vB::$vbulletin->db->query_first( "SELECT threadid FROM " . TABLE_PREFIX
		. "post AS post where postid = $postid"))
		{
			return $record['threadid'];
		}
		return false;
	}

	/*********************
	* This function creates HTML for a user interface. It is called by
	* ajax.php so we can add a user interface.
	* @param integer $postid
	* @return nothing.
	*********/
	public static function GetCommentUIXml($postid)
	{
		require_once DIR . '/includes/functions_misc.php';
		require_once DIR . '/includes/functions_editor.php';
		global $vbulletin;
		global $vbphrase;
		global $messagearea;
		global $sessionhash;
		fetch_phrase_group('posting');
		fetch_phrase_group('vbcms');

		$editor_name = construct_edit_toolbar($text = $vbphrase['post_comment'],
			false, 0, true, true, false, 'fe', 'editor_' . $postid);
		$template = vB_Template::create('vbcms_comments_editor');
		$template->register('messagearea', $messagearea	);
		$template->register('sessionhash', $sessionhash	);
		$template->register('editor_name', $editor_name	);
		$template->register('postid', $postid	);
		$template->register('threadid', self::getThreadId($postid));

		$xml = new vB_AJAX_XML_Builder($vbulletin, 'text/xml');
		$xml->add_group('root');

		//todo handle prefs for xml types
		$xml->add_tag('html', $template->render());

		$xml->close_group();
		$xml->print_xml();
	}
	/**
	 * This does the actual work of creating the navigation elements. This needs some
	 * styling, but we'll do that later.
	 *
	 * @return string;
	 */
	private static function showComments($nodeid, $userinfo, $pageno = 1,
		$perpage = 5, $target_url = '' , $max_level = 4, $pixel_indent = 10)
	{
		require_once DIR . '/includes/functions_misc.php';
		require_once DIR . '/includes/functions.php';
		require_once DIR . '/includes/functions_databuild.php';

		global $vbulletin;
		global $vbphrase;
		global $show;
		global $sessionhash;

		fetch_phrase_group('posting');

		//First let's see if we have forum/thread view permissions. If not,
		// we're done
		if (! $permissions = self::canViewThread($nodeid, $userinfo))
		{
			return false;
		}

		$forumperms = fetch_permissions(self::getForumId($nodeid));

		//Normally this thread will be wide open, so let's get the list first
		// without checking. We'll verify each post anyway.
		$perpage = min(max(0, intval($perpage)), 20);
		//get our results
		$results = self::getComments($nodeid, $userinfo, $max_level);

		if (!$results OR !count($results))
		{
			return '';
		}
		$record_count = count($results);

		//we accept the parameter "last" for pageno.
		if ($pageno == 'last')
		{
			$pageno = intval(($record_count + $perpage -1) / $perpage);
			$first = ($pageno -1) * $perpage;
		}
		else
		{
			$pageno = max(1, intval($pageno) );
			$first = $perpage * ($pageno -1) ;
		}

		//Let's trim off the results we need.
		//This also tells us if we should show the "next" button.
		$results = array_slice($results, $first, $perpage, true);

		//Now format the overall block.

		if (!$comments = self::renderResult( $userinfo, $results, $permissions,
				$forumperms, $pixel_indent, $max_level)
			or ($comments == ''))
		{
			return false;
		}

		$template = vB_Template::create('vbcms_comments_block');
		$template->register('last_page', intval(($record_count + $perpage - 1)/$perpage));
		$template->register('comment_count', $record_count	);
		$template->register('sessionhash', $sessionhash	);
		$template->register('per_page', $perpage);
		$template->register('cms_comments', $comments);
		$template->register('current_page', $pageno);
		$template->register('this_url', $target_url);
		$template->register('nodeid', $nodeid);
		$template->register('comments_page_nav',self::makeNav($perpage, $record_count, $pageno, $target_url));
		$template->register('target_url', $target_url);

		return $template->render() ;
	}

	public static function showCommentsXml($nodeid, $userinfo, $pageno = 1,
		$perpage = 5, $target_url = '')
	{
		require_once DIR . '/includes/functions_misc.php';
		global $vbulletin;
		global $show;


		$xml = new vB_AJAX_XML_Builder($vbulletin, 'text/xml');
		$xml->add_group('root');

		//todo handle prefs for xml types
		$xml->add_tag('html', $check_val = self::showComments($nodeid, $userinfo,  $pageno,
		$perpage, $target_url));

		$xml->close_group();
		$xml->print_xml();
	}

	/******
	* This function gets the forum id, which we get for fetch_permissions
	* @param integer $nodeid
	* @return object permissions
	***/
	private static function getForumId($nodeid)
	{
		if (! $row = vB::$vbulletin->db->query_first("SELECT forumid FROM "
			. TABLE_PREFIX . "cms_nodeinfo AS nodeinfo INNER JOIN " . TABLE_PREFIX
			. "thread AS thread ON thread.threadid = nodeinfo.associatedthreadid
			WHERE nodeinfo.nodeid = $nodeid"))
		{
			return false;
		}
		return $row['forumid'];
	}


	/*****
	* This function renders the results for display . It is basically copied
	*  from showthread.php. We have a minor problem with keeping order, because
	*  we can't use any sql sort. So we put the html into the array,
	*  and then dump it in order.
	*
	* @param array $userinfo
	* @param array $array of sequence => array(postid, level, html)
	* @param array $permissions : What are this user's permissions for this thread?
	*
	* @return string : the html results of the render.
	*/
	private static function renderResult($userinfo, $post_array, $permissions,
		$forumperms, $pixel_indent, $max_level = 4)
	{
		require_once DIR . '/includes/functions_bigthree.php' ;
		require_once DIR . '/includes/class_postbit.php' ;
		global $vbulletin;
		global $vbphrase;
		global $template_hook;
		global $show;

		require_once DIR . '/includes/functions_user.php';
		$show['inlinemod'] = false;
		$postids = array();

		if (! isset(vB::$vbulletin->userinfo['permissions']['cms']))
		{
			require_once DIR . '/packages/vbcms/permissions.php';
			vBCMS_Permissions::getUserPerms();
		}


		foreach ($post_array as $key =>$postinfo)
		{
			$postids[] = $postinfo['postid'];
		}
		$postids = ' post.postid in ('
 			. implode(', ', $postids) .')';

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

		if (!($forumperms & $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 = count($postid_array);

		$counter = 0;
		$postbits = '';
		$vbulletin->noheader = true;
		$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());

		$show['avatar'] = 1;

		while ($post = $vbulletin->db->fetch_array($posts))
		{

			if ($post['avatarpath'] == '' AND intval($post['profilepic']))
			{
				$post['avatar'] = 1;
				$post['avatarpath'] = "./image.php?u=" . $post['userid']  . "&amp;dateline=" . $post['profilepicdateline'] . "&amp;type=profile";
				$post['avwidth'] = $post['ppwidth'];
				$post['avheight'] = $post['ppheight'];
			}

			if (! self::canViewPost($post, $permissions) )
			{

				continue;
			}

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

			//now we need to find the sequence number that matches this record
			// based on postid
			$this_key = -1;
			foreach ($post_array as $key =>$postinfo)
			{
				if (intval($postinfo['postid']) == intval($post['postid']))
				{
					$show['show_comments_link'] = (intval($userinfo->get_field('userid'))
							and  $postinfo['level'] < $max_level);
					$this_key = $key;
					break;
				};
			}

			if (intval($this_key < 0))
			{
				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';
			}

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

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

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

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

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


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

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

			$post_array[$key]['html'] = $this_template->render();

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

			if ($post_cachable AND $post['pagetext_html'] == '')
			{
				if (!empty($saveparsed))
				{
					$saveparsed .= ',';
				}
				$saveparsed .= "($post[postid], " . intval($thread['lastpost']) . ', ' . intval($postbit_obj->post_cache['has_images']) . ", '" . $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']) . ")";
			}
		}

		foreach ($post_array as $html_array)
		{
			$postbits .= $html_array['html'];
		}

		$vbulletin->db->free_result($posts);
		unset($post);
		return $postbits;
	}

	public function getConfigEditorView()
	{
		require_once DIR . '/includes/functions_databuild.php' ;
		fetch_phrase_group('posting');
		global $show;

		require_once DIR . '/includes/functions_editor.php' ;
		require_once(DIR . '/includes/functions_file.php');

		$config = $this->getConfig();


		$attachmentoption = '';
		$attachcount = 0;
		$posthash = 0;
		$poststarttime = 0;
		$postattach = 0;
		$contenttypeid = 0;

		$attachinfo = array(
			'auth_type'     => (empty($_SERVER['AUTH_USER']) AND empty($_SERVER['REMOTE_USER'])) ? 0 : 1,
			'posthash'      => $posthash,
			'poststarttime' => $poststarttime,
			'userid'        => $vbulletin->userinfo['userid'],
			'contenttypeid' => $contenttypeid,
			'max_file_size' => fetch_max_upload_size(),
			'values'        => array(
				'f' => $foruminfo['forumid']
			)
		);
		$view->editorid = construct_edit_toolbar($pagetext, 0, 'blog_entry',1, 1, true,'fe', '', false);

		$templater = vB_Template::create('vbcms_comments_editor');
		$templater->register('attachmentoption', $attachmentoption);
		$templater->register('checked', $checked);
		$templater->register('disablesmiliesoption', $disablesmiliesoption);
		$templater->register('editorid', $view->editorid);
		$templater->register('messagearea', $messagearea);
		$tag_delimiters = addslashes_js(vB::$vbulletin->options['tagdelimiter']);
		$templater->register('tag_delimiters', $tag_delimiters);
		$content = $templater->render();

		return $GLOBALS['messagearea'];
	}

	/**
	 * Returns a hash function for caching. Each user must have a unique
	 * view because their permissions might vary.
	 *
	 * @param integer $nodeid
	 * @return hash that will identify this content for this user
	 */
	protected static function getStaticHash($nodeid)
	{
		$context = new vB_Context('comments' , array('nodeid' => $nodeid,
			'userid' => vB::$vbulletin->userinfo['userid']));
		return strval($context);
	}
}

/*======================================================================*\
|| ####################################################################

|| # SVN: $Revision: 32453 $
|| ####################################################################
\*======================================================================*/