<?php
include(dirname(__FILE__)."/../etc/wn_common.php");
include("$ETC_DIR/db.php");

use Webnews\NewspaperDomain;

// Is there a specific url route for this call?
$uri =  $_SERVER['REQUEST_URI'];
$domain = $_SERVER['HTTP_HOST'];

$redir_domain = Routing::checkPermanentRedirect($domain);
if ($redir_domain && $domain != $redir_domain) {
  Routing::redirectWebnews('http://' . $redir_domain . $uri, 301, TRUE);
  exit;
}

// Strip mobile subdomain
if (strpos($domain, 'm.') === 0) {
  $domain = substr($domain, 2);
}

if (strpos($uri, '/m/') === 0 || $uri === '/m') {
  $uri = substr($uri, 2);
}

if ($MOBILE === 2 && $domain === $GENERAL_DOMAINNAME) {
  header('Location: http://m.' . $domain . $uri);
  exit;
}

$page = false;

$parts = explode("?",$uri);
if(is_array($parts) && TypeSafe::count($parts)>1){
  $paramstr = $parts[1];
  $params = explode("&",$paramstr);

  foreach($params as $param){
    $arr= explode("=",$param);
    if(is_array($arr) && TypeSafe::count($arr)>1 && $arr[0]=="page"){
      $page=$arr[1];
    }
  }
}


$redir = Routing::getDestination($domain, $uri);

if ($redir && is_array($redir)) {
  $urarr = explode("?",$uri);

  if($urarr) {
    $uri = rtrim($urarr[0],"/");
  }
 
  list($url, $httpstatus) = $redir;
  if($newer = Routing::getURI($domain,$url)){
    list($new_uri,$new_httpstatus) = $newer;
    if($new_uri !== $uri){
      Routing::redirectWebnews($WWW_URL.$new_uri, $new_httpstatus,TRUE);
    }
  }

  if(substr($url,0,3) == "htt"){
    Routing::redirectWebnews($url, $httpstatus,TRUE);
    exit();
  }

  $file = Routing::processDestination($url,$httpstatus);
  include($file);
}
