//<?php

class cms_hook_Url extends _HOOK_CLASS_
{

	protected static $gatewayDir = NULL;
	
	/**
	 * Get friendly URL data
	 *
	 * @param	bool	$verify		If TRUE, will check URL uses correct SEO title
	 * @return	array	Parameters
	 * @throws	\OutOfRangeException	Invalid URL
	 * @throws	\DomainException		URL does not have correct SEO title (exception message will contain correct URL)
	 */
	public function getFriendlyUrlData( $verify=false )
	{
		try
		{
			return call_user_func_array( 'parent::getFriendlyUrlData', func_get_args() );
		}
		catch( \OutOfRangeException $ex )
		{
			/* Pass to IP.Content to handle */
			$baseUrl = parse_url( \IPS\Settings::i()->base_url );
			if ( \IPS\Settings::i()->htaccess_mod_rewrite )
			{
				$query = ( isset( $this->data['path'] ) ? $this->data['path'] : '' );
			}
			else
			{
				if ( isset( $this->data['path'] ) and mb_strpos( $this->data['path'], 'index.php?' ) )
				{
					$query = ( isset( $this->data['query'] ) ? ltrim( $this->data['query'], '/' )  : '' );
				}		
				else
				{
					$query = '';
				}	
			}	
			
			$set = array();
		
			/* Need to remember the template we use for FURL verification */
			$usedTemplate	= NULL;

			/* Get furl definition */
			$furlDefinition = array('cms_page' => array(
				'friendly' => '{@path}',
				'real'     => 'app=cms&module=pages&controller=page'
			) );

			$query = preg_replace( '#^(' . preg_quote( rtrim( $baseUrl['path'], '/' ), '#' ) . ')/(index.php)?(?:(?:\?/|\?))?(.+?)?$#', '$3', $query );		
			
			$this->examineFurl( $furlDefinition, $query, $set, $usedTemplate );
			
			if ( count( $set ) )
			{
				return $set;
			}
			else
			{			
				throw new \OutOfRangeException();
			}
		}
	}

	/**
	 * Make friendly
	 *
	 * @param	    string|array	        $seoTemplate        	The key for making this a friendly URL; or a manual FURL definition
	 * @param       string|array            $seoTitles              The title(s) needed for the friendly URL
	 * @param       bool                    $forceHttps             Force HTTPS
	 * @return      parent
	 */
	public function makeFriendly( $seoTemplate, $seoTitles, $forceHttps=FALSE )
	{
		$called = $seoTemplate;
		if ( $seoTemplate === 'content_page_path' )
		{
			$seoTemplate = array(
				'friendly' => '{@path}',
				'real'     => 'app=cms&module=pages&controller=page'
			);
		}

		parent::makeFriendly( $seoTemplate, $seoTitles, $forceHttps );
		
		if ( $called === 'content_page_path' and \IPS\Settings::i()->cms_use_different_gateway )
		{
			if ( static::$gatewayDir === NULL )
			{
				static::$gatewayDir = preg_replace( '#^/?(.+?)/?$#', '\1', str_replace( \IPS\Settings::i()->cms_root_page_url, '', \IPS\Settings::i()->base_url ) );
			}
			
			$this->data['path'] = str_replace( '/' . static::$gatewayDir, '', $this->data['path'] );
			$this->url = str_replace( static::baseUrl(), \IPS\Settings::i()->cms_root_page_url, $this->url );
		}
	}
}