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

/**
 * Main CMS Page Controller
 * Page controller with actions to view nodes, edit nodes, edit content, add and
 * delete content.
 *
 * @TODO: Generalise some of the stuff that's done in multiple actions.  This class
 * is still a rough merge of various controllers into action methods.
 *
 * @TODO: We have to abstract the overlay stuff somehow so that config views can be
 * rendered as part of a html page; and to make overlay views easier to work with.
 *
 * @author vBulletin Development Team
 * @version $Revision: 32126 $
 * @since $Date: 2009-09-18 15:39:16 -0500 (Fri, 18 Sep 2009) $
 * @copyright Jelsoft Enterprises Ltd.
 */
class vBCms_Controller_List extends vBCms_Controller
{
	/*Properties====================================================================*/

	/**
	 * The package that the controller belongs to.
	 *
	 * @var string
	 */
	protected $package = 'vBCms';

	/**
	 * The class string id that identifies the controller.
	 *
	 * @var string
	 */
	protected $class = 'List';

	/**
	 * The action definitions for the controller.
	 *
	 * @var array string => bool
	 */
	protected $actions = array(
		'list'
	);

	protected $params;
	protected $styleid;
	protected $layoutid;
	protected $authorid;
	protected $categoryid;
	protected $sectionid;
	protected $query_filter = '';
	protected $joins = '';
	protected $displaysectionid = 1;
	protected $perpage = 5;
	protected $title = '';
	protected $result_type;

	/*Initialization================================================================*/

	public function __construct($parameters, $action = 'list')
	{
		$this->params = $parameters;
		// Evaluate the node that we're working with
		$this->initialize();
		$this->registerXHTMLTemplater();
	}


	/**
	 * Initialisation.
	 * Initialises the view, templaters and all other necessary objects for
	 * successfully creating the response.
	 */
	protected function initialize()
	{
		// Setup the templater.  Even XML output needs this for the html response
		//First we need a node from which we can get a style.

		//We need to set sectionid, style, and layout
		global $vbphrase;
		require_once DIR . '/includes/functions_databuild.php';
		fetch_phrase_group('vbcms');

			switch($this->params[1])
		{
			case 'author':
				//if we were passed a parameter for fromsection, we use that.
				//or it could be the fourth parameter.
				vB::$vbulletin->input->clean_array_gpc('r', array(
					'fromsection' => TYPE_INT,
					'sectionid' => TYPE_INT,
					));

				if (count($this->params) > 1 AND intval($this->params[2]))
				{
					$this->query_filter = " AND node.userid = " . intval($this->params[2]);
				}

				if (vB::$vbulletin->GPC_exists['fromsection'] AND intval(vB::$vbulletin->GPC['fromsection']))
				{
					$displaysectionid = intval(vB::$vbulletin->GPC['fromsection']);
				}
				else if (vB::$vbulletin->GPC_exists['sectionid'] AND intval(vB::$vbulletin->GPC['sectionid']))
				{
					$displaysectionid = intval(vB::$vbulletin->GPC['sectionid']);
				}
				else if (count($this->params) > 3 AND intval($this->params[4]))
				{
					$displaysectionid = intval($this->params[4]);
				}
				//we haven't got a section.
				else $displaysectionid = "SELECT MIN(nodeid) AS nodeid FROM " . TABLE_PREFIX . "cms_node WHERE
					parentnode IS NULL";
				;
				if ($record = vB::$vbulletin->db->query_first("SELECT username FROM " .TABLE_PREFIX .
					"user WHERE userid = " . $this->params[2]))
				{
					$this->title = $record['username'];
				}
				$this->result_type = $vbphrase['author'];
				break;
			case 'section':

				if (count($this->params) > 1 AND intval($this->params[2]))
				{
					$this->query_filter = " AND node.parentnode = " . intval($this->params[2]);
				}

				if (count($this->params) > 2 AND intval($this->params[2]))
				{
					$displaysectionid = intval($this->params[2]);
				}
				//we haven't got a section.
				else
				{
					if ($record = vB::$vbulletin->db->query_first("SELECT MIN(nodeid) AS nodeid FROM " . TABLE_PREFIX . "cms_node WHERE
						parentnode IS NULL"))
					{
						$displaysectionid = $record['nodeid'];
					}

				}

				if ($record = vB::$vbulletin->db->query_first("SELECT title FROM " .TABLE_PREFIX .
					"cms_nodeinfo WHERE nodeid = ($displaysectionid)" ))
				{
					$this->title = $record['title'];
				}

				$this->result_type = $vbphrase['section'];
				break;

			case 'category':

				if (count($this->params) > 1 AND intval($this->params[2]))
				{
					$this->joins = " INNER JOIN " . TABLE_PREFIX . "cms_nodecategory AS nodecat ON nodecat.nodeid = node.nodeid
						 AND nodecat.categoryid =" . intval($this->params[2]);
				}

				if (count($this->params) > 2 AND intval($this->params[2]))
				{
					$displaysectionid = "SELECT parentnode AS nodeid FROM " . TABLE_PREFIX . "cms_category WHERE
					categoryid = " . intval($this->params[2]) ;
				}
				//we haven't got a section.
				else $displaysectionid = "SELECT MIN(nodeid) AS nodeid FROM " . TABLE_PREFIX . "cms_node WHERE
					parentnode IS NULL";
				;

				if ($record = vB::$vbulletin->db->query_first("SELECT category FROM " .TABLE_PREFIX .
					"cms_category WHERE categoryid = " . $this->params[2]))
				{
					$this->title = $record['category'];
				}
				$this->result_type = $vbphrase['category'];
				break;

			default:
				//we haven't got a section.
				$displaysectionid = "SELECT MIN(nodeid) AS nodeid FROM " . TABLE_PREFIX . "cms_node WHERE
					parentnode IS NULL";
				;
				if ($record = vB::$vbulletin->db->query_first("SELECT title FROM " .TABLE_PREFIX .
					"cms_nodeinfo WHERE nodeid = ($displaysectionid)"))
				{
					$this->title = $record['title'];
					$this->result_type = $vbphrase['section'];
				}
				$this->result_type = $vbphrase['section'];
			;
		} // switch

		if (! is_numeric($displaysectionid) )
		{
			$record = vB::$vbulletin->db->query_first($displaysectionid);
			$displaysectionid = $record['nodeid'];
		}

		$rst = vB::$vbulletin->db->query_read("SELECT parent.nodeid, parent.styleid, parent.layoutid from " .
			TABLE_PREFIX . "cms_node AS node	INNER JOIN " . TABLE_PREFIX .
			"cms_node AS parent ON node.nodeleft BETWEEN parent.nodeleft AND parent.noderight
			   WHERE node.nodeid = " . $displaysectionid . "
			 ORDER BY parent.nodeleft DESC ;");

		$record = vB::$vbulletin->db->fetch_array($rst);

		$this->sectionid = $record['nodeid'];

		$node = vBCms_Item_Content::create('vBCms', 'Section', $displaysectionid);
		$node->requireInfo(vBCms_Item_Content::INFO_NODE);
		vBCms_NavBar::prepareNavBar($node);

		while($record)
		{
			if (intval($record['layoutid']) AND !intval($this->layoutid))
			{
				$this->layoutid = $record['layoutid'];
			}
			if (intval($record['styleid']) AND !intval($this->styleid))
			{
				$this->styleid = $record['styleid'];
			}

			if (intval($this->styleid) AND intval($this->layoutid))
			{
				$this->displaysectionid = $displaysectionid;
				return;
			}

			$record = vB::$vbulletin->db->fetch_array($rst);
		}

		if (!intval($this->styleid))
		{
			$this->styleid = 1;
		}

		if (!intval($this->layoutid))
		{
			$this->layoutid = 1;
		}



	}

	/*Actions=======================================================================*/


	public function setPageNo($pageno)
	{
		$this->params[3] = $pageno;
	}

	private function getTitle()
	{
		//{vb:var $title}
	}

	public function actionList()
	{
		//This is an aggregator. We can pull in three different modes as of this writing,
		// and we plan to add more. We can have passed on the url the following:
		// author=id, category=id, section=id, and format=id. "Format" should normally
		// be passed as for author only, and it defines a sectionid to be used for the format.

		global $vbphrase;

		if (! isset($this->params[1]))
		{
			$this->params[1] = 'section';
		}

		if (! isset($this->params[2]))
		{
			$this->params[2] = 1;
		}

		if (! isset($this->params[3]))
		{

			$this->params[3] = 1;
		}


		// Create the page view
		$view = new vB_View_Page('vbcms_page');

		$view->page_url = vB_Router::getURL();
		$view->base_url = vB_Router::getBaseRoutingURL();
		$view->rawtitle = $this->title;

		$this->content = vB_Content::create('vBCms', 'Section', $this->displaysectionid) ;

		// Get layout
		$this->layout = new vBCms_Item_Layout($this->layoutid);
		$this->layout->requireInfo(vBCms_Item_Layout::INFO_CONFIG | vBCms_Item_Layout::INFO_WIDGETS);
		// Create the layout view
		$layout = new vBCms_View_Layout($this->layout->getTemplate());
		$layout->contentcolumn = $this->layout->getContentColumn();
		$layout->contentindex = $this->layout->getContentIndex();

		// Get content controller
		$collection = new vBCms_Collection_Content();

		$collection->setContentQueryWhere($this->query_filter . " AND node.contenttypeid <> "
			. vB_Types::instance()->getContentTypeID("vBCms_Section")	);

		$collection->setContentQueryJoins($this->joins);

		$collection->paginate();
		$collection->paginateQuantity($this->perpage);
		$collection->paginatePage($this->params[3]);


		$results = array();
		// Get the content view
		foreach($collection as $id => $content)
		{
			// get the content controller
			$controller = vB_Types::instance()->getContentTypeController($content->getContentTypeId(), $content);

			// set preview length
			$controller->setPreviewLength(400);

			// get the aggregate view from the controller
			if ($result = $controller->getPreview())
			{
				$results[$id] = $result;
			}
		}
		$recordcount = $collection->getCount();
		$contentview->contenttypeid = vB_Types::instance()->getContentTypeID("vBCms_Section");
		$contentview->contentid = $contentview->item_id = $contentview->nodeid = $this->displaysectionid;
		$contentview = new vB_View_Content('vbcms_content_list');
		$contentview->package = 'vBCms';
		$contentview->class = 'Section';
		$contentview->result_type = $this->result_type;
		$contentview->rawtitle = $this->title;
		if (! $recordcount)
		{
			switch($this->params[1]){
				case 'author':
					$contentview->contents = array(1 => new vB_Phrase('vbcms', 'no_content_for_author_x', $this->title ));
					break;
				case 'section':
					$contentview->contents = array(1 => new vB_Phrase('vbcms', 'no_content_for_section_x', $this->title ));
					break;
				case 'category':
					$contentview->contents = array(1 => new vB_Phrase('vbcms', 'no_content_for_category_x', $this->title ));
					break;
				;
			} // switch

		}
		else
		{
			$contentview->contents = $results;

			if (intval($recordcount) > intval($this->perpage))
			{
				$pagelist = vBCms_ContentManager::getPageList($this->perpage, $recordcount, $this->params[3]);
				unset($this->params[3]);
				$contentview->page_url = vB_Router::getURL()  . implode ('/',$this->params)	;

				$contentview->pageno_list = $pagelist;
				$contentview->pagecount = count($pagelist) + 2;

			}
			else
			{
				$contentview->pagecount = 1;
			}

		}
		$layout->content = $contentview;

		// Get widget locations
		$layout->widgetlocations = $this->layout->getWidgetLocations();

		// Get Widgets
		$widgets = vBCms_Widget::getWidgetCollection($this->layout->getWidgetIds(), vBCms_Item_Widget::INFO_CONFIG, $this->displaysectionid);
		$widgets = vBCms_Widget::getWidgetControllers($widgets, true, $this->content);

		// Get the widget views
		$widget_views = array();
		foreach($widgets AS $widgetid => $widget)
		{
			try
			{
				$widget_views[$widgetid] = $widget->getPageView();
			}
			catch (vB_Exception $e)
			{
				if ($e->isCritical())
				{
					throw ($e);
				}

				if (vB::$vbulletin->debug)
				{
					$widget_views[$widgetid] = 'Exception: ' . $e;
				}
			}
		}

		// Assign the widgets to the layout view
		$layout->widgets = $widget_views;

		// Assign the layout view to the page view
		$view->layout = $layout;

		// Add general page info
		$view->setPageTitle($this->content->getTitle());
		$view->pagedescription = $this->content->getDescription();

		// Render view and return
		return $view->render();
	}
	/**
	 * Views the page in edit mode
	 *
	 * @return string
	 */


	/**
	 * Sets up the XHTML templater.
	 */
	protected function registerXHTMLTemplater()
	{
		// Create the standard vB templater
		$templater = new vB_Templater_vB();

		// TODO: Check if node allows user style.  Check if current user style is allowed. Apply user style.
		$templater->setStyle($this->styleid);

		// Register the templater to be used for XHTML
		vB_View::registerTemplater(vB_View::OT_XHTML, new vB_Templater_vB());
	}


	/**
	 * Sends an AJAXHTML save failed message.
	 *
	 * @param vB_View $view
	 * @param string $debug_message
	 */
	protected function saveError(vB_View_AJAXHTML $view, $debug_message)
	{
		if ($debug_message)
		{
			$view->addError($debug_message, 'debug');
		}

		$view->setStatus(vB_View_AJAXHTML::STATUS_MESSAGE, new vB_Phrase('vbcms', 'save_failed'));

		return $view->render(true);
	}
}

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

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