<?php
//error_log(__FILE__ . " - " . ($_SERVER["REDIRECT_URL"]??"/"));

use tcom\app\App;
use tcom\core\net\ServerRequestFactory;
use tcom\src\catalog\search\domain\SearchSpecConstants;
use tcom\src\common\common\application\ExecutionContextUpdater\ExecutionContextUpdater;

define ("MY_ABSPATH", dirname(__FILE__) . "/");
require_once (MY_ABSPATH . "app/config.php");
require_once (MY_ABSPATH . "app/min-utils.php");
require_once (MY_ABSPATH . "app/theme.php");

function sanitize_url($url) {
    return strtr($url, [
        '"' => '',
        "'" => '',
        "<" => '',
        ">" => '',
    ]);
}

function index_sanitize_array(&$array) : void {
    foreach ($array as &$value) {
        $value = strip_tags($value);
    }
}

index_sanitize_array($_REQUEST);
index_sanitize_array($_GET); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.
index_sanitize_array($_POST); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.


$_SERVER['REDIRECT_URL'] = sanitize_url($_SERVER['REDIRECT_URL'] ?? '');
$_SERVER['REQUEST_URI'] = sanitize_url($_SERVER['REQUEST_URI'] ?? '');
$_SERVER['PHP_SELF'] = sanitize_url($_SERVER['PHP_SELF'] ?? '');
	// XXX - dfraga: this looks useless, but if we don't do it, _REQUEST doesn't show the current value of some URL arguments.
	// It might be related with https://www.php.net/manual/en/ini.core.php#ini.variables-order 
	// The current config is "variables_order": "EGPCS". This should be right, but it's not working. So, this patch solves the problem.
$_REQUEST = array_merge($_REQUEST, $_GET);

// -----------------------------------------------------------------------------------------
// XXX - dfraga: global vars
// -----------------------------------------------------------------------------------------
// $theme representa el theme especificado por URL
$theme_by_url = THEME_STANDARD;
$resources_theme = FALSE;
$view         = "";
	// Método que realizará la búsqueda --> es un callable PHP (http://www.php.net/manual/en/language.types.callable.php)
$search_f     = "search_void";
$search_exemplar_f = FALSE;
$theme_render_f = "to_deprecate_theme_render";
$search_items = array();
$search_exemplar = FALSE;
$search_spec  = array();
$search_spec_exemplar = array();
$redirect_url = isset($_SERVER["REDIRECT_URL"])?$_SERVER["REDIRECT_URL"]:"";
$canonical_url_arr = get_url_as_array();

// Definimos la variable del idioma antes del get_url_encoded_params, por que ya la vamos a necesitar ah�
$lang_culture_name = init_lang();
$url_params   = get_url_encoded_params ();

// -----------------------------------------------------------------------------------------
// XXX - Variable Theme support
// -----------------------------------------------------------------------------------------
foreach ($valid_themes as $n) {
	if (strpos($redirect_url, "/" . $n . "/") === 0) {
        $theme_by_url = $n;
		$redirect_url = substr($redirect_url, 1 + strlen($n));
		array_shift($url_params);
		break;
	}
}

if ($_REQUEST["render_theme"] ?? FALSE) {
    // $render_theme representa el theme especificado por argumento o por configuracion
    $render_theme = $_REQUEST["render_theme"];
}
else {
    $render_theme = $theme_by_url == THEME_STANDARD ? THEME_DEFAULT_THEME : $theme_by_url;
}
// $theme esta deprecado. No deberia usarse mas alla de esta linea. Lo ideal seria eliminarlo pero la gran cantidad de uso en funciones en el resto del codigo impide su eliminacion.
$theme = $render_theme;

User::getLoggedUser();

TThemeFactory::loadThemes();

to_deprecate_theme_load ($render_theme);

	// XXX - dfraga: cargamos primero el theme ya que puede condicionar la carga de los includes.
require_once(MY_ABSPATH . "includes.php");
//var_dump_pre($url_params,$redirect_url); //exit;
//var_dump_pre($_REQUEST,$redirect_url); exit;

sanitize_search_spec($_REQUEST);
sanitize_search_spec($_GET); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.
sanitize_search_spec($_POST); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.

//    ¡¡IMPORTANTE!!
// Inicialización de la sesión de usuario: calculo de UTMs, destination page, etc
// Este código deberíamos hacerlo en todos los puntos de entrada a Taquilla.
// Lo ideal es que todos implementen un ControllerInterface y que incluyan el UserSessionMiddleware
$requestFactory = App::get(ServerRequestFactory::class);
$executionContextUpdater = App::get(ExecutionContextUpdater::class);
$request = $requestFactory->fromGlobals();
$executionContextUpdater->update($request);

//  -----------------------------------------------------------------------------------------
// XXX - Variable Language support
// -----------------------------------------------------------------------------------------
//var_dump_pre($active_langs);
//var_dump_pre($redirect_url);
//var_dump_pre($url_params,__METHOD__);

$allow_rewrite_lang = $_REQUEST[SEARCH_TRANSLATE_URL] ?? false;

// Sólo permitimos la "redirección" de idioma si nos piden la URL canónica
if (!in_array($url_params[1], array_keys($langCodes))) { 
	$rewrite_lang = $_REQUEST[SEARCH_LANGUAGE] ?? false;

	if ($allow_rewrite_lang && in_array($rewrite_lang, array_keys($langCodes))) {
		$new_url = i18n_get_url($redirect_url, $rewrite_lang);

		// Sobre-escribimos las variables globales redirect_url y url_params para simular que estamos gestionando la URL traducida.
		setLocalization($rewrite_lang);
		$redirect_url = str_replace('https://'.T10_APP_URL, '', $new_url);
		$url_params = get_url_encoded_params($redirect_url);
	}
}

$ref_langs = $allow_rewrite_lang ? array_keys($langCodes) : $active_langs ?? [];
//var_dump_pre(array_keys($langCodes));
foreach ($ref_langs as $url_lang) {
        if (strpos($redirect_url, '/' . $url_lang . '/') === 0) {
                $lang_culture_name = $url_lang;
                if ($lang_culture_name == DEFAULT_LANG) { utils_permanent_redirection ('/' . $url_lang . '/', '/'); }
                setLocalization($lang_culture_name);
                $redirect_url = substr($redirect_url, 1 + strlen($url_lang));
                array_shift($url_params);
                break;
        }
}
//var_dump_pre($lang_culture_name, __METHOD__."-LANG:".$lang);
//error_log(__FILE__ . " lang '" . $lang_culture_name . "'");
// -----------------------------------------------------------------------------------------


// -----------------------------------------------------------------------------------------
// Set currency and his cookie

if (isset($_GET[SEARCH_CURRENCY])) { 
  //var_dump_pre($_GET[SEARCH_CURRENCY], "Currency");
  mycookie_set(SEARCH_CURRENCY,$_GET[SEARCH_CURRENCY]); 
  setSelectedCurrency($_GET[SEARCH_CURRENCY]);
}
else if(mycookie_getc2(SEARCH_CURRENCY, $mycookie) != FALSE)
{
// Por ahora no vamos a fijarla en la cookie porque es innecesario en este punto, podemos trabajar con la divisa por defecto sin problema hasta que el usuario decida cambiarla expl�citamente.
  setSelectedCurrency($mycookie, $set_cookie = FALSE);
}

// -----------------------------------------
// Argument Shorcuts
// -----------------------------------------

	if (isset($_REQUEST[SEARCH_TYPE_SUBTYPE])) { search_type_shortcut($_REQUEST[SEARCH_TYPE_SUBTYPE], $_REQUEST); }

	if (isset($_REQUEST[SEARCH_DATE])) { search_date_shortcut($_REQUEST[SEARCH_DATE], $_REQUEST); }

	if (isset($_REQUEST[SEARCH_NUM])) { search_num_shortcut($_REQUEST[SEARCH_NUM], $_REQUEST); }

	if (isset($_REQUEST[SEARCH_VENUE_NAME])) { search_place_name_shortcut ($_REQUEST[SEARCH_VENUE_NAME], $_REQUEST); }

	if (isset($_REQUEST[SEARCH_SKIP_ENTITY_MENU])) { $_REQUEST[SEARCH_NUM] = SEARCH_NUM_UNLIMITED; }

if (isset($_REQUEST[SearchSpecConstants::SEARCH_ORDER_CITY_NAME])) {
    $_REQUEST[SearchSpecConstants::SEARCH_NUM] = SearchSpecConstants::SEARCH_NUM_UNLIMITED;
}

	// ---------------------------------
	// SEARCH_GO_CITY
// XXX - dfraga: revisar la coherencia de redirect_url!!!
if (isset($_REQUEST[SEARCH_GO_CITY])) {
        if ($redirect_url == "") {
                $redirect_url = "/"; // . THEME_VIEW_MAIN . "/-/-/";
        }
	$search_field = SEARCH_CITY;
	if ($_REQUEST[SEARCH_GO_CITY] != "1") { $search_field = SEARCH_GO_CITY; }
	$sep = "";
	if ($redirect_url[strlen($redirect_url)-1] != "/") { $sep = "/"; }
	if (($_REQUEST[$search_field] != "") &&
	    ($_REQUEST[$search_field] != SEARCH_OPTION_NOT_INIT) &&
	    (($city_name_url = City::get_city_url_from_city_name ($_REQUEST[$search_field])) != FALSE)) {
		$base_url = "http://" . $_SERVER['HTTP_HOST'] . $redirect_url;
		if (strpos ($base_url, $sep.$city_name_url) === FALSE) { 
		       	$new_url = "http://" . $_SERVER['HTTP_HOST'] . $redirect_url . $sep . lang_get_url_sufix() . $city_name_url;
	        	header ("Location: " . $new_url);
		        exit;
		}
	}
}

if (isset($_REQUEST[SEARCH_UNSET_CITY])) {
        if ($redirect_url == "") { $redirect_url = "/"; }
        if (($_REQUEST[SEARCH_UNSET_CITY] != "") &&
            ($_REQUEST[SEARCH_UNSET_CITY] != SEARCH_OPTION_NOT_INIT) &&
            (($city_name_url = City::get_city_url_from_city_name (util_prettify($_REQUEST[SEARCH_UNSET_CITY]))) != FALSE)) {

                if (getActualLangCultureName() == DEFAULT_LANG) {
                  $new_url = "https://" . $_SERVER['HTTP_HOST'] . str_replace("/" . $city_name_url, "", $redirect_url);
                } else {
                  $new_url = "https://" . $_SERVER['HTTP_HOST'] . "/" . getActualLangCultureName() . str_replace("/" . $city_name_url, "", $redirect_url);
                }

		$query_args = search_get_spec_from_getargs ($_SERVER["QUERY_STRING"]);
		foreach ($query_args as $k => &$v) { if ($k == SEARCH_UNSET_CITY) {unset($query_args[$k]);} }
		$new_query = search_get_url_args ($query_args);

		if ($new_query != "") { $new_url .= '?' . $new_query; }

                header ("Location: " . $new_url);
                exit;
        }
}



// -----------------------------------------------------------------------------------------------
// XXX - 'tickets/events/calendar/images/map' { venue | city | artist/entity }
// -----------------------------------------------------------------------------------------------
if (($url_params[1] == SEARCH_METHOD_TICKETS) || 
    ($url_params[1] == SEARCH_METHOD_EVENTS) || 
    ($url_params[1] == SEARCH_METHOD_OFFERS) || 
    ($url_params[1] == SEARCH_METHOD_IMAGES) || 
    ($url_params[1] == SEARCH_METHOD_MICROSITES) || 
    ($url_params[1] == SEARCH_METHOD_PLACES) || 
    ($url_params[1] == SEARCH_METHOD_DAYS_EXT) || 
    ($url_params[1] == SEARCH_METHOD_DAYS)) {
  $search_spec = $_REQUEST;
  $search_spec[SEARCH_METHOD] = $url_params[1];

  // View setup
  $args_offset = 0;
  $search_f = DEFAULT_SEARCH_ENGINE;
  $search_exemplar_f = DEFAULT_SEARCH_EXEMPLAR;

  $search_spec[SEARCH_NULLPRICE_DISABLED]  = TRUE;
  if (($search_spec[SEARCH_METHOD] == SEARCH_METHOD_TICKETS) && ($url_params[2] == "event")) {
	//var_dump_pre($url_params);
	 $view  = THEME_VIEW_TICKETS; /* single event view */
	
         $parent_url = Event::get_main_url ($url_params[3]);
         if ($url_params[3] != $parent_url) { utils_permanent_redirection ("/".$url_params[3], "/".$parent_url); }

	 search_spec_set_event ($url_params[3], $search_spec);
	 unset($search_spec[SEARCH_NULLPRICE_DISABLED]);
  } 
  else if (($search_spec[SEARCH_METHOD] == SEARCH_METHOD_TICKETS) && ($url_params[2] == "offer")) {
	 $search_spec[SEARCH_METHOD] = SEARCH_METHOD_OFFER;
	 $view  = THEME_VIEW_OFFER; /* single event view */
	 search_spec_set_offer ($url_params[3], $search_spec);
	 unset($search_spec[SEARCH_NULLPRICE_DISABLED]);
  } 
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_EVENTS) {
	$view = THEME_VIEW_EVENTS;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_OFFERS) {
	$view = THEME_VIEW_OFFERS;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_DAYS) {
	$view = THEME_VIEW_DAYS;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_DAYS_EXT) {
	$view = THEME_VIEW_DAYS_EXT;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_PLACES) {
	$view = THEME_VIEW_PLACES;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_MICROSITES) {
	$view = THEME_VIEW_MICROSITE;
  }
  else if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_IMAGES) {
	$view = THEME_VIEW_IMAGES;
  }

  // ...tickets + venue | city | artist --> no deberia aparecer...
  if (($search_spec[SEARCH_METHOD] != SEARCH_METHOD_TICKETS) && ($search_spec[SEARCH_METHOD] != SEARCH_METHOD_OFFER)) {
	search_set_search_spec_by_params($url_params, $search_spec, $search_spec_exemplar);
  }

/*
	// XXX - dfraga: not supported anymore
  // Date spec
  if (isset($url_params[4+$args_offset]) && isset($url_params[5+$args_offset])) {
                // .../yyyy/mm
	search_spec_set_date ($url_params[4+$args_offset], $url_params[5+$args_offset], $search_spec);
  } else if (isset($url_params[4+$args_offset]) && !isset($url_params[5+$args_offset])) {
                // .../old
	search_spec_set_date ($url_params[4+$args_offset], "", $search_spec);
        unset($search_spec[SEARCH_NULLPRICE_DISABLED]);
  }
*/

  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_MICROSITES) {
	$extra_url = array_slice($url_params, 4);
  	$search_spec[SEARCH_MICROSITE_URL]  = implode('/', $extra_url);
  }

  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_IMAGES) {
	if (isset($url_params[4])) {
		$search_spec[SEARCH_IMAGE_SPEC] = $url_params[4];	
	}
        // XXX - por defecto se muestra la imagen original
        if (! isset($search_spec[SEARCH_IMAGE_SPEC])) {
		$searc_spec[SEARCH_IMAGE_SPEC] = "";
	}
	$search_f = "search_get_image_items";
  }


  // XXX - dfraga: el que primero se obtenga el exemplar y luego se haga el
  // update_search_spec, hace que este �ltimo no pueda modificar el c�mo
  // se consigue el exemplar. Esto es una limitaci�n cuando no queremos un
  // exemplar "por defecto".
  // XXX - habr�a que valorar hasta que punto es importante mantener este
  // orden. Lo cierto es que el update_search_spec normalmente est� condicionado
  // por caracter�sticas del exemplar.
  // XXX - habr�a que ver si para utilizar dichas caracter�sticas es necesario
  // que exista la instancia del exemplar o si por el contrario son f�cilmente
  // extraibles del search_spec. En tal caso podr�amos cambiar el orden de
  // ejecuci�n sin m�s que expresar todas las condiciones de los update_search_spec
  // en base al search_spec y no en base al exemplar.

  // XXX - getting exemplar IMPORTANT => this process can modify search_spec
  //     - now (since 2016-06-13), only these views pre-fetch the exemplar
  if ($search_exemplar_f && (function_exists($search_exemplar_f))) {
	$search_exemplar = $search_exemplar_f ($search_spec);
  }
//var_dump_pre($search_exemplar,__METHOD__ . " EXEMPLAR");

	// Redirection if no compliant URLs found based on exemplar data
  if ($url_params[2] == "venue") {
	if ($url_params[4] != $search_exemplar->city_url) {
		utils_permanent_redirection("/".$url_params[4], "/".$search_exemplar->city_url);
	}
  }


  // XXX - theme modifiers
  to_deprecate_theme_update_search_spec ($search_spec);

  // XXX - search results 
  //$search_items = $search_f ($search_spec);
  $search_items = search_f_execute ($search_f, $search_spec);
}

else if ($url_params[1] == THEME_VIEW_LIST) {
  $search_spec = $_REQUEST;
  $search_spec[ARCHIVE_TYPE]   = $url_params[2];
  $search_spec[ARCHIVE_VALUE]  = $url_params[3] ?? '';
  $search_spec[ARCHIVE_XVALUE] = $url_params[4] ?? '';

  $view  = THEME_VIEW_LIST;
  to_deprecate_theme_update_search_spec ($search_spec);

  $search_items = search_get_v2_list_items ($search_spec);
}

else if (($url_params[1] == THEME_VIEW_HOME) || ($url_params[1] == THEME_VIEW_MAIN) || ($url_params[1] == THEME_VIEW_MAIN_OFFERS)) {
	$search_spec = $_REQUEST;

	$view = $url_params[1];
	if ($view == THEME_VIEW_MAIN_OFFERS) {
		$search_spec[SEARCH_METHOD] = SEARCH_METHOD_OFFERS;
	}
	$search_f = "search_get_v2_main_items";

        search_set_search_spec_by_params($url_params, $search_spec, $search_spec_exemplar);

	// XXX - theme modifiers
	to_deprecate_theme_update_search_spec ($search_spec);

  	//$search_items = $search_f ($search_spec);
  	$search_items = search_f_execute ($search_f, $search_spec);
}
else if ($url_params[1] == SEARCH_METHOD_PRIVATE) {
	$view = $url_params[2];

	// Actualizamos el search_spec como en una vista convencional
	to_deprecate_theme_update_search_spec ($search_spec);

	// XXX - dfraga: si hay alguna petici�n de creaci�n/modificaci�n la procesamos previamente a la b�squeda
        $search_update_f = "search_private_update_".$view;
        if (function_exists($search_update_f)) { $search_update_f ($search_items); }

	$search_f = "search_private_".$view;
	if (function_exists($search_f)) {
		//$search_items = $search_f ($search_spec);
  		$search_items = search_f_execute ($search_f, $search_spec);
	}
}

// XXX - dfraga: THEME_VIEW_ALERTS view is deprecated
else if ($url_params[1] == THEME_VIEW_ALERTS) {
    taquilla10_error404("'" . $url_params[1] . "' view is deprecated");
  //$view = THEME_VIEW_ALERTS;
  //$search_items = [ 'hack' ]; // Hack to avoid 404
}


// -----------------------------------------------------------------------------------------------
// XXX - Search Tickets/events views: "search", "search/events"
// -----------------------------------------------------------------------------------------------
else if ($url_params[1] == THEME_VIEW_SEARCH) {

  // XXX - dfraga: esto habr�a que acabar integr�ndolo en el bloque del /events/ ya que devuelve lo mismo
  $view  = THEME_VIEW_SEARCH;
  $search_f = DEFAULT_SEARCH_ENGINE;

  $search_spec = $_REQUEST;
  $search_spec[SEARCH_METHOD] = search_get_method_from_path($url_params[2]);
  $search_spec[SEARCH_NULLPRICE_DISABLED]  = TRUE;
  if (! isset($search_spec[SEARCH_ORDER])) { $search_spec[SEARCH_ORDER]  = SEARCH_ORDER_POPULARITY; }

  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_ENTITIES) {
	$search_spec[SEARCH_ENTITY_DETAILS] = 1;
  }


  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_PLACES) {
        $view = THEME_VIEW_PLACES;
  	if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_PLACES) {

	// XXX - dfraga:
	//		Si est� fijado DST y no GEO, habr�a que utilizar alg�n tipo de criterio como intentar obtener "mi posci�n".
	// 		Habr�a que ver d�nde ponemos esta l�gica.
	// XXX - dfraga: TODO - habria que utilizar alg�n sistema de geolocalizaci�n basado en la IP en vez de utilizar las _DEFAULT
	        if (! ( (isset($search_spec[SEARCH_GEO_LAT])) &&
	                (isset($search_spec[SEARCH_GEO_LNG])) &&
	                (isset($search_spec[SEARCH_GEO_DST_M]))
	                )) {
	                search_spec_set_geo (SEARCH_GEO_LAT_DEFAULT, SEARCH_GEO_LNG_DEFAULT, SEARCH_GEO_DST_M_DEFAULT, $search_spec);
			if (! isset($search_spec[SEARCH_NUM])) {
				$search_spec[SEARCH_NUM] = SEARCH_NUM_GEO_DEFAULT;
			}
	        }
	}
  }


  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_RESTAURANTS) {
	$view = THEME_VIEW_PLACES;
  }

  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_HOTELS) {
	$view = THEME_VIEW_PLACES;
  }

  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_DAYS) {
	$view = THEME_VIEW_DAYS;
  }
  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_DAYS_EXT) {
	$view = THEME_VIEW_DAYS_EXT;
  }


  // Soporte para b�squedas custom <--> casi equivalente a /events/custom/ pero con matches
  if ($url_params[2] == THEME_VIEW_SEARCH_CUSTOM) {
	$search_spec[SEARCH_METHOD] = SEARCH_METHOD_EVENTS;
        $custom_path = $url_params[3];
        if ($search_spec[T10_ID] != "") {
                $custom_path = $search_spec[T10_ID];
        }
        search_spec_set_custom ($custom_path, $search_spec);
  }

  // XXX - theme modifiers
  to_deprecate_theme_update_search_spec ($search_spec);

  // XXX - search results
  $search_items = array();

  $matches_spec = $search_spec;
// XXX - dfraga: esto podria ser interesante en algunos casos, pero para el uso que le damos al live-search, es mejor que 
//  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_ENTITIES) { $matches_spec[SEARCH_ONLY_EXACT_ENTITIES] = 1; }
//  if ($search_spec[SEARCH_METHOD] == SEARCH_METHOD_PLACES) { $matches_spec[SEARCH_ONLY_EXACT_PLACES] = 1; }
  $matches_spec[SEARCH_NUM] = SEARCH_NUM_DEFAULT; 
  $matches = search_get_search_exact_matches ($matches_spec);
  if ((!isset($search_spec[SEARCH_NO_REDIRECT_MATCH])) && is_array($matches)) {
	foreach ($matches as $m) {
//error_log(__FILE__ . " match-name'" . $m["name"] . "' vs. search-name: '" . $search_spec[SEARCH_FIELD] . "'");
		if (strcasecmp ($m["name"], $search_spec[SEARCH_FIELD]) == 0) {
		//if (strcasecmp (StringHelper::encodeUTF8($m["name"]), $search_spec[SEARCH_FIELD]) == 0) {
			$url_path = 'events/' . $m['type'] . '/' . $m['name_url'];
			if ($m['type'] == "entity") {
				$url_path = theme_url_entity_events ($m['name_url']);
			} else if ($m['type'] == "event") {
				$url_path = theme_url_tickets ($m['name_url']);
			} else if ($m['type'] == "venue") {
				$url_path = theme_url_venue_events ($m['name_url']);
			}

			$new_url = "https://" . $_SERVER['HTTP_HOST'] . '/' . $url_path;
			header ("Location: " . $new_url);
			exit;
		}
	}
  }
  //$search_items = $search_f ($search_spec);
  $search_items = search_f_execute ($search_f, $search_spec);
  $search_items["matches"] = $matches;
}
// La URL no tiene la raiz esperada /xxx/...
else if ($url_params[1] != "") {
    taquilla10_error404("'" . $url_params[1] . "' is not found");
}

// -----------------------------------------------------------------------------------------------
// XXX - Render results 
// -----------------------------------------------------------------------------------------------
//var_dump_pre ($view,"View");var_dump_pre ($theme,"Output");var_dump_pre ($search_spec,"search_spec"); var_dump_pre($search_items, "search_items");
//exit;
if (($_SERVER['REQUEST_URI'] != "/") && (($view != THEME_VIEW_MAIN) && ($view != THEME_VIEW_HOME))&&
	(($view == "") || ($search_items && (count($search_items) == 0) && ($view != THEME_VIEW_SEARCH)) ) &&
	($url_params[1] != SEARCH_METHOD_PRIVATE)) {
	taquilla10_error404("'" . $_SERVER['REQUEST_URI'] . "' not found");
}

search_filter_fields ($search_spec, $search_items);

sanitize_search_spec($search_spec);
sanitize_search_spec($_REQUEST);
sanitize_search_spec($_GET); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.
sanitize_search_spec($_POST); // Esto es necesario ya que hay muchos acceso a _GET en tcom-2.0 en vez de a _REQUEST. Habría que sustituirlos todos.

to_deprecate_theme_update_search_items ($search_items);

$theme_render_f($view);
