<?php

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

class vB5_Route_Conversation extends vB5_Route
{
	public function __construct($routeInfo, $matches, $queryString = '')
	{
		parent::__construct($routeInfo, $matches, $queryString);
		
		if (isset($this->arguments['channelid']))
		{
			// check if we need to force a styleid
			$channel = vB_Library::instance('Content_Channel')->getContent($this->arguments['channelid']);
			if (is_array($channel))
			{
				$channel = array_pop($channel);
			}
			
			if (!empty($channel['styleid']))
			{
				$forumOptions = vB::getDatastore()->getValue('bf_misc_forumoptions');
				if($forumOptions['styleoverride'] & $channel['options'])
				{
					// the channel must force the style
					$this->arguments['forceStyleId'] = $channel['styleid'];
				}
				else
				{
					// the channel suggests to use this style
					$this->arguments['routeStyleId'] = $channel['styleid'];
				}
			}
			
			$this->setPageKey('pageid', 'channelid', 'nodeid');
		}
		
		if (isset($this->arguments['nodeid']))
		{
			$node = vB_Library::instance('node')->getNodeContent($this->arguments['nodeid']);
			if ($node)
			{
				$node = array_pop($node);
				
				// set user action
				$this->setUserAction('viewing_topic_x', $node['title'], $this->getFullUrl('nosession'));
				
				// set last crumb
				$this->breadcrumbs[] = array(
					'title' => $node['title'],
					'url'	=> ''
				);
			}
		}
	}

	protected static function validInput(array &$data)
	{
		// ignore page number
		unset($data['pagenum']);
		
		if (
				!isset($data['channelid']) OR !is_numeric($data['channelid']) OR
				!isset($data['pageid']) OR !is_numeric($data['pageid']) // this is used for rendering the page
			)
		{
			return FALSE;
		}
		$data['channelid'] = intval($data['channelid']);
		$data['pageid'] = intval($data['pageid']);

		if (!isset($data['prefix']))
		{
			$channelApi = vB_Api::instanceInternal('content_channel');
			$channel = $channelApi->fetchChannelById($data['channelid']);
			$channelUrl = self::buildUrl("{$channel['routeid']}|nosession");

			if ($channelUrl AND $channelUrl{0} == '/')
			{
				$channelUrl = substr($channelUrl, 1);
			}

			$data['prefix'] = $channelUrl;
			$data['regex'] = $channelUrl . '/(?P<nodeid>[0-9]+)(?P<title>(-[A-Za-z0-9-]*)*)(?:/page(?P<pagenum>[0-9]+))?';
			$data['arguments'] = serialize(array(
				'nodeid'	=> '$nodeid',
				'pagenum'	=> '$pagenum',
				'channelid' => $data['channelid'],
				'pageid'	=> $data['pageid']
			));
		}
		else
		{
			if (!isset($data['nodeid']))
			{
				// when modifying the url for a conversation page, we need to store the conversation node id
				return FALSE;
			}

			$data['regex'] = $data['prefix'];
			$data['arguments'] = serialize(array(
				'nodeid'	=> $data['nodeid'],
				'customUrl'	=> true,
				'pagenum'	=> '$pagenum',
				'channelid' => $data['channelid'],
				'pageid'	=> $data['pageid']
			));
			unset($data['nodeid']);
		}
		
		$data['class'] = __CLASS__;
		$data['controller']	= 'page';
		$data['action']		= 'index';
		// this field will be used to delete the route when deleting the channel (contains channel id)
		$data['contentid'] = $data['channelid'];
		
		unset($data['channelid']);
		unset($data['pageid']);

		return parent::validInput($data);
	}
	
	protected static function updateContentRoute($oldRouteInfo, $newRouteInfo)
	{
		$db = vB::getDbAssertor();
		
		$arguments = unserialize($newRouteInfo['arguments']);

		// update routeid in nodes table
		$db->update('node', array('routeid' => $newRouteInfo['routeid']), array('nodeid' => $arguments['nodeid']));
		// don't modify the routeid for default pages, as it will still be used
		$db->update('page', array('routeid' => $newRouteInfo['routeid']), array('routeid' => $oldRouteInfo['routeid'], 'pagetype' => vB_Page::TYPE_CUSTOM));
	}

	public function getUrl()
	{
		if (isset($this->arguments['customUrl']) AND $this->arguments['customUrl'])
		{
			$result = '/' . $this->prefix;
		}
		else
		{
			$channelApi = vB_Api::instanceInternal('content_channel');
			$channel = $channelApi->fetchChannelById($this->arguments['channelid']);
			$channelUrl = self::buildUrl("{$channel['routeid']}|nosession");

			$nodeApi = vB_Api::instanceInternal('node');
			$node = $nodeApi->getNodeContent($this->arguments['nodeid']);
			$node = $node[$this->arguments['nodeid']];

			$mainConversationId = $node['starter'];
			if ($mainConversationId AND $mainConversationId != $node['nodeid'])
			{
				$mainConversation = $nodeApi->getNodeContent($mainConversationId);
				$urlident = $mainConversation[$mainConversationId]['urlident'];
			}
			else
			{
				$urlident = $node['urlident'];
			}

			$result = $channelUrl . '/' . $node['nodeid'] . '-' . $urlident;
		}

		if (isset($this->arguments['pagenum']) AND is_numeric($this->arguments['pagenum']))
		{
			$result .= '/page' . intval($this->arguments['pagenum']);
		}
		
		return $result;
	}

	public function  getCanonicalRoute()
	{
		if (!isset($this->canonicalRoute))
		{
			$node = vB::getDbAssertor()->getRow('node', array('nodeid'=>$this->arguments['nodeid']));
			$data = array(
				'channelid'=>$this->arguments['channelid'],
				'nodeid'=>$this->arguments['nodeid']
			);
			if ($this->arguments['pagenum'] > 1)
			{
				$data['pagenum'] = $this->arguments['pagenum'];
			}
			$this->canonicalRoute = self::getRoute($node['routeid'], $data);
		}

		return $this->canonicalRoute;
	}
	
	public static function exportArguments($arguments)
	{
		$data = unserialize($arguments);
		
		$channel = vB::getDbAssertor()->getRow('channel', array('nodeid' => $data['channelid']));
		if (empty($channel))
		{
			throw new Exception('Couldn\'t find channel');
		}
		$data['channelGuid'] = $channel['guid'];
		unset($data['channelid']);
		
		
		$page = vB::getDbAssertor()->getRow('page', array('pageid' => $data['pageid']));
		if (empty($page))
		{
			throw new Exception('Couldn\'t find page');
		}
		$data['pageGuid'] = $page['guid'];
		unset($data['pageid']);
		
		return serialize($data);
	}
	
	public static function importArguments($arguments)
	{
		$data = unserialize($arguments);
		
		$channel = vB::getDbAssertor()->getRow('channel', array('guid' => $data['channelGuid']));
		if (empty($channel))
		{
			throw new Exception('Couldn\'t find channel');
		}
		$data['channelid'] = $channel['nodeid'];
		unset($data['channelGuid']);
		
		$page = vB::getDbAssertor()->getRow('page', array('guid' => $data['pageGuid']));
		if (empty($page))
		{
			throw new Exception('Couldn\'t find page');
		}
		$data['pageid'] = $page['pageid'];
		unset($data['pageGuid']);
		
		return serialize($data);
	}
	
	public static function importContentId($arguments)
	{
		return $arguments['channelid'];
	}
}

/*======================================================================*\
|| ####################################################################
|| # 
|| # CVS: $RCSfile$ - $Revision: 40911 $
|| ####################################################################
\*======================================================================*/
