<?php
App::uses('Helper', 'View');
class AppHelper extends Helper {

	function beforeRender($viewFile) {
		$this->View = ClassRegistry::getObject('View');
	}

	function url($url = null, $full = false) {
		$languages = @join('|', array_keys(Configure::read('Config.Languages')));

		Timer::startLoop('AppHelper::url()'); {

			# String url
			if(is_string($url)) {

				# Special cases
				if(strpos($url, ':')) {

					# Link to another page
					if(preg_match('~^\s*page:(?P<id>\d+)\s*(?P<hash>#.*)?\s*$~', $url, $page)) {
						$base = CMS ? FRONT_BASE_URL : '';
						$url = $base . ClassRegistry::init('Page')->getPageLink($page['id']) . (!empty($page['hash']) ? $page['hash'] : '');

					# Referrer
					} elseif(preg_match('~^\s*referer:(?P<href>.+)?\s*$~', $url, $alt)) {
						$url = $this->_View->viewVars['referer'];
						$href = !empty($alt['href']) ? $alt['href'] : '/';
						if($url === '/') {
							$url = $href{0} == '^' ? array_slice($this->request->params['pass'], 0, 0-strlen($href)) : $href;
						}

					# Language switch
					} elseif(preg_match('~^\s*language:(?P<href>.+)?\s*$~', $url, $alt)) {
						$locale = $this->Session->read('Config.language');
						$languages = join('|', array_keys(Configure::read('Config.Languages')));
						$location = preg_replace("~^/{$languages}(/|:|$)~", '', $this->request->here);
						$url = "'/{$locale}:' . \$language['Language']['locale'] . '/{$location}'";
					}
				}

				# Prepend language
				if(is_string($url) && isset($url{0}) && $url{0} === '/' && !preg_match("~/{$languages}(/|:|$)~", $url) && !preg_match('~\.[a-zA-Z0-9]{2,4}$~', $url)) {
					$url = '/' . Configure::read('Config.language') . '/' . ltrim($url, '/');
				}

			# Array url
			} elseif(is_array($url)) {

				# Append language abbreviation #
				if(!isset($url['language'])) {
					$url = array('language' => Configure::read('Config.language')) + $url;
				}

				# Append prefix #
				if(!empty($this->params['ctrl']) && isset($url['controller']) && $url['controller'] == $this->params['controller']) {
					$url['ctrl'] = '/' . $this->params['ctrl'];
				}
			}

			$return = parent::url($url, $full);

		} Timer::endLoop('AppHelper::url()');

		return $return;
	}

}

