<?php

/**
 * <pre>
 * Invision Power Services
 * IP.Content topic posting library
 * Last Updated: $Date: 2010-01-15 10:18:44 -0500 (Fri, 15 Jan 2010) $
 * </pre>
 *
 * @author 		$Author: bfarber $
 * @copyright	(c) 2001 - 2009 Invision Power Services, Inc.
 * @license		http://www.invisionpower.com/community/board/license.html
 * @package		IP.Content
 * @link		http://www.invisionpower.com
 * @since		18th February 2010
 * @version		$Revision: 5713 $
 */

if ( ! defined( 'IN_IPB' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit();
}

class topicsLibrary
{
	/**
	 * Moderator library
	 *
	 * @access	protected
	 * @var 	object
	 */
	protected $moderatorLibrary;

	/**
	 * Posting library
	 *
	 * @access	protected
	 * @var 	object
	 */
	protected $post;
	
	/**
	 * Forum data
	 *
	 * @access	protected
	 * @var 	array
	 */
	protected $forum		= array();

	/**
	 * Current topic data
	 *
	 * @access	protected
	 * @var 	array
	 */
	protected $topic		= array();
	
	/**
	 * Base URL
	 *
	 * @access	protected
	 * @var 	string
	 */
	protected $base_url		= "";
	
	/**#@+
	 * Registry objects
	 *
	 * @access	protected
	 * @var		object
	 */	
	protected $registry;
	protected $DB;
	protected $settings;
	protected $request;
	protected $lang;
	protected $member;
	protected $memberData;
	protected $cache;
	protected $caches;
	/**#@-*/

	/**
	 * Current type
	 *
	 * @access	protected
	 * @var		string
	 */	
	protected $type;

	/**
	 * Custom fields class
	 *
	 * @access	public
	 * @var		obj
	 */
	public $fieldsClass;
	
	/**
	 * Categories class
	 *
	 * @access	public
	 * @var		obj
	 */
	public $categories;

	/**
	 * Array of information about the fields in this database
	 *
	 * @access	public
	 * @var		array
	 */
	public $fields			= array();
		
	/**
	 * Constructor
	 *
	 * @access	public
	 * @param	object		Registry object
	 * @param	object		Custom fields object
	 * @param	object		Categories object
	 * @param	array 		Custom fields
	 * @return	void
	 */
	public function __construct( ipsRegistry $registry, $fieldsClass=null, $categories=null, $fields=array() )
	{
		/* Make object */
		$this->registry = $registry;
		$this->DB       = $this->registry->DB();
		$this->settings =& $this->registry->fetchSettings();
		$this->request  =& $this->registry->fetchRequest();
		$this->lang     = $this->registry->getClass('class_localization');
		$this->member   = $this->registry->member();
		$this->memberData =& $this->registry->member()->fetchMemberData();
		$this->cache    = $this->registry->cache();
		$this->caches   =& $this->registry->cache()->fetchCaches();
		
		//-----------------------------------------
		// Custom fields class
		//-----------------------------------------
		
		if( is_object($fieldsClass) )
		{
			$this->fieldsClass	= $fieldsClass;
		}
		else
		{
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/fields.php' );
			$this->fieldsClass	= new ccs_database_fields( $this->registry );
			$this->fieldsClass->getHandlers();
		}
		
		//-----------------------------------------
		// Category class
		//-----------------------------------------
		
		if( is_object($categories) )
		{
			$this->categories	= $categories;
		}
		
		//-----------------------------------------
		// Custom fields
		//-----------------------------------------
		
		$this->fields	= array();
		
		if( is_array($fields) AND count($fields) )
		{
			$this->fields	= $fields;
		}
		
		//-----------------------------------------
		// Base URL
		//-----------------------------------------
		
		$this->base_url	= $this->settings['board_url'] . '/index.php?';
	}
	
	/**
	 * Increment comment count for articles for replies posted in the topic
	 *
	 * @access	public
	 * @param	array 		New post insert data
	 * @return	void
	 */
	public function checkAndIncrementComments( $insert )
	{
		if( $insert['topic_id'] )
		{
			$_databases	= $this->cache->getCache('ccs_databases');
			
			foreach( $_databases as $_database )
			{
				//-----------------------------------------
				// Got a record using this tid in this db?
				//-----------------------------------------
				
				$_record	= $this->DB->buildAndFetch( array( 'select' => 'primary_id_field', 'from' => $_database['database_database'], 'where' => 'record_topicid=' . $insert['topic_id'] ) );
				
				if( $_record['primary_id_field'] )
				{
					$this->DB->update( $_database['database_database'], "record_comments=record_comments+1", "primary_id_field=" . $_record['primary_id_field'], true, true );
					break;
				}
			}
		}
	}
	
	/**
	 * Get topic replies (comments) for a specific topic
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	string		Template to use
	 * @return	array
	 */	
	public function getComments( $record, $category, $database, $templateBit='topicComments' )
	{
		//-----------------------------------------
		// Init
		//-----------------------------------------

		$this->registry->class_localization->loadLanguageFile( array( 'public_global' ), 'core' );

		//-----------------------------------------
		// Approved?  Got a topic?
		//-----------------------------------------

		if( !$record['record_approved'] OR !$record['record_topicid'] )
		{
			return '';
		}

		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------

		if( !is_array($this->fields) OR !count($this->fields) )
		{
			if( is_array($this->caches['ccs_fields'][ $database['database_id'] ]) AND count($this->caches['ccs_fields'][ $database['database_id'] ]) )
			{
				foreach( $this->caches['ccs_fields'][ $database['database_id'] ] as $_field )
				{
					$this->fields[ $_field['field_id'] ]	= $_field;
				}
			}
		}

		//-----------------------------------------
		// Get category handler
		//-----------------------------------------
		
		if( !is_object($this->categories) )
		{
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/categories.php' );
			$this->categories	= new ccs_categories( $this->registry );
			$this->categories->init( $database );
		}

		//-----------------------------------------
		// Format the fields for the record
		//-----------------------------------------

		foreach( $record as $k => $v )
		{
			if( preg_match( "/^field_(\d+)$/", $k, $matches ) )
			{
				$record[ $k . '_value' ]	= $this->fieldsClass->getFieldValue( $this->fields[ $matches[1] ], $record );
			}
		}

		//-----------------------------------------
		// Get forum libs
		//-----------------------------------------
		
		$this->_getForumLibraries();
		
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$comments	= array();
		$perPage	= 30;
		$start		= intval($this->request['st']) > 0 ? intval($this->request['st']) : 0;
		$where		= $database['moderate_approvec'] ? '' : "queued=0 AND ";
		$topic		= $this->DB->buildAndFetch( array( 'select' => '*', 'from' => 'topics', 'where' => "tid={$record['record_topicid']}" ) );
		
		if( !$topic['tid'] )
		{
			return '';
		}
		
		//-----------------------------------------
		// Pagination
		//-----------------------------------------
		
		$count		= $this->DB->buildAndFetch( array( 'select' => 'count(*) as total', 'from' => 'posts', 'where' => $where . "pid <> {$topic['topic_firstpost']} AND topic_id={$record['record_topicid']}" ) );

		$pages		= $this->registry->output->generatePagination( array( 
																'totalItems'		=> $count['total'],
																'itemsPerPage'		=> $perPage,
																'currentStartValue'	=> $start,
																'baseUrl'			=> $database['base_link'],
																'base'				=> 'none',
										 				)	);

		//-----------------------------------------
		// Joins
		//-----------------------------------------
		
		$_post_joins = array(
							array(
									'type'		=> 'left',
									'select'	=> 'm.*',
									'where'		=> 'm.member_id=p.author_id',
									'from'		=> array( 'members' => 'm' )
								),
							array(
									'type'		=> 'left',
									'select'	=> 'pp.*',
									'where'		=> 'pp.pp_member_id=m.member_id',
									'from'		=> array( 'profile_portal' => 'pp' )
								),
							array(
									'select'	=> 'pd.*',
									'from'		=> array( 'pfields_content' => 'pd' ),
									'where'		=> 'pd.member_id=m.member_id',
									'type'		=> 'left',
								),
							);
			
		//-----------------------------------------
		// Reputation system joins
		//-----------------------------------------
		
		if( $this->settings['reputation_enabled'] )
		{
			require_once( IPS_ROOT_PATH . 'sources/classes/class_reputation_cache.php' );
			$this->registry->setClass( 'repCache', new classReputationCache() );
		
			/* Add the join to figure out if the user has already rated the post */
			$_post_joins[] = $this->registry->repCache->getUserHasRatedJoin( 'pid', 'p.pid', 'forums' );
			
			/* Add the join to figure out the total ratings for each post */
			if( $this->settings['reputation_show_content'] )
			{
				$_post_joins[] = $this->registry->repCache->getTotalRatingJoin( 'pid', 'p.pid', 'forums' );
			}
		}
		
		/* Cache? */
		if ( IPSContentCache::isEnabled() )
		{
			if ( IPSContentCache::fetchSettingValue('post') )
			{
				$_post_joins[] = IPSContentCache::join( 'post', 'p.pid' );
			}
		}
		
		//-----------------------------------------
		// Get posts
		//-----------------------------------------

		$this->DB->build( array( 
								'select'	=> 'p.*',
								'from'		=> array( 'posts' => 'p' ),
								'where'		=> $where . "p.pid <> {$topic['topic_firstpost']} AND p.topic_id={$record['record_topicid']}",
								'order'		=> $this->settings['post_order_column'] . ' ' . $this->settings['post_order_sort'],
								'add_join'	=> $_post_joins,
								'limit'		=> array( $start, $perPage ),
						)	);

		$oq = $this->DB->execute();

		while( $row = $this->DB->fetch($oq) )
		{
			//-----------------------------------------
			// Post content
			//-----------------------------------------
			
			if ( ! $row['cache_content'] )
			{
				IPSText::getTextClass( 'bbcode' )->parse_smilies			= $row['use_emo'];
				IPSText::getTextClass( 'bbcode' )->parse_html				= ( $this->registry->getClass('class_forums')->allForums[ $topic['forum_id'] ]['use_html'] and $this->caches['group_cache'][ $row['member_group_id'] ]['g_dohtml'] and $row['post_htmlstate'] ) ? 1 : 0;
				IPSText::getTextClass( 'bbcode' )->parse_nl2br				= $row['post_htmlstate'] == 2 ? 1 : 0;
				IPSText::getTextClass( 'bbcode' )->parse_bbcode				= $this->registry->getClass('class_forums')->allForums[ $topic['forum_id'] ]['use_ibc'];
				IPSText::getTextClass( 'bbcode' )->parsing_section			= 'ccs_comment';
				IPSText::getTextClass( 'bbcode' )->parsing_mgroup			= $row['member_group_id'];
				IPSText::getTextClass( 'bbcode' )->parsing_mgroup_others	= $row['mgroup_others'];

				$_tmp = $this->memberData['view_img'];
				$this->memberData['view_img'] = 1;
				
				$row['post']	= IPSText::getTextClass( 'bbcode' )->preDisplayParse( $row['post'] );
				
				$this->memberData['view_img'] = $_tmp;

				IPSContentCache::update( $row['pid'], 'post', $row['post'] );
			}
			else
			{
				$row['post'] = '<!--cached-' . gmdate( 'r', $row['cache_updated'] ) . '-->' . $row['cache_content'];
			}

			$row['post'] = IPSLib::memberViewImages( $row['post'] );

			//-----------------------------------------
			// Poster details
			//-----------------------------------------

			$row	= IPSMember::buildDisplayData( $row );
				
			//-----------------------------------------
			// Reputation
			//-----------------------------------------
			
			if( $this->settings['reputation_enabled'] )
			{
				$row['pp_reputation_points']	= $row['pp_reputation_points'] ? $row['pp_reputation_points'] : 0;
				$row['has_given_rep']			= $row['has_given_rep'] ? $row['has_given_rep'] : 0;
				$row['rep_points']				= $row['rep_points'] ? $row['rep_points'] : 0;
			}
			
			$row['_repignored']	= 0;

			$this->memberData['_cache']['rep_filter'] = isset( $this->memberData['_cache']['rep_filter'] ) ? $this->memberData['_cache']['rep_filter'] : '*';

			if( $this->settings['reputation_enabled'] )
			{
				if( ! ( $this->settings['reputation_protected_groups'] && 
					    in_array( $row['member_group_id'], explode( ',', $this->settings['reputation_protected_groups'] ) ) 
					   ) &&
				 	$this->memberData['_members_cache']['rep_filter'] !== '*' 
				)
				{
					if( $this->settings['reputation_show_content'] && $row['rep_points'] < $this->memberData['_cache']['rep_filter'] )
					{
						$row['_repignored'] = 1;
					}
				}
			}
			
			$_link	= $this->registry->getClass('output')->formatUrl( $this->registry->getClass('output')->buildUrl( "showuser={$row['member_id']}", "public" ), $row['members_seo_name'], "showuser" );
			$_temp	= $this->registry->getClass('output')->getTemplate('global')->user_popup( $row['member_id'], $row['members_seo_name'] );
			
			$row['author_link']	= "<a href='{$_link}'>{$row['members_display_name']}</a> {$_temp}";
		
			//-----------------------------------------
			// Store
			//-----------------------------------------
			
			$comments[]	= $row;
		}
		
		$this->lang->loadLanguageFile( array( 'public_editors' ), 'core' );

		$commentHtml	= $this->registry->output->getTemplate('ccs_global')->$templateBit( $database, $record, $comments, $pages );
		
		return $commentHtml;
	}
	
	/**
	 * Remove a posted comment
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	int			Post ID
	 * @return	boolean		Removed successfully
	 */
	public function removeComment( $record, $category, $database, $pid )
	{
		//-----------------------------------------
		// Have a topic?
		//-----------------------------------------
		
		if( !$record['record_topicid'] OR !$pid )
		{
			return false;
		}

		//-----------------------------------------
		// Get forum libs
		//-----------------------------------------
		
		$this->_getForumLibraries();
		
		$topic		= $this->DB->buildAndFetch( array( 'select' => 'title, topic_firstpost', 'from' => 'topics', 'where' => 'tid=' . $record['record_topicid'] ) );
		$forumId	= $category['category_forum_override'] ? $category['category_forum_forum'] : $database['database_forum_forum'];

		$this->moderatorLibrary->init( $this->registry->getClass('class_forums')->allForums[ $forumId ] );

		$this->moderatorLibrary->postDelete( $pid );
		$this->moderatorLibrary->addModerateLog( $forumId, $record['record_topicid'], '', $topic['title'], $this->lang->words['log_comment_del'] );

		//-----------------------------------------
		// Recount "comments"
		//-----------------------------------------
		
		$count	= $this->DB->buildAndFetch( array( 'select' => 'count(*) as total', 'from' => 'posts', 'where' => "queued=0 AND pid <> {$topic['topic_firstpost']} AND topic_id={$record['record_topicid']}" ) );
		
		$this->DB->update( $database['database_database'], array( 'record_comments' => intval($count['total']) ), 'primary_id_field=' . $record['primary_id_field'] );
		
		return true;
	}
	
	/**
	 * Toggle comment approved/unapproved
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	int			Post ID
	 * @param	bool		Comment approved
	 * @return	boolean		Removed successfully
	 */
	public function toggleComment( $record, $category, $database, $pid, $approved=true )
	{
		//-----------------------------------------
		// Have a topic?
		//-----------------------------------------
		
		if( !$record['record_topicid'] OR !$pid )
		{
			return false;
		}

		//-----------------------------------------
		// Get forum libs
		//-----------------------------------------

		$this->_getForumLibraries();
		
		$topic		= $this->DB->buildAndFetch( array( 'select' => 'title, topic_firstpost', 'from' => 'topics', 'where' => 'tid=' . $record['record_topicid'] ) );
		$forumId	= $category['category_forum_override'] ? $category['category_forum_forum'] : $database['database_forum_forum'];

		$this->moderatorLibrary->init( $this->registry->getClass('class_forums')->allForums[ $forumId ] );

		$this->moderatorLibrary->postToggleApprove( array( $pid ), $approved, $record['record_topicid'] );

		return true;
	}
	
	/**
	 * Remove a posted topic
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @return	boolean		Removed successfully
	 */
	public function removeTopic( $record, $category, $database )
	{
		//-----------------------------------------
		// Have a topic?
		//-----------------------------------------
		
		if( !$record['record_topicid'] )
		{
			return false;
		}

		//-----------------------------------------
		// Should we delete?
		//-----------------------------------------
		
		$delete		= $category['category_forum_override'] ? $category['category_forum_delete'] : $database['database_forum_delete'];
		$forumId	= $category['category_forum_override'] ? $category['category_forum_forum'] : $database['database_forum_forum'];
		
		if( $delete )
		{
			//-----------------------------------------
			// Get forum libs
			//-----------------------------------------
			
			$this->_getForumLibraries();
			
			$topic	= $this->DB->buildAndFetch( array( 'select' => 'title', 'from' => 'topics', 'where' => 'tid=' . $record['record_topicid'] ) );

			$this->moderatorLibrary->init( $this->registry->getClass('class_forums')->allForums[ $forumId ] );

			$this->DB->build( array( 'select' => 'tid, forum_id', 'from' => 'topics', 'where' => "state='link' AND moved_to='" . $record['record_topicid'] . '&' . $forumId . "'" ) );
			$this->DB->execute();
			
			if ( $linked_topic = $this->DB->fetch() )
			{
				$this->DB->delete( 'topics', "tid=" . $linked_topic['tid'] );
				
				$this->moderatorLibrary->forumRecount( $linked_topic['forum_id'] );
			}
			
			$this->moderatorLibrary->topicDelete( $record['record_topicid'] );
			$this->moderatorLibrary->addModerateLog( $forumId, $record['record_topicid'], '', $topic['title'], $this->lang->words['log_topic_del'] );
		}
		
		return true;
	}
	
	/**
	 * Sort out the topic
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param 	array		Comment information
	 * @return	boolean		Posted successfully
	 */	
	public function postComment( $record, $category, $database, $comment )
	{
		//-----------------------------------------
		// Init
		//-----------------------------------------

		$this->registry->class_localization->loadLanguageFile( array( 'public_global' ), 'core' );

		//-----------------------------------------
		// Approved?  Got a topic?
		//-----------------------------------------

		if( !$record['record_approved'] OR !$record['record_topicid'] )
		{
			return false;
		}

		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------

		if( !is_array($this->fields) OR !count($this->fields) )
		{
			if( is_array($this->caches['ccs_fields'][ $database['database_id'] ]) AND count($this->caches['ccs_fields'][ $database['database_id'] ]) )
			{
				foreach( $this->caches['ccs_fields'][ $database['database_id'] ] as $_field )
				{
					$this->fields[ $_field['field_id'] ]	= $_field;
				}
			}
		}

		//-----------------------------------------
		// Get category handler
		//-----------------------------------------
		
		if( !is_object($this->categories) )
		{
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/categories.php' );
			$this->categories	= new ccs_categories( $this->registry );
			$this->categories->init( $database );
		}

		//-----------------------------------------
		// Format the fields for the record
		//-----------------------------------------

		foreach( $record as $k => $v )
		{
			if( preg_match( "/^field_(\d+)$/", $k, $matches ) )
			{
				$record[ $k . '_value' ]	= $this->fieldsClass->getFieldValue( $this->fields[ $matches[1] ], $record );
			}
		}

		//-----------------------------------------
		// Get forum libs
		//-----------------------------------------
		
		$this->_getForumLibraries();
		
		//-----------------------------------------
		// Post comment
		//-----------------------------------------
		
		$member	= IPSMember::load( $comment['comment_user'] );
		$forum	= $category['category_forum_override'] ? $category['category_forum_forum'] : $database['database_forum_forum'];
		
		$post	= array(
					'author_id'			=> $comment['comment_user'],
					'use_sig'			=> 1,
					'use_emo'			=> 1,
					'ip_address'		=> $this->member->ip_address,
					'post_date'			=> $comment['comment_date'],
					'icon_id'			=> 0,
					'post'				=> $comment['comment_post'],
					'author_name'		=> $member['members_display_name'],
					'topic_id'			=> $record['record_topicid'],
					'queued'			=> !$comment['comment_approved'] ? 1 : 0,
					'post_htmlstate'	=> 0,
					'post_key'			=> md5( microtime() ),
			 );
			 
		$this->DB->insert( 'posts', $post );
		$pid	= $this->DB->getInsertId();
		
		$this->moderatorLibrary->rebuildTopic( $record['record_topicid'], false );
		
		if ( $this->registry->getClass('class_forums')->allForums[ $forum ]['inc_postcount'] )
		{
			$this->post->setPublished( true );
			$this->post->setAuthor( $member );
			$this->post->setForumData( $this->registry->getClass('class_forums')->allForums[ $forum ] );
			$this->post->incrementUsersPostCount();
		}
				
		$this->moderatorLibrary->forumRecount( $this->registry->getClass('class_forums')->allForums[ $forum ]['id'] );
		$this->moderatorLibrary->statsRecount();
		
		return array_merge( $comment, $post, array( 'pid' => $pid, 'comment_id' => $pid ) );
	}
	
	/**
	 * Sort out the topic
	 *
	 * @access	public
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param 	string		Type [new|edit]
	 * @return	boolean		Posted successfully
	 */	
	public function postTopic( $record, $category, $database, $type = 'new' )
	{
		//-----------------------------------------
		// Init
		//-----------------------------------------

		$this->registry->class_localization->loadLanguageFile( array( 'public_global' ), 'core' );

		//-----------------------------------------
		// Approved?
		//-----------------------------------------

		if( !$record['record_approved'] )
		{
			return false;
		}

		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------

		if( !is_array($this->fields) OR !count($this->fields) )
		{
			if( is_array($this->caches['ccs_fields'][ $database['database_id'] ]) AND count($this->caches['ccs_fields'][ $database['database_id'] ]) )
			{
				foreach( $this->caches['ccs_fields'][ $database['database_id'] ] as $_field )
				{
					$this->fields[ $_field['field_id'] ]	= $_field;
				}
			}
		}

		//-----------------------------------------
		// Get category handler
		//-----------------------------------------
		
		if( !is_object($this->categories) )
		{
			require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/categories.php' );
			$this->categories	= new ccs_categories( $this->registry );
			$this->categories->init( $database );
		}

		//-----------------------------------------
		// Format the fields for the record
		//-----------------------------------------

		foreach( $record as $k => $v )
		{
			if( preg_match( "/^field_(\d+)$/", $k, $matches ) )
			{
				$record[ $k . '_value' ]	= $this->fieldsClass->getFieldValue( $this->fields[ $matches[1] ], $record );
			}
		}

		//-----------------------------------------
		// Get our options
		//-----------------------------------------
		
		$topicOptions	= array(
								'postTopic'		=> $category['category_forum_override'] ? $category['category_forum_record'] : $database['database_forum_record'],
								'forumId'		=> $category['category_forum_override'] ? $category['category_forum_forum'] : $database['database_forum_forum'],
								'prefix'		=> $category['category_forum_override'] ? $category['category_forum_prefix'] : $database['database_forum_prefix'],
								'suffix'		=> $category['category_forum_override'] ? $category['category_forum_suffix'] : $database['database_forum_suffix'],
								);

		//-----------------------------------------
		// Post the topic?
		//-----------------------------------------

		if( $topicOptions['postTopic'] AND $topicOptions['forumId'] )
		{
			//-----------------------------------------
			// Get forum libs
			//-----------------------------------------
			
			$this->_getForumLibraries();

			//---------------------------------------------------------
			// Update topic or post a new one?
			//---------------------------------------------------------
			
			if(	$type == 'new' )
			{
				$this->_postNewTopic( $record, $category, $database, $topicOptions );
			}
			else
			{
				$this->_postUpdatedTopic( $record, $category, $database, $topicOptions );
			}
			
			return true;
		}
		
		return false;
	}

	/**
	 * Post a new topic
	 *
	 * @access	private
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	array 		Topic posting options
	 * @return	boolean
	 */	
	private function _postNewTopic( $record, $category, $database, $topicOptions )
	{
		$this->forum	= $this->registry->getClass('class_forums')->allForums[ $topicOptions['forumId'] ];
		$member			= IPSMember::load( $record['member_id'] );
										
		$ttitle			= $record[ $database['database_field_title'] . '_value' ];
		
		if( $topicOptions['prefix'] )
		{
			$ttitle		= $topicOptions['prefix'] . $ttitle;
		}
		
		if( $topicOptions['suffix'] )
		{
			$ttitle		.= $topicOptions['suffix'];
		}
		
		$post_content	= $this->_buildPostContent( $record, $category, $database, $topicOptions );

		$this->topic = array(
							'title'				=> $ttitle,
							'state'				=> 'open',
							'posts'				=> 0,
							'starter_id'		=> $record['member_id'],
							'starter_name'		=> $member['members_display_name'],
							'start_date'		=> time(),
							'last_poster_id'	=> $record['member_id'],
							'last_poster_name'	=> $member['members_display_name'],
							'last_post'			=> time(),
							'icon_id'			=> 0,
							'author_mode'		=> 1,
							'poll_state'		=> 0,
							'last_vote'			=> 0,
							'views'				=> 0,
							'forum_id'			=> $this->forum['id'],
							'approved'			=> 1,
							'pinned'			=> 0,
							'title_seo'			=> IPSText::makeSeoTitle( $ttitle ),
							'seo_last_name'		=> $member['members_seo_name'],
							'seo_first_name'	=> $member['members_seo_name'],
			);

		$this->DB->insert( 'topics', $this->topic );
		$this->topic['tid']     = $this->DB->getInsertId();

		$this->post->sendOutTrackedForumEmails( $this->topic['forum_id'], $this->topic['tid'], $this->topic['title'], $this->forum['name'], $post_content, $record['member_id'], $member['members_display_name'] );
		
		$post = array(
					'author_id'			=> $record['member_id'],
					'use_sig'			=> 1,
					'use_emo'			=> 1,
					'ip_address'		=> $this->member->ip_address,
					'post_date'			=> time(),
					'icon_id'			=> 0,
					'post'				=> $post_content,
					'author_name'		=> $member['members_display_name'],
					'topic_id'			=> $this->topic['tid'],
					'queued'			=> 0,
					'post_htmlstate'	=> 0,
					'post_key'			=> md5( microtime() ),
			 );
			 
		$this->DB->insert( 'posts', $post );
		$pid	= $this->DB->getInsertId();
		
		$this->moderatorLibrary->rebuildTopic( $this->topic['tid'], false );
		
		if ( $this->forum['inc_postcount'] )
		{
			$this->post->setPublished( true );
			$this->post->setAuthor( $member );
			$this->post->setForumData( $this->forum );
			$this->post->incrementUsersPostCount();
		}
				
		$this->moderatorLibrary->forumRecount( $this->forum['id'] );
		$this->moderatorLibrary->statsRecount();
			 
		$this->DB->update( $database['database_database'], array( 'record_topicid' => $this->topic['tid'] ), "primary_id_field=" . $record['primary_id_field'] );		
		
		return true;
	}
	
	/**
	 * Update an existing topic
	 *
	 * @access	private
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	array 		Topic posting options
	 * @return	boolean
	 */	
	private function _postUpdatedTopic( $record, $category, $database, $topicOptions )
	{
		//-----------------------------------------
		// No topic?  Nothing to update then
		//-----------------------------------------

		if( !$record['record_topicid'] )
		{
			return false;
		}

		$this->forum	= $this->registry->getClass('class_forums')->allForums[ $topicOptions['forumId'] ];
		$member			= IPSMember::load( $record['member_id'] );

		//-----------------------------------------
		// Topic title
		//-----------------------------------------
		
		$ttitle			= $record[ $database['database_field_title'] . '_value' ];
		
		if( $topicOptions['prefix'] )
		{
			$ttitle		= $topicOptions['prefix'] . $ttitle;
		}
		
		if( $topicOptions['suffix'] )
		{
			$ttitle		.= $topicOptions['suffix'];
		}

		//-----------------------------------------
		// Update
		//-----------------------------------------
		
		$this->DB->update( "topics", array( 'title' => $ttitle, 'title_seo' => IPSText::makeSeoTitle( $ttitle ), 'forum_id' => $this->forum['id'] ), "tid=" . $record['record_topicid'] );
		
		$firstpost	= $this->DB->buildAndFetch( array( 'select'	=> 'topic_firstpost',
														'from'	=> 'topics',
														'where'	=> 'tid=' . $record['record_topicid']
												)		);
		
		if( $firstpost['topic_firstpost'] )
		{
			$post_content	= $this->_buildPostContent( $record, $category, $database, $topicOptions );

			$this->DB->update( 'posts', array( 'post' => $post_content, 'edit_time' => time(), 'edit_name' => $member['members_display_name'] ), 'pid=' . $firstpost['topic_firstpost'] );
			IPSContentCache::drop( 'post', array( $firstpost['topic_firstpost'] ) );

			$this->moderatorLibrary->forumRecount( $this->forum['id'] );
			$this->moderatorLibrary->statsRecount();							
		}

		return true;
	}
	
	/**
	 * Build the actual post content
	 *
	 * @access	private
	 * @param	array 		Record/article information
	 * @param	array 		Category information
	 * @param	array 		Database information
	 * @param	array 		Topic posting options
	 * @return	boolean
	 */	
	private function _buildPostContent( $record, $category, $database, $topicOptions )
	{
		return $record[ $database['database_field_content'] . '_value' ];
	}

	/**
	 * Load the forum libraries
	 *
	 * @access	protected
	 * @return	void
	 */
	protected function _getForumLibraries()
	{
		//---------------------------------------------------------
		// Get some libraries we need
		//---------------------------------------------------------

		require_once( IPSLib::getAppDir( 'forums' ) . '/app_class_forums.php' );
		$app_class_forums		= new app_class_forums( $this->registry );
		
		require_once( IPSLib::getAppDir('forums') . '/sources/classes/moderate.php' );
		$this->moderatorLibrary	=  new moderatorLibrary( $this->registry );
		
		require_once( IPSLib::getAppDir('forums') . '/sources/classes/post/classPost.php' );
		$this->post				=  new classPost( $this->registry );
	}
}
