<?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_Widget_Nav
 *
 * @package
 * @author ebrown
 * @copyright Copyright (c) 2009
 * @version $Id: sectionnav.php 32078 2009-09-16 20:39:09Z ebrown $
 * @access public
 */
class vBCms_Widget_SectionNav extends vBCms_Widget
{
	/*Properties====================================================================*/

	/**
	 * A package identifier.
	 * This is used to resolve any related class names.
	 * It is also used by client code to resolve the class name of this widget.
	 *
	 * @var string
	 */
	protected $package = 'vBCms';

	/**
	 * A class identifier.
	 * This is used to resolve any related class names.
	 * It is also used by client code to resolve the class name of this widget.
	 *
	 * @var string
	 */
	protected $class = 'SectionNav';

	protected $cache_ttl = 5;


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

	/**
	 * Returns the config view for the widget.
	 *
	 * @return vBCms_View_Widget				- The view result
	 */
	public function getConfigView($widget = false)
	{
		global $vbphrase;
		$this->assertWidget();

		vB::$vbulletin->input->clean_array_gpc('r', array(
			'do'      => vB_Input::TYPE_STR,
			'template_name'    => vB_Input::TYPE_STR
			));

		$view = new vB_View_AJAXHTML('cms_widget_config');
		$view->title = new vB_Phrase('vbcms', 'configuring_widget_x', $this->widget->getTitle());
		$config = $this->widget->getConfig();
		$widgetdm = $this->widget->getDM();

		if ((vB::$vbulletin->GPC['do'] == 'config') AND $this->verifyPostId())
		{
			if (vB::$vbulletin->GPC_exists['template_name'])
			{
				$config['template_name'] = vB::$vbulletin->GPC['template_name'];
			}

			if ($this->content)
			{
				$widgetdm->setConfigNode($this->content->getNodeId());
			}

			$widgetdm->set('config', $config);
			$widgetdm->save();

			if (!$widgetdm->hasErrors())
			{
				if ($this->content)
				{
					$segments = array('node' => $this->content->getNodeURLSegment(),
										'action' => vB_Router::getUserAction('vBCms_Controller_Content', 'EditPage'));
					$view->setUrl(vB_View_AJAXHTML::URL_FINISHED, vBCms_Route_Content::getURL($segments));
				}

				$view->setStatus(vB_View_AJAXHTML::STATUS_FINISHED, new vB_Phrase('vbcms', 'configuration_saved'));
			}
			else
			{
				if (vB::$vbulletin->debug)
				{
					$view->addErrors($widgetdm->getErrors());
				}

				// only send a message
				$view->setStatus(vB_View_AJAXHTML::STATUS_MESSAGE, new vB_Phrase('vbcms', 'configuration_failed'));
			}
		}
		if (!isset($config['template_name']) OR ($config['template_name'] == '') )
		{
			$config['template_name'] = 'vbcms_widget_sectionnav_page';
		}
		// add the config content
		$configview = $this->createView('config');

		$configview->template_name = $config['template_name'];


		// item id to ensure form is submitted to us
		$this->addPostId($configview);

		$view->setContent($configview);

		// send the view
		$view->setStatus(vB_View_AJAXHTML::STATUS_VIEW, new vB_Phrase('vbcms', 'configuring_widget'));

		return $view;	}


	/**
	 * Fetches the standard page view for a widget.
	 *
	 * @param bool $skip_errors					- If using a collection, omit widgets that throw errors
	 * @return vBCms_View_Widget				- The resolved view, or array of views
	 */
	public function getPageView()
	{

		$this->assertWidget();

		if (! isset($vbulletin->userinfo['permissions']['cms']))
		{
			require_once DIR . '/packages/vbcms/permissions.php';
			vBCMS_Permissions::getUserPerms();
		}
		// Create view
		$config = $this->widget->getConfig();
		if (!isset($config['template_name']) OR ($config['template_name'] == '') )
		{
			$config['template_name'] = 'vbcms_widget_sectionnav_page';
		}

		$canviewlist = implode(', ', vB::$vbulletin->userinfo['permissions']['cms']['canview']);
		$caneditlist = implode(', ', vB::$vbulletin->userinfo['permissions']['cms']['canview']);
		// Create view
		$view = new vBCms_View_Widget($config['template_name']);
		if (!isset($_REQUEST['nocache']) AND $link_nodes = vB_Cache::instance()->read($cache_key = $this->getHash($this->widget->getId()), true))
		{
			$links_before = $link_nodes['links_before'];
			$links_above = $link_nodes['links_above'];
			$links_sibling = $link_nodes['links_sibling'];
			$links_children = $link_nodes['links_children'];
			$links_after = $link_nodes['links_after'];
			$myself = $link_nodes['myself'];
		}
		else
		{
			//If we're on a section, we show for this nodeid. If we're on
			// on a leaf-type node we show for the parent
			$for_node = intval($this->content->getContentTypeId()) == intval(vb_Types::instance()->getContentTypeID("vBCms_Section")) ?
				$this->content->getNodeId() : $this->content->getParentId();


			//First we'll generate our parentage. Remember the title- we'll need it in a minute.
			$rst = vB::$vbulletin->db->query_read($sql = "SELECT node.nodeid, node.parentnode, info.title, node.url
			FROM " . TABLE_PREFIX . "cms_node AS bottom
			INNER JOIN " . TABLE_PREFIX . "cms_node AS node ON bottom.nodeleft BETWEEN node.nodeleft AND node.noderight
			LEFT JOIN " . TABLE_PREFIX . "cms_nodeinfo AS info ON info.nodeid = node.nodeid
			WHERE bottom.nodeid = $for_node AND node.parentnode IS NOT NULL
			AND node.contenttypeid = " .	vb_Types::instance()->getContentTypeID("vBCms_Section") . "
			ORDER by node.nodeleft;");
			$record = vB::$vbulletin->db->fetch_array($rst);
			$links_before = array();
			$links_above = array();
			$links_sibling = array();
			$links_after = array();
			$links_children = array();
			$myself = array();
			$indent = 0;
			$route = new vBCms_Route_Content();
			while($record)
			{
				$route->node = $record['nodeid'] . (strlen($record['url']) ? '-' . $record['url'] : '' );
				if (intval($record['nodeid']) == intval($for_node))
				{
					$myself = array('sectionurl' => $route->getCurrentUrl(),
					'title' => $record['title'], 'indent' => $indent * 10);
				}
				else
				{
					$indent++;
					$links_above[] = array('title' => $record['title'],
					 'sectionurl' => $route->getCurrentUrl(),
					 'indent' => $indent * 10);
				}
				$record = vB::$vbulletin->db->fetch_array($rst);
			}

			//Now- if we're a top-level node,  then siblings and top-level are the same.
			// we recognize that by a count of zero.
			if (count($links_above) > 0)
			{
				//Now get our siblings
				$rst = vB::$vbulletin->db->query_read($sql = "SELECT node.nodeid, node.url, info.title
			FROM " . TABLE_PREFIX . "cms_node AS bottom
			INNER JOIN " . TABLE_PREFIX . "cms_node AS node ON node.parentnode = bottom.parentnode
			LEFT JOIN " . TABLE_PREFIX . "cms_nodeinfo AS info ON info.nodeid = node.nodeid
			WHERE bottom.nodeid = $for_node AND node.contenttypeid = " .
			vb_Types::instance()->getContentTypeID("vBCms_Section") . " AND (
				(node.setpublish > 0 AND node.publishdate < " . TIMENOW . "
				AND node.permissionsfrom in ($canviewlist)) or
				node.permissionsfrom in ($caneditlist) )
			ORDER by info.title");

				while($record = vB::$vbulletin->db->fetch_array($rst))
				{
					$route->node = $record['nodeid'] . (strlen($record['url']) ? '-' . $record['url'] : '' );
					if (intval($record['nodeid']) != intval($for_node))
					{
						$links_sibling[] = array('title' => $record['title'],
							'sectionurl' => $route->getCurrentUrl(),
							'indent' => $indent * 10);
					}
				}
			}

			//Now pull the child nodes, unless we're at the root
			if (1 != intval($for_node))
			{
				$rst = vB::$vbulletin->db->query_read($sql = "SELECT node.nodeid, node.url, info.title FROM
				" . TABLE_PREFIX . "cms_node AS node
				LEFT JOIN " . TABLE_PREFIX . "cms_nodeinfo AS info ON info.nodeid = node.nodeid
				WHERE node.contenttypeid = " .
					vb_Types::instance()->getContentTypeID("vBCms_Section") . " AND node.parentnode = $for_node
				AND ((node.setpublish > 0 AND node.publishdate < " . TIMENOW . "
				AND node.permissionsfrom in ($canviewlist)) or
				node.permissionsfrom in ($caneditlist) )
				ORDER BY info.title");

				while($record = vB::$vbulletin->db->fetch_array($rst))
				{
					$route->node = $record['nodeid'] . (strlen($record['url']) ? '-' . $record['url'] : '' );
					$links_children[] =  array('title' => $record['title'],
							 'sectionurl' => $route->getCurrentUrl(),
							 'indent' => ($indent + 1) * 10);

				}
			}

			//Now pull the before & after nodes
			$rst = vB::$vbulletin->db->query_read($sql = "SELECT info2.title AS toptitle,
			 top.url AS topurl, top.nodeid AS topnode, node.nodeid, node.url, info.title AS title FROM
			" . TABLE_PREFIX . "cms_node AS top
			INNER JOIN " . TABLE_PREFIX . "cms_node AS node ON node.parentnode = top.nodeid
			LEFT JOIN " . TABLE_PREFIX . "cms_nodeinfo AS info2 ON info2.nodeid = top.nodeid
			LEFT JOIN " . TABLE_PREFIX . "cms_nodeinfo AS info ON info.nodeid = node.nodeid
			WHERE top.parentnode IS NULL AND node.contenttypeid = " .
				vb_Types::instance()->getContentTypeID("vBCms_Section") . " AND (
				(node.setpublish > 0 AND node.publishdate < " . TIMENOW . "
				AND node.permissionsfrom in ($canviewlist)) or
				node.permissionsfrom in ($caneditlist) )
			ORDER BY info.title");

			$record = vB::$vbulletin->db->fetch_array($rst);
			$route->node = $record['topnode'] . (strlen($record['topurl']) ? '-' . $record['topurl'] : '' );
			$links_before[] =  array('title' => $record['toptitle'],
				 'sectionurl' => $route->getCurrentUrl());
			while($record)
			{
				$route->node = $record['nodeid'] . (strlen($record['url']) ? '-' . $record['url'] : '' );

				if (intval($record['nodeid']) == intval($for_node))
				{
					$record = vB::$vbulletin->db->fetch_array($rst);
					continue;
				}
				else if ($record['title'] < $first_name)
				{
					$links_before[] =  array('title' => $record['title'],
						 'sectionurl' => $route->getCurrentUrl());

				}
				else if (intval($record['nodeid']) != intval($first_node))
				{
					$links_after[] =  array('title' => $record['title'],
						 'sectionurl' => $route->getCurrentUrl());
				}

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

			vB_Cache::instance()->write($cache_key,
				   array('links_before' => $links_before, 'links_above' => $links_above,
				   'links_sibling' => $links_sibling , 'links_after' => $links_after,
				   'links_children' => $links_children, 'myself' => $myself ), $this->cache_ttl);
		}

		$view->links_before = $links_before;
		$view->links_above = $links_above;
		$view->links_sibling = $links_sibling;
		$view->links_children = $links_children;
		$view->links_after = $links_after;
		$view->myself = $myself;
		$view->widget_title = $this->widget->getTitle();

		return $view;
	}

	/**
	 * This returns a hash for widget caching. We include nodeid and userid b
	 *
	 *
	 * @param integer $widgetid
	 * @return hash that will identify this widget content for this page
	 */
	protected function getHash($widgetid)
	{
		$context = new vB_Context('widget' , array('widgetid' => $widgetid,
			'group' => vB::$vbulletin->userinfo['usergroupid'],
			'groups' => vB::$vbulletin->userinfo['membergroupids'],
			'nodeid' => $this->content->getNodeId()));
		return strval($context);

	}

}

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

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