<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php
  // Permalinks Dispatcher - This script loads the appropriate viewer based on the permalink

  // load viewer library
  $libraryPath = 'lib/viewer_functions.php';
  $dirsToCheck = array('../','../../','../../../','../../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  // get redirect url
  $REDIRECT_URL = _permalink_getRedirectUrl(); 

  // error checking
  if (!@$GLOBALS['PERMALINKS_PLUGIN']) { dieAsCaller("Please activate the Permalinks plugin!"); }
  if (!$REDIRECT_URL) {
    print "Dispatcher: No mod_rewrite url detected!<br/>\n";
    // debugging - uncomment the next line
    //print "<xmp>\$_SERVER = ".print_r($_SERVER, true)."\n\$_REQUEST = ".print_r($_REQUEST, true)."\n</xmp>";
    exit;
  }

  // get permalink
  $permalinkText   = preg_replace("!^/|/$!", '', $REDIRECT_URL);
  $permalinkRecord = mysql_get('_permalinks', null, array('permalink' => $permalinkText));

  // if old permalink, redirect to latest one
  if ($permalinkRecord && $permalinkRecord['old']) {
    $whereEtc   = mysql_escapef("`tableName` = ? AND `recordNum` = ? AND `old` = '0'", $permalinkRecord['tableName'], $permalinkRecord['recordNum']);
    $latestLink = mysql_get('_permalinks', null, $whereEtc);
    header("Location: /{$latestLink['permalink']}/", true, 301); // 301 Moved Permanently
    exit;
  }

  // 404 Not Found - show error page if no permalink record found
  if (!$permalinkRecord) {
    header("HTTP/1.0 404 Not Found");
     
    ### DEBUGGING CODE - show debug output when a CMS Admin is logged in and requests /non-existant-url?this=that
    $debugOutput  = false; // set this to true to force showing debug info, or for specific ip: ($_SERVER['REMOTE_ADDR'] == '0.0.0.0');
    foreach ($_SERVER as $key => $value) {
      if (!is_array($value) && preg_match("/non-existant-url/", $value)) {
        $CMS_USER     = getCurrentUserFromCMS();
        if ($CMS_USER['isAdmin']) { $debugOutput = true; }
        break;
      }
    }
    if ($debugOutput) {
      print "<h1>Debug Output</h1>\n";
      print "<b>You must be logged in as admin user in the CMS to see this.</b><br/>";
      $debugInfo = array();
      $debugInfo['date']                 = date('Y-m-d H:i:s');
      $debugInfo['HTTP_HOST']            = @$_SERVER['HTTP_HOST'];
      $debugInfo['SERVER_SOFTWARE']      = @$_SERVER['SERVER_SOFTWARE'];
      $debugInfo['PHP_VERSION']          = phpversion();
      $debugInfo['PHP_SAPI']             = PHP_SAPI;
      $debugInfo['PHP_UNAME']            = @php_uname();
      $debugInfo['_NOTES_']              = '';
      $debugInfo['---------']            = '---------';
      
      ksort($_SERVER);
      foreach ($_SERVER as $key => $value) {
        $keyMatches = preg_match("/ORIG|PATH_INFO|QUERY|REDIRECT|SCRIPT|URI|URL/i", $key);
        $valueMatches = !is_array($value) && preg_match("/non-existant-url|permalinks/", $value);
        if ($keyMatches || $valueMatches) { $debugInfo[$key] = $value; }
      }
      $debugInfo['--------']            = '--------';
      $debugInfo['_OUTPUT_ACTUAL_']     = $REDIRECT_URL;
      $debugInfo['_OUTPUT_EXPECTED_']   = '/non-existant-url';
      
      $outputCode = "\$server[] = " . var_export($debugInfo, true) . ';';
      $outputCode = preg_replace("/=>\s*array\s*/s", "=> array", $outputCode); // reformat PHP so arrays start on the same line as keys (easier to read)
      showme($outputCode);
      exit;
    }
    ### /END DEBUGGING CODE
    
    if (!is_file($GLOBALS['PERMALINKS']['404_not_found_filepath'])) {
      die("Couldn't find filepath for 404 page: '" .htmlencode($GLOBALS['PERMALINKS']['404_not_found_filepath']). "'!\n");
    }
    else {
      include $GLOBALS['PERMALINKS']['404_not_found_filepath'];
    }
    exit;
  }



  // get filepath to custom page or detail page viewer for permalink, eg: /www/e/example_com/htdocs/news_detail.php
  list($viewerAbsPath, $pathErrors) = _permalink_getAbsolutePath($permalinkRecord['tableName'], $permalinkRecord['customSourceUrl']);
  if ($pathErrors) { die( nl2br(htmlencode($pathErrors)) ); }

  // debug
  //showme($_SERVER);
  //_permalink_web_showDebugInfo($permalinkText, $permalinkRecord, $viewerFilepath); exit;

  // Fake QUERY_STRING and $_GET values so viewers can get record number and extra values
  foreach (array($permalinkRecord['tableName'], $permalinkRecord['customSourceUrl']) as $urlAndQuery) {
    @list(,$querystring) = explode('?', $urlAndQuery);
    parse_str($querystring, $namesToValues);
    foreach ($namesToValues as $name => $value) {
      $_GET[$name]              = $value;
      $_REQUEST[$name]          = $value;
      $_SERVER['QUERY_STRING'] .= "&$name=" . urlencode($value);
    }
  }
  if ($permalinkRecord['recordNum']) {  // fake num, so viewers can get the record num
    $_GET['num']              = $permalinkRecord['recordNum'];
    $_REQUEST['num']          = $permalinkRecord['recordNum'];
    $_SERVER['QUERY_STRING'] .= "&num=" . $permalinkRecord['recordNum'];
  }
  $_SERVER['QUERY_STRING'] = trim($_SERVER['QUERY_STRING'], '&'); // remove leading/trailing & (in case there was no query string before we started adding data)
  $_SERVER['SCRIPT_NAME'] = $REDIRECT_URL; // fake SCRIPT_NAME, so thisPageUrl and self-referencing code works

  // chdir to the dir of the included file so relative include paths work, eg: include("includes/header.php");
  chdir(dirname($viewerAbsPath));

  //$_GET['tableName'] = $permalinkRecord['tableName'];
  //$_SERVER['SCRIPT_NAME_ORIGINAL'] = $_SERVER['SCRIPT_NAME'];

  // debug
  //_permalink_web_showDebugInfo($permalinkText, $permalinkRecord, $viewerFilepath); exit;

  // include viewer
  $GLOBALS['PERMALINKS_HAS_REDIRECTED'] = true; 
  include $viewerAbsPath;
  exit;

//
function _permalink_web_showDebugInfo($permalinkText, $permalinkRecord, $viewerFilepath) {

  header("Content-type: text/plain");
  print "Permalinks Dispatcher: Debug mode\n";
  print "----------------------------------------------------------------------\n";

  print "\n\$permalinkText = " . print_r($permalinkText, true);
  print "\n\$viewerFilepath = " . print_r($viewerFilepath, true);
  print "\n\n\$permalinkRecord = " . print_r($permalinkRecord, true);
  print "\n\$_REQUEST = " . print_r($_REQUEST, true);

  // Show $_SERVER
  print "\n\$_SERVER = ";
  foreach ($_SERVER as $key => $value) {
    if (!preg_match("/REDIRECT|SCRIPT_NAME|QUERY/", $key)) { unset($_SERVER[$key]); }
  }
  print_r($_SERVER);
  exit;
}
?>