<?php
if (!defined('VB_ENTRY')) die('Access denied.');
/*======================================================================*\
   || #################################################################### ||
   || # vBulletin 5.0.0 Beta 10
   || # ---------------------------------------------------------------- # ||
   || # Copyright ?2000-2012 vBulletin Solutions Inc. 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 # ||
   || #################################################################### ||
   \*======================================================================*/


/**
 * vB_Api_Content_Text
 *
 * @package vBApi
 * @author ebrown
 * @copyright Copyright (c) 2011
 * @version $Id$
 * @access public
 */
class vB_Api_Content_Text extends vB_Api_Content
{
	//override in client- the text name
	protected $contenttype = 'vBForum_Text';

	//The table for the type-specific data.
	protected $tablename = 'text';

	//When we parse the page.
	protected $bbcode_parser = false;

	//Whether we change the parent's text count- 1 or zero
	protected $textCountChange = 1;

	//for spam checking
	protected $spamType = false;
	protected $spamKey = false;
	protected $akismet;

	//Does this content show author signature?
	protected $showSignature = true;

	/** normal protector- protected to prevent direct instantiation **/
	protected function __construct()
	{
		parent::__construct();
		$this->library = vB_Library::instance('Content_Text');
		//see if we have spam checking set.
		if (isset($this->options['vb_antispam_type']) AND !empty($this->options['vb_antispam_key']))
		{
			$this->spamType = $this->options['vb_antispam_type'];
			$this->spamKey = $this->options['vb_antispam_key'];
		}
	}

	/** This function parses the raw text and stores the result in pagetext and previewtext
	*
	*	@param	mixed
	***/
	protected function parseContent(&$record)
	{
		require_once(DIR . '/includes/class_bbcode.php');
	//	require_once(DIR . '/packages/vbforum/bbcode/wysiwyg.php');
		if ($this->bbcode_parser == false)
		{
			//TODO: execute the line below to get all text tags.
			//$tags = vBForum_BBCode_Wysiwyg::fetchTextTags();
			$tags = fetch_tag_list();
			$registry = vB::get_registry();

			if (empty($registry->db) AND !empty(vB::$db))
			{
				$registry->db = vB::$db;
			}

			$this->bbcode_parser = new vB_BbCodeParser($registry, $tags);
		}

		// Articles will generally have an attachment but they should still keep a counter so that this query isn't always running
		require_once(DIR . '/packages/vbattach/attach.php');
		$attach = new vB_Attach_Display_Content(vB::$vbulletin, 'vBForum_Text');
		$attachments = $attach->fetch_postattach(0, $record['nodeid']);
		$this->bbcode_parser->attachments = $attachments;
		$this->bbcode_parser->unsetattach = true;

		require_once DIR . '/includes/functions.php';
		$this->bbcode_parser->attachments = $attachments;

		$authorContext = vB::getUserContext($record['userid']);

		$record['pagetext'] = fetch_censored_text($this->bbcode_parser->do_parse(
			$record['rawtext'],
			$authorContext->getChannelPermission('forumpermissions', 'canusehtml', $record['parentid']),
			true, true, $authorContext->getChannelPermission('forumpermissions', 'cangetattachment', $record['parentid']),
			true,true,$record->htmlstate
			));

		$attach->process_attachments($record, $this->bbcode_parser->attachments, false, false, true, false, true);

		$record['previewtext'] = $this->bbcode_parser->get_preview($record['rawtext'], 200,
			false, true, $record->htmlstate );
		$this->assertor->assertQuery('vBForum:text', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_UPDATE, 'nodeid' => $record['nodeid'],
			'pagetext' => $record['pagetext'], 'previewtext' => $record['previewtext']) );
	}

	/*** Permanently deletes a node
	 *	@param	integer	The nodeid of the record to be deleted
	 *
	 *	@return	boolean
	 ***/
	public function delete($nodeid)
	{
		return $this->library->delete($nodeid);
	}

	/*** Adds a new node.
	 *
	 *	@param	mixed		Array of field => value pairs which define the record.
	 *  @param	array		Array of options for the content being created.
	 *						Available options include:
	 *							- nl2br: if TRUE, all \n will be converted to <br /> so that it's not removed by the html parser (e.g. comments).
	 *
	 * 	@return	integer		the new nodeid
	 ***/
	public function add($data, $options = array())
	{

		if (empty($data['title']) AND empty($data['pagetext']) AND empty($data['rawtext']))
		{
			throw new vB_Exception_Api('invalid_data');
		}

		$vboptions = vB::getDatastore()->getValue('options');
		if (!empty($data['pagetext']) AND vB_String::vbStrlen(trim($data['pagetext']), true) < $vboptions['postminchars'])
		{
			throw new vB_Exception_Api('invalid_data');
		}

		if (!empty($data['rawtext']) AND vB_String::vbStrlen(trim($data['rawtext']), true) < $vboptions['postminchars'])
		{
			throw new vB_Exception_Api('invalid_data');
		}

		// If node is a starter and has no title
		if (!empty($data['starter']) AND ($data['starter'] != $data['parentid']) AND empty($data['title']))
		{
			return false;
		}

		if (isset($data['userid']))
		{
			unset($data['userid']);
		}

		if (isset($data['authorname']))
		{
			unset($data['authorname']);
		}

		if (!$this->validate($data, vB_Api_Content::ACTION_ADD))
		{
			throw new vB_Exception_Api('no_create_permissions');
		}
		$this->cleanInput($data);
		return $this->library->add($data , $options);
	}

	/*** Processing after a move. In this case, update the starter field and set the text counts and "last" data.
	*
	* 	@param	int		the nodeid
	* 	@param	int		the old parentid
	* 	@param	int		the new parentid
	*/
	public function afterMove($nodeid, $oldparent, $newparent)
	{
		parent::afterMove($nodeid, $oldparent, $newparent);
		$newParentNode = $this->nodeApi->getNode($newparent);

		//if this IS the starter, then no change is necessary.
		if ($newParentNode['starter'] != $nodeid)
		{
			$starter = $this->getStarter($nodeid);
			$this->assertor->assertQuery('vBForum:setStarter', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_STORED,
				'nodeid' => $nodeid, 'starter' => $starter));
		}

	}

	/** THis returns a string with quoted strings in bbcode format.
	*
	*	@param	mixed	array of integers
	*
	* 	@return	string
	***/

	public function getQuotes($nodeids)
	{
		return $this->library->getQuotes($nodeids);
	}

	public function getIndexableFromNode($node, $include_attachments = true)
	{
		$all_content = parent::getIndexableFromNode($node, $include_attachments = true);
		array_unshift($all_content, $node['rawtext']);
		return $all_content;
	}

	/**
	 * Adds content info to $result so that merged content can be edited.
	 * @param array $result
	 * @param array $content
	 */
	public function mergeContentInfo(&$result, $content)
	{
		$this->library->mergeContentInfo($result, $content);
	}

	/**
	 * Performs the merge of content and updates the node.
	 * @param type $data
	 * @return type
	 */
	public function mergeContent($data)
	{
		return $this->library->mergeContent($data);
	}

}
