<?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 # ||
|| #################################################################### ||
\*======================================================================*/

/**
 * Article Content Controller
 *
 * @package vBulletin
 * @author vBulletin Development Team
 * @version $Revision: 28694 $
 * @since $Date: 2008-12-04 16:12:22 +0000 (Thu, 04 Dec 2008) $
 * @copyright Jelsoft Enterprises Ltd.
 */
class vBCms_Content_Article extends vBCms_Content
{
	/*Properties====================================================================*/

	/**
	 * A class identifier.
	 *
	 * @var string
	 */
	protected $class = 'Article';

	/**
	 * A package identifier.
	 *
	 * @var string
	 */
	protected $package = 'vBCms';

	/**
	 * Controller Parameters.
	 *
	 * @var mixed
	 */
	protected $parameters = array('page' => 1);

	protected $parent_node = false;
	/*ViewInfo======================================================================*/
	protected $data_saved = false;

	/**
	 * Info required for view types.
	 *
	 * @var array
	 */
	protected $view_info = array(
		self::VIEW_LIST => vBCms_Item_Content::INFO_BASIC,
		self::VIEW_PREVIEW => /* vB_Item::INFO_BASIC | vBCms_Item_Content::INFO_NODE | vBCms_Item_Content::INFO_CONTENT */ 19,
		self::VIEW_PAGE => /* vB_Item::INFO_BASIC | vBCms_Item_Content::INFO_NODE | vBCms_Item_Content::INFO_CONTENT */ 19,
		self::VIEW_AGGREGATE => vBCms_Item_Content::INFO_NODE
	);

	protected $cache_ttl = 10;

	protected $editing = false;

	/*Creation======================================================================*/


	/**
	 * Creates a new, empty content item to add to a node.
	 *
	 * @param vBCms_DM_Node $nodedm				- The DM of the node that the content is being created for
	 * @return int | false						- The id of the new content or false if not applicable
	 */
	public function createDefaultContent(vBCms_DM_Node $nodedm)
	{
		$contentdm = new vBCms_DM_Article();

		vB::$vbulletin->input->clean_array_gpc('r', array(
			'nodeid' => vB_Input::TYPE_UINT,
			'parentnode' => vB_Input::TYPE_UINT,
			'blogcommentid' => vB_Input::TYPE_UINT,
			'postid' => vB_Input::TYPE_UINT,
			'blogid' => TYPE_UINT
			));


		//We should have a nodeid, but a parentnode is even better.

		if ($this->parent_node)
		{
			$parentnode = $this->parent_node;
		}
		else if (vB::$vbulletin->GPC_exists['parentnode'] AND intval(vB::$vbulletin->GPC['parentnode'] ))
		{
			$parentnode = vB::$vbulletin->GPC['parentnode'];
		}
		else if (vB::$vbulletin->GPC_exists['nodeid'] AND intval(vB::$vbulletin->GPC['nodeid'] )
			and $record = vB::$vbulletin->db->query_first("SELECT contenttypeid, nodeid, parentnode FROM " .
			TABLE_PREFIX . "cms_node where nodeid = " . vB::$vbulletin->GPC['nodeid'] ))
		{
			$parentnode = vB_Types::instance()->getContentTypeID("vBCms_Section") == $record['contenttypeid'] ?
				$record['nodeid'] : $record['parentnode'];
		}
		else
		{
			throw (new vB_Exception_Content('No valid parent node'));
		}

		$nodedm->set('contenttypeid', vB_Types::instance()->getContentTypeID("vBCms_Article"));
		$nodedm->set('parentnode', $parentnode);

		if (vB::$vbulletin->GPC_exists['blogcommentid'] OR vB::$vbulletin->GPC_exists['blogid'])
		{
			$this->createFromBlogPost($nodedm);
		}
		else if (vB::$vbulletin->GPC_exists['postid'])
		{
			$this->createFromForumPost($nodedm);
		}
		else
		{
			$title = new vB_Phrase('vbcms', 'new_article');
			$nodedm->set('description', $title);
			$nodedm->set('title', $title);
			$nodedm->set('html_title', $title);
			$nodedm->set('pagetext', new vB_Phrase('vbcms', 'new_article_edit'));
			$nodedm->set('userid', vB::$vbulletin->userinfo['userid']);
		}
		if (!($contentid = $nodedm->save()))
		{
			throw (new vB_Exception_Content('Failed to create default content for contenttype ' . get_class($this)));
		}


		//at this point we have saved the data. We need to get the content id, which isn't easily available.
		if ($record = vB::$vbulletin->db->query_first("SELECT contentid FROM " . TABLE_PREFIX .
			"cms_node WHERE nodeid = $contentid"))
		{
			$nodedm->set('contentid', $record['contentid']);
		}

		return $contentid;
	}

	/*** This function sets the parent node for creating a new article
	****/
	public function setParentNode($parentnode)
	{

		$this->parent_node = $parentnode;
	}

	/*Configuration=================================================================*/

	/**
	 * Assigns a parameter value.
	 *
	 * @param string $parameter					- The key name of the parameter to set
	 * @param mixed $value						- The value to set it to
	 */
	protected function assignParameter($parameter, $value)
	{
		if ($parameter == 'page')
		{
			$this->parameters['page'] = max(intval($value), 1);
		}
		else
		{
			parent::assignParameter($parameter, $value);
		}
	}


	protected function createFromBlogPost($nodedm)
	{
		global $vbphrase;
		//make sure we are only called once;

		//let's confirm the rights
		$title = new vB_Phrase('vbcms', 'new_article');

		$sql = "SELECT txt.pagetext, txt.bloguserid, txt.title, blog.title AS blogtitle, blog.userid AS poststarter,
			txt.username, blog.postedby_username AS author, blog.blogid, txt.blogtextid, txt.dateline AS post_posted,
			blog.dateline AS post_started FROM " . TABLE_PREFIX .
			"blog_text AS txt INNER JOIN " . TABLE_PREFIX . "blog AS blog
			ON blog.firstblogtextid = txt.blogtextid " ;

		if (vB::$vbulletin->GPC_exists['blogcommentid'] )
		{
			$sql .= "WHERE txt.blogtextid = "	. vB::$vbulletin->GPC['blogcommentid'];
		}
		else if (vB::$vbulletin->GPC_exists['blogid'])
		{
			$sql .= " WHERE blog.blogid = " .
				vB::$vbulletin->GPC['blogid'];
		}
		else
		{
			return false;
		}

		if ($record = vB::$vbulletin->db->query_first($sql))
		{
			$nodedm->set('description', (strlen($record['title']) > 10 ? $record['title'] :
				$tagline));
			$nodedm->set('userid', $record['userid']);
			$nodedm->set('title', (strlen($record['title']) > 10 ? $record['title'] :
				$title));
			$nodedm->set('html_title', (strlen($record['title']) > 10 ? $record['title'] :
				$title));
			$url = htmlspecialchars(str_replace(' ', '-',(strlen($record['title']) > 10 ? $record['title'] :$title) ));
			$nodedm->set('url', $url);

			$nodedm->set('contenttypeid', vB_Types::instance()->getContentTypeID("vBCms_Article"));
			$nodedm->set('pagetext', $record['pagetext']);
			$nodedm->set('blogid', $record['blogid'] );
			$nodedm->set('posttitle', $record['blogtitle'] );
			$nodedm->set('poststarter', $record['poststarter'] );
			$nodedm->set('blogpostid', $record['blogtextid'] );
			$nodedm->set('post_started', $record['post_started'] );
			$nodedm->set('post_posted', $record['post_posted'] );
		}
	}

	protected function createFromForumPost($nodedm)
	{
		global $vbphrase;
		//make sure we are only called once;

		//let's confirm the rights
		$title = new vB_Phrase('vbcms', 'new_article');

		if (vB::$vbulletin->GPC_exists['postid'] )
		{
			$sql = "SELECT pagetext, post.userid, post.title, post.username, post.threadid,
				thread.title AS threadtitle, thread.postuserid AS poststarter, thread.postusername AS author,
				thread.dateline AS post_started ,post.dateline AS post_posted FROM " . TABLE_PREFIX .
				"post AS post INNER JOIN " . TABLE_PREFIX ."thread AS thread ON thread.threadid = post.threadid
				WHERE post.postid = " .
				vB::$vbulletin->GPC['postid'];
		}
		else
		{
			return false;
		}

		if ($record = vB::$vbulletin->db->query_first($sql))
		{
			$nodedm->set('description', (strlen($record['title']) > 10 ? $record['title'] :
				$title));
			$nodedm->set('userid', $record['userid']);
			$nodedm->set('title', (strlen($record['title']) > 10 ? $record['title'] :
				$title));
			$nodedm->set('html_title', (strlen($record['title']) > 10 ? $record['title'] :
				$title));
			$url = htmlspecialchars(str_replace(' ', '-',(strlen($record['title']) > 10 ? $record['title'] :$title) ));
			$nodedm->set('url', $url);
			$nodedm->set('contenttypeid', vB_Types::instance()->getContentTypeID("vBCms_Article"));
			$nodedm->set('pagetext', $record['pagetext']);
			$nodedm->set('threadid', $record['threadid']);
			$nodedm->set('posttitle', $record['threadtitle'] );
			$nodedm->set('postauthor', $record['author'] );
			$nodedm->set('poststarter', $record['poststarter'] );
			$nodedm->set('postid', vB::$vbulletin->GPC['postid'] );
			$nodedm->set('post_started', $record['post_started'] );
			$nodedm->set('post_posted', $record['post_posted'] );
		}
	}

	/*Render========================================================================*/

	/**
	 * Populates a view with the expected info from a content item.
	 *
	 * @param vB_View $view
	 * @param int $viewtype
	 */
	protected function populateViewContent(vB_View $view, $viewtype = self::VIEW_PAGE, $increment_count = true)
	{

		if ($_REQUEST['do']== 'apply' OR $_REQUEST['do'] == 'update' OR $_REQUEST['do'] == 'movenode')
		{
			$this->SaveData();
			$_REQUEST['nocache'] = 1;
		}

		if ($_REQUEST['do'] == 'delete')
		{
			$dm = $this->content->getDM();
			$dm->delete();
			return $vbphrase['article_deleted'];
		}

		//When we come from the link to upgrade a blog post, blog, or forum post, the
		// router puts us here.


		parent::populateViewContent($view, $viewtype);

		// Only break pages for the page view
		if ((self::VIEW_PAGE == $viewtype) OR (self::VIEW_PREVIEW == $viewtype))
		{
			if (self::VIEW_PAGE == $viewtype)
			{
				if ($this->editing)
				{
					$view->pagetext = $this->content->getPageText();
				}
				else
				{
					//$bbcode_parser = new vBCms_BBCode_HTML(vB::$vbulletin, vBCms_BBCode_HTML::fetchCmsTags());
					$bbcode_parser = new vBCms_BBCode_Wysiwyg(vB::$vbulletin, vBCms_BBCode_HTML::fetchCmsTags());
					//				$bbcode_parser->setOutputPage($this->parameters['page']);
					$pagetext = $bbcode_parser->handle_bbcode_img($this->content->getPageText(), true, BBCODE_HAS_ATTACH);
					$view->pagetext = $bbcode_parser->do_parse($pagetext, true);

					//				if (!$bbcode_parser->fetchedValidPage())
					//				{
					//					throw (new vB_Exception_404());
				}

//				}
				$view->parenttitle = $this->content->getParentTitle();
//				$view->pagelist = $bbcode_parser->getPageTitles();


				if ($increment_count)
				{
					//update the view count
					vB::$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX .
							"cms_nodeinfo set viewcount = viewcount + 1 where nodeid = " . $this->content->getNodeId());
				}


				//tagging code
				require_once DIR . '/includes/class_taggablecontent.php';
				$taggable = vB_Taggable_Content_Item::create(vB::$vbulletin, $this->content->getContentTypeId(),
					$this->content->getContentId(), $this->content);
				$view->tags = $taggable->fetch_rendered_tag_list();
				$view->tag_count = $taggable->fetch_existing_tag_count();
				$view->showtags = vB::$vbulletin->options['threadtagging'];

				// get pagelist for navigation
				$view->promoted_threadid = $this->content->getThreadId();
				$view->postitle = $this->content->getPostTitle();
				$view->poststarter = $this->content->getPostStarter();
				$view->postauthor = $this->content->getPostAuthor();
				$view->promoted_blogid = $this->content->getBlogId();
				$view->comment_count = $this->content->getReplyCount();
				$view->authorid = ($this->content->getUserId());
				$view->authorname = ($this->content->getUsername());
				$view->viewcount = ($this->content->getViewCount());
				$view->replycount = ($this->content->getReplyCount());
				$view->postid = ($this->content->getPostId());
				$view->blogpostid = ($this->content->getBlogPostId());
				$view->post_started = ($this->content->getPostStarted());
				$view->post_posted = ($this->content->getPostPosted());
				$view->can_edit = vBCMS_Permissions::canEdit($this->content->getNodeId());
				$view->parentid = $this->content->getParentId();



				//check to see if there is an associated thread.
				if ($associatedthreadid = $this->content->getAssociatedThreadId()
					and $this->content->getComments_Enabled())
				{
					$comment_block = new vBCms_Comments();
					$view->comment_block = $comment_block->getPageView($this->content->getNodeId());
				}

			}
			else if (self::VIEW_PREVIEW == $viewtype)
			{
				if (($pagetext = strip_bbcode($this->content->getPreviewText()) ) == '')
				{
				$pagetext = strip_bbcode($this->content->getPageText());
				$pagetext = nl2br(vbchop($pagetext, $this->preview_length));
				}

				if (!( substr($pagetext, -1, 1) == '.'))
				{
					$view->preview_chopped = 1;
				}

				$segments = array('node' => $this->content->getNodeId() . '-' . $this->content->getUrl(), 'action' =>'view');
				$view->page_url =  vBCms_Route_Content::getURL($segments) ;
				$segments = array('node' => $this->content->getNodeId() . '-' . $this->content->getUrl(), 'action' =>'edit');
				$view->edit_url =  vBCms_Route_Content::getURL($segments) ;
				$view->read_more_phrase = new vB_Phrase('vbcms', 'read_more');
				$view->parenttitle = $this->content->getParentTitle();
				$view->pagetext = $pagetext;
				$view->setpublish = $view->published = $this->content->getSetPublish();
				$view->publishdate = $this->content->getSetPublish();
				$view->promoted_blogid = $this->content->getBlogId();
				$view->comment_count = $this->content->getReplyCount();
				$view->authorid = ($this->content->getUserId());
				$view->authorname = ($this->content->getUsername());
				$view->viewcount = ($this->content->getViewCount());
				$view->replycount = ($this->content->getReplyCount());
				$view->postid = ($this->content->getPostId());
				$view->blogpostid = $this->content->getBlogPostId();
				$view->can_edit = vBCMS_Permissions::canEdit($this->content->getNodeId());
				$view->parentid = $this->content->getParentId();
				$view->post_started = $this->content->getPostStarted();
				$view->post_posted = $this->content->getPostPosted();

				if ($view->previewimage= $this->content->getPreviewImage())
				{
					$view->haspreview = true;
					$view->imagewidth= $this->content->getImageWidth();
					$view->imageheight= $this->content->getImageHeight();
				}

				if (intval($this->content->getReplyCount()) > 0)
				{
					$view->echo_comments = 1;
					$view->comment_count = $this->content->getReplyCount();
				}
				else
				{
					$view->echo_comments = 0;
					$view->comment_count = 0;
				}
			}
		}
		$view->categories = $this->content->getCategories();
		$view->html_title = $this->content->getHtmlTitle();
		$view->title = $this->content->getTitle();
		$view->contenttypeid = vB_Types::instance()->getContentTypeID("vBCms_Article");
		$view->dateformat = vB::$vbulletin->options['dateformat'];
		return $view;
	}

	//At this point some of the images may be in the form [IMG]<base url>/attachment.php?attachmentid=<number><stuff>[/IMG]
	//We need to fix the editor so this isn't necessary, but for now....
	protected function setAttachments($pagetext)
	{
		$offset = 0;

		while($offset < strlen($pagetext) AND ($i = stripos($pagetext, '[IMG]', $offset)) !== false AND $j = stripos($pagetext, '[/IMG]', $offset) AND $j > $i)
		{
			$extract = substr($pagetext, $i, $j-$i + 6);
			if ($k = stripos($extract, 'attachment.php?attachmentid='))
			{
				$attachmentid = intval(substr($extract, $k + 28, min(strpos($pagetext, '&'), strpos($pagetext, '[/IMG]')) - ($k + 28) ) );
				$replace = '[ATTACH=CONFIG]' . $attachmentid . '[/ATTACH]' ;
				$pagetext = str_replace($extract, $replace , $pagetext);
				$offset = $offset + $j + 6 + ( strlen($replace) - strlen($extract));
			}
			else
			{
				$offset = $j + 6;
			}

		}
		return $pagetext;
	}


	protected function saveData()
	{
		if ($this->data_saved )
		{
			return true;
		}
		$this->data_saved = true;

		if ( !vBCMS_Permissions::canEdit($this->content->getNodeId()))

		{
			return $vb_phrase['no_edit_permissions'];
		}

		// collect error messages
		$errors = array();
		vB::$vbulletin->input->clean_array_gpc('p', array(
			'do' => vB_Input::TYPE_STR,
			'message' => vB_Input::TYPE_STR,
			'url' => vB_Input::TYPE_STR,
			'title' => vB_Input::TYPE_NOHTML,
			'setpublish' => TYPE_UINT,
			'html_title' => vB_Input::TYPE_NOHTML,
			'publicpreview' => vB_Input::TYPE_UINT,
			'new_parentid' => vB_Input::TYPE_UINT,
			'comments_enabled' => vB_Input::TYPE_UINT,
			'wysiwyg' => vB_Input::TYPE_BOOL,
			'parseurl' => vB_Input::TYPE_BOOL,
		));

		// get pagetext
		$pagetext = vB::$vbulletin->GPC['message'];
		$html_title = vB::$vbulletin->GPC['html_title'];
		$title = vB::$vbulletin->GPC['title'];

		// unwysiwygify the incoming data
		if (vB::$vbulletin->GPC['wysiwyg'])
		{
			$html_parser = new vBCms_WysiwygHtmlParser(vB::$vbulletin);
			$pagetext = $html_parser->parse($pagetext);
		}

		//At this point some of the images may be in the form [IMG]<base url>/attachment.php?attachmentid=<number><stuff>[/IMG]
		//We need to fix the editor so this isn't necessary, but for now....
		$pagetext = $this->setAttachments($pagetext);

		$dm = $this->content->getDM();

		//set the values, for the dm and update the content.
		if ( vB::$vbulletin->GPC['do'] == 'movenode'
			and vB::$vbulletin->GPC_exists['new_parentid'] AND intval(vB::$vbulletin->GPC['new_parentid']))
		{
			vBCms_ContentManager::moveSection(array($this->content->getNodeId()), vB::$vbulletin->GPC['new_parentid']);
		}

		$dm->set('contentid', $this->content->getId());

		if (vB::$vbulletin->GPC_exists['publicpreview'])
		{
			$new_values['publicpreview'] = vB::$vbulletin->GPC['publicpreview'];
			$dm->set('publicpreview', vB::$vbulletin->GPC['publicpreview']);
		}

		if (vB::$vbulletin->GPC_exists['comments_enabled'])
		{
			$new_values['comments_enabled'] = vB::$vbulletin->GPC['comments_enabled'];
			$dm->set('comments_enabled', vB::$vbulletin->GPC['comments_enabled']);
		}

		if (vB::$vbulletin->GPC_exists['setpublish'])
		{
			$new_values['setpublish'] = vB::$vbulletin->GPC['setpublish'];
			$dm->set('setpublish', vB::$vbulletin->GPC['setpublish']);
		}

		if (vB::$vbulletin->GPC_exists['html_title'])
		{
			$new_values['html_title'] = vB::$vbulletin->GPC['html_title'];
			$dm->set('html_title', vB::$vbulletin->GPC['html_title']);
		}

		if (vB::$vbulletin->GPC_exists['url'])
		{
			$new_values['url'] = vB::$vbulletin->GPC['url'];
			$dm->set('url', vB::$vbulletin->GPC['url']);
		}

		$new_values['pagetext'] = $pagetext;
		$dm->set('pagetext',$pagetext);

		if ($title)
		{
			$new_values['title'] = vB::$vbulletin->GPC['title'];
			$dm->set('title', $pagetext);
		}
		if ($i = strpos($pagetext, '[PRBREAK][/PRBREAK]'))
		{
			$previewtext = substr($pagetext, 0, $i );
			require_once DIR . '/includes/class_bbcode_alt.php';
			$parser = new vB_BbCodeParser_Wysiwyg(vB::$vbulletin, array());
			$dm->set('previewtext', $parser->parse_bbcode($previewtext, false, false, false));
		}

		if (($i = strpos($pagetext, '[IMG]')) !== false and ($j = strpos($pagetext, '[/IMG]')) AND $j > $i)
		{
			$previewimage = substr($pagetext, $i+5, $j - $i - 5);
			if ($size = getimagesize($previewimage))
			{
				$dm->set('previewimage', $previewimage);
				$dm->set('imagewidth', $size[0]);
				$dm->set('imageheight', $size[1]);
			}
		}
		else if (($i = stripos($pagetext, "[ATTACH=CONFIG]")) !== false and ($j = stripos($pagetext, '[/ATTACH]')) AND $j > $i)
		{
			$attachmentid = substr($pagetext, $i + 15, $j - $i - 15);

			if ($record = vB::$vbulletin->db->query_first("SELECT thumbnail_width, thumbnail_height FROM " . TABLE_PREFIX .
				"attachment AS attach INNER JOIN "  . TABLE_PREFIX . "filedata AS data
				ON data.filedataid = attach.filedataid WHERE attachmentid = $attachmentid"))
			{

				$image_template = new vB_View('vbcms_image_src');
				$image_template->attachmentid = $attachmentid;
				$image_template->contenttypeid = vB_Types::instance()->getContentTypeID("vBCms_Article");

				$dm->set('previewimage', $image_template->render(true));

				if ($record['thumbnail_width'] AND $record['thumbnail_height'])
				{
					$dm->set('imagewidth', $record['thumbnail_width']);
					$dm->set('imageheight', $record['thumbnail_height']);

				}
				else
				{
					$dm->set('imagewidth', $record['width']);
					$dm->set('imageheight', $record['height']);

				}
			}
		}

		$this->content->setInfo($new_values);

		//We may have some processing to do for public preview. Let's see if comments
		// are enabled. We never enable them for sections, and they might be turned off globally.
		vB::$vbulletin->input->clean_array_gpc('r', array(
			'publicpreview' => TYPE_UINT));

		if (!intval($this->content->getAssociatedThreadId()) AND
			vB::$vbulletin->GPC_exists['published'] AND intval(vB::$vbulletin->GPC['published']) AND
			vB::$vbulletin->GPC_exists['publicpreview'] AND intval(vB::$vbulletin->GPC['publicpreview']) AND
			intval(vB::$vbulletin->options['vbcmsforumid']) )
		{
			$this->content->associateThread();
		}

		$success = $dm->saveFromForm($this->content->getNodeId());

		if ($dm->hasErrors())
		{
			$fieldnames = array(
				'html_title' => new vB_Phrase('vbcms', 'html_title'),
				'title' => new vB_Phrase('global', 'title')
			);

			$view->errors = $dm->getErrors(array_keys($fieldnames));
			$view->error_summary = self::getErrorSummary($dm->getErrors(array_keys($fieldnames)), $fieldnames);
			$view->status = $view->error_view->title;
		}
		else
		{
			$view->status = new vB_Phrase('vbcms', 'content_saved');
		}

		// postback content
		$view->html_title = $html_title;
		$view->title = $title;
	}


	public function getInlineEditBodyView()
	{
		global $vbphrase;
		require_once DIR . '/includes/functions_databuild.php';
		fetch_phrase_group('cpcms');

		$this->editing = true;

		//confirm that the user has edit rights
		if (!vBCMS_Permissions::canEdit($this->content->getNodeId()))
		{
			return $vb_phrase['no_edit_permissions'];
		}


		vB::$vbulletin->input->clean_array_gpc('r', array(
			'postid' => vB_Input::TYPE_UINT,
			'blogcommentid' => vB_Input::TYPE_UINT,
			'do' => vB_Input::TYPE_STR,
			'blogid' => TYPE_UINT
		));

		if ($_REQUEST['do'] == 'delete')
		{
			$dm = $this->content->getDM();
			$dm->delete();
			return $vbphrase['article_deleted'];
		}

		if ($_REQUEST['do'] == 'apply' OR $_REQUEST['do'] == 'update')
		{
			$this->SaveData();
		}



		require_once DIR . '/packages/vbcms/contentmanager.php';
		// Load the content item
		if (!$this->loadContent($this->getViewInfoFlags(self::VIEW_PAGE)))
		{
			throw (new vB_Exception_404());
		}

		global $show;

		$show['img_bbcode'] = true;
		// Get smiliecache and bbcodecache
		vB::$vbulletin->datastore->fetch('smiliecache,bbcodecache');

		// Create view
		$view = $this->createView('inline', self::VIEW_PAGE);

		// Add the content to the view
		$view = $this->populateViewContent($view, self::VIEW_PAGE, false);
		$pagetext = $this->content->getPageText();

		// Get postings phrasegroup
		// need posting group
		require_once DIR . '/includes/functions_databuild.php';
		fetch_phrase_group('posting');

		// Build editor
		global $messagearea;
		require_once DIR . '/includes/functions_file.php';
		require_once DIR . '/includes/functions_editor.php';
		require_once(DIR . '/packages/vbattach/attach.php');

		$view->formid = "cms_article_data";
		//$attachinfo = array('nodeid' => $this->content->getNodeId(), 'url' => $this->content->getUrl());

		$attach = new vB_Attach_Display_Content(vB::$vbulletin, 'vBCms_Article');
		//this will set a number of its parameters if they are not already set.
		$posthash = null;
		$poststarttime = null;
		$postattach = array();
		$attachcount = 0;

		$values = "values[f]=" . $this->content->getNodeId() ;

		$attachmentoption = $attach->fetch_edit_attachments($posthash, $poststarttime, $postattach,
			$this->content->getNodeId(), $values, '', $attachcount);

		$view->editorid = construct_edit_toolbar($pagetext, false,
			new vBCms_Editor_Override(vB::$vbulletin), true, true, false, 'cms_article');

		$attachinfo = array(
			'auth_type'     => 0,
			'posthash'      => $posthash,
			'poststarttime' => $poststarttime,
			'userid'        => vB::$vbulletin->userinfo['userid'],
			'contenttypeid' => $this->getContentTypeId(),
			'max_file_size' => fetch_max_upload_size(),
			'values'        => array('f' => $this->content->getNodeId())
		);

		$view->editorid = construct_edit_toolbar(
			$pagetext,
			false,
			new vBCms_Editor_Override(vB::$vbulletin),
			true,
			true,
			true,
			'cms_article',
			'',
			$attachinfo
		);

		$templater = vB_Template::create('vbcms_article_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();


		$view->editor = $content;
		$view->url = $this->content->getUrl();
		$view->type = new vB_Phrase('vbcms', 'content');
		$view->adding = 	new vB_Phrase('cpcms', 'adding_x', $vbphrase['article']);
		$view->html_title = $this->content->getHtmlTitle();
		$view->title = $this->content->getTitle();
		$view->publicpreview = $this->content->getPublicPreview();
		$view->metadata = $this->content->getMetadataEditor();
		$view->comments_enabled = ($this->content->getComments_Enabled());
		$segments = array('node' => $this->content->getUrlSegment(),
							'action' => vB_Router::getUserAction('vBCms_Controller_Content', 'View'));
		$view->view_url = vBCms_Route_Content::getURL($segments);
		// Add URL to submit to
		$segments = array('node' => $this->content->getUrlSegment(),
							'action' => vB_Router::getUserAction('vBCms_Controller_Content', 'EditPage'));
		$view->submit_url = vBCms_Route_Content::getURL($segments);
		$segments = array('node' => $this->content->getUrlSegment(),
							'action' => vB_Router::getUserAction('vBCms_Controller_Content', 'View'));
		$view->editbar = $this->content->getEditBar($view->submit_url, vBCms_Route_Content::getURL($segments), $view->formid);
		$view->publisher = $this->content->getPublishEditor($view->submit_url, $view->formid);
		$view->authorid = ($this->content->getUserId());
		$view->authorname = ($this->content->getUsername());
		$view->viewcount = ($this->content->getViewCount());
		$view->parentid = $this->content->getParentId();
		$view->post_started = ($this->content->getPostStarted());
		$view->post_posted = ($this->content->getPostPosted());

		$view->comment_count = ($this->content->getReplyCount());

		$view->show_threaded = true;
		$view->per_page = 10;
		$view->indent_per_level = 5;
		$view->max_level = 4;
		// Add form check
		$this->addPostId($view);
		return $view;
	}


	/**
	 * Creates a content view.
	 * The default method fetches a view based on the required result, package
	 * identifier and content class identifier.  Child classes may want to override
	 * this.  Ths method is also voluntary if the getView methods are overriden.
	 *
	 * @param string $result					- The result identifier for the view
	 * @return vB_View
	 */
	protected function createView($result)
	{
		$result = strtolower($this->package . '_content_' . $this->class . '_' . $result);

		return new vBCms_View_Article($result);
	}
}

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

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