<?php

include_once(dirname(__FILE__).'/Database.php');
include_once(dirname(__FILE__).'/HTML/XHTML.php');
include_once(dirname(__FILE__).'/HTML/HTML.php');
include_once(dirname(__FILE__).'/HTTP.php');
include_once(dirname(__FILE__).'/Types/Type.php');
include_once(dirname(__FILE__).'/Output.php');

$MonthNames = array('', 'Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen', 'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec');

$PrefixMultipliers = array
(
  'Binary' => array
  (
    'BaseIndex' => 0,
    'Definition' => array
    (
      array('', '', pow(2, 0)),
      array('Ki', 'kibi', pow(2, 10)),
      array('Mi', 'mebi', pow(2, 20)),
      array('Gi', 'gibi', pow(2, 30)),
      array('Ti', 'tebi', pow(2, 40)),
      array('Pi', 'pebi', pow(2, 50)),
      array('Ei', 'exbi', pow(2, 60)),
      array('Zi', 'zebi', pow(2, 70)),
      array('Yi', 'yobi', pow(2, 80)),
    ),
  ),
  'Decimal' => array
  (
    'BaseIndex' => 8,
    'Definition' => array
    (
      array('y', 'yocto', pow(10, -24)),
      array('z', 'zepto', pow(10, -21)),
      array('a', 'atto', pow(10, -18)),
      array('f', 'femto', pow(10, -15)),
      array('p', 'piko', pow(10, -12)),
      array('n', 'nano', pow(10, -9)),
      array('u', 'mikro', pow(10, -6)),
      array('m', 'mili', pow(10, -3)),
      array('', '', pow(10, 0)),
      array('k', 'kilo', pow(10, 3)),
      array('M', 'mega', pow(10, 6)),
      array('G', 'giga', pow(10, 9)),
      array('T', 'tera', pow(10, 12)),
      array('P', 'peta', pow(10, 15)),
      array('E', 'exa', pow(10, 18)),
      array('Z', 'zetta', pow(10, 21)),
      array('Y', 'yotta', pow(10, 24)),
    ),
  ),
  'Time' => array
  (
    'BaseIndex' => 8,
    'Definition' => array
    (
      array('ys', 'yoctosekunda', pow(10, -24)),
      array('zs', 'zeptosekunda', pow(10, -21)),
      array('as', 'attosekunda', pow(10, -18)),
      array('fs', 'femtosekunda', pow(10, -15)),
      array('ps', 'pikosekunda', pow(10, -12)),
      array('ns', 'nanosekunda', pow(10, -9)),
      array('us', 'mikrosekunda', pow(10, -6)),
      array('ms', 'milisekunda', pow(10, -3)),
      array('s', 'sekund', 1),
      array('minut', 'minuta', 60),
      array('hodin', 'hodina', 60 * 60) ,
      array('dnů', 'den', 24 * 60 * 60),
      array('týdnů', 'týden', 7 * 24 * 60 * 60),
      array('měsíců', 'měsíc', 30 * 24 * 60 * 60),
      array('roků', 'rok', 364 * 24 * 60 * 60),
      array('desitiletí', 'desetiletí', 10 * 364 * 24 * 60 * 60),
      array('staletí', 'staletí', 100 * 364 * 24 * 60 * 60),
      array('tisíciletí', 'tisiciletí', 10000 * 364 * 24 * 60 * 60),
    ),
  ),
);

function ErrorHandler()
{
}
  
class System
{
  var $Model = array(); 
  var $View = array(); 
  var $Controller = array(); 
  var $Config;
  var $Database;
  var $HTTP;
  var $HTML;
  var $Type;
  var $TimeStart;
  var $Translation;
  var $Output;
  var $DefaultModule;
  var $Modules = array();

  function __construct()
  {
    global $ShowPHPError;

    $TimeStart = $this->GetMicrotime();
    
    // Change base dir to index. Helpfull if script is executed from command line with related path.
    chdir(dirname(__FILE__));

    $this->Output = new Output($this);

    $FileName = dirname(__FILE__).'/Config/Config.php';
    if(file_exists($FileName)) include($FileName);
      else {
        $this->Output->Show($this->Output->SystemMessage('Configuration file "'.$FileName.'" not found.'));
        exit;
      }
    $this->Config = $Config;
    $ShowPHPError = $this->Config['Web']['ShowPHPError'];

    $FileName = dirname(__FILE__).'/../Application/Localization/'.$Config['Web']['Locale'].'.php';
    if(file_exists($FileName)) include($FileName);
      else {
        $this->Output->Show($this->Output->SystemMessage('Translation file "'.$FileName.'" not found.'));
        exit;
      }
    $this->Translation = $Translation;

    if(isset($_SERVER['REMOTE_ADDR'])) session_start();
    $this->Database = new Database($this->Config['Database']['Host'],
    $this->Config['Database']['User'], $this->Config['Database']['Password'],
    $this->Config['Database']['Database']);
    $this->Database->ShowSQLQuery = $this->Config['Web']['ShowSQLQuery'];
    $this->Database->ShowSQLError = $this->Config['Web']['ShowSQLError'];
    $this->Database->Prefix = $this->Config['Database']['Prefix'];
    $this->Database->charset($this->Config['Database']['Charset']);
     
    $this->HTTP = new HTTP();
    $this->HTML = new HTML($this);
    $this->Type = new Type($this);
  }

  function Run()
  {
    $this->TimeStart = $this->GetMicrotime();
    
    // SQL injection hack protection
    foreach($_POST as $Index => $Item) $_POST[$Index] = addslashes($Item);
    foreach($_GET as $Index => $Item) $_GET[$Index] = addslashes($Item);

    if(array_key_exists('M', $_GET)) $Module = $_GET['M'];
      else $Module = $this->DefaultModule;

    $ControllerName = $Module.'Controller';
    $FileName = dirname(__FILE__).'/../Application/Controller/'.$Module.'.php';
    if(!file_exists($FileName))
    {
      $this->Output->Show($this->Output->SystemMessage('Soubor '.$FileName.' nenalezen.'));
      exit;
    } else include($FileName);
    if(class_exists($ControllerName))
    {
      $Controller = new $ControllerName($this);
      $this->Output->Show($Controller->Process());
    } else $this->Output->Show($this->Output->SystemMessage('Modul "'.$ControllerName.'" nenalezen.'));
  }

  function ModulePresent($Name)
  {
    return(array_key_exists($Name, $this->Modules));
  }

  function AddModule($Name)
  {
    $this->Modules[$Name] = new $Name($this);
  }
  
  function HumanDate($Time)
  {
    return(date('j.n.Y', $Time));
  }

  function TruncateDigits($Value, $Digits = 4)
  {
    for($II = 2; $II > -6; $II--)
    {
      if($Value >= pow(10, $II))
      {
        if($Digits < ($II + 1)) $RealDigits = $II + 1; else $RealDigits = $Digits;
        $Value = round($Value / pow(10, $II - $RealDigits + 1)) * pow(10, $II - $RealDigits + 1);
        break;
      }
    }
    return($Value);
  }

  function AddPrefixMultipliers($Value, $Unit, $Digits = 4, $PrefixType = 'Decimal')
  {
    global $PrefixMultipliers;

    $Negative = ($Value < 0);
    $Value = abs($Value);
    if(($Unit == '') and ($PrefixType != 'Time'))
      return($this->TruncateDigits($Value, $Digits));

    $I = $PrefixMultipliers[$PrefixType]['BaseIndex'];
    if($Value == 0) return($Value.' '.$PrefixMultipliers[$PrefixType]['Definition'][$I][0].$Unit);
     
    if($Value > 1) 
    {
      while((($I + 1) <= count($PrefixMultipliers[$PrefixType]['Definition'])) and (($Value / $PrefixMultipliers[$PrefixType]['Definition'][$I + 1][2]) > 1))
        $I = $I + 1;
    } else 
    if($Value < 1)
    {
      while((($I - 1) >= 0) and (($Value / $PrefixMultipliers[$PrefixType]['Definition'][$I][2]) < 1))
        $I = $I - 1;
    }
    $Value = $Value / $PrefixMultipliers[$PrefixType]['Definition'][$I][2];
    
    // Truncate digits count
    $Value = $this->TruncateDigits($Value, $Digits);
    if($Negative) $Value = -$Value;
    return($Value.' '.$PrefixMultipliers[$PrefixType]['Definition'][$I][0].$Unit);
  }
  
  function NetworkPortState($Address, $Port, $Timeout = 1)
  {
    set_error_handler('ErrorHandler');
    $Socket = @fsockopen($Address, $Port, $ERROR_NO, $ERROR_STR, (float)$Timeout);
    if($Socket)
    {
      fclose($Socket);
      $Result = true;
    } else $Result = false;
    restore_error_handler();
    return($Result);
  }

  function Translate($Text)
  {
    if(array_key_exists($Text, $this->Translation)) return($this->Translation[$Text]);
      else return('#'.$Text);
  }

  function MakeLink($Module, $Action, $Parameters = array())
  {
    $Parameters = $this->HTTP->SetQueryStringArray($Parameters);
    if($Parameters != '') $Parameters = '&amp;'.$Parameters;
    return('?M='.$Module.'&amp;A='.$Action.$Parameters);
  }

  function GetRemoteAddress()
  {
    if(array_key_exists('HTTP_X_FORWARDED_FOR',$_SERVER)) $IP = $_SERVER['HTTP_X_FORWARDED_FOR'] ;
    else if(array_key_exists('REMOTE_ADDR', $_SERVER)) $IP = $_SERVER['REMOTE_ADDR'];
    else $IP = '0.0.0.0';
    return($IP);
  }

  function GetMicrotime()
  {
    list($Usec, $Sec) = explode(' ', microtime());
    return((float)$Usec + (float)$Sec);
  }

  function RemoveDiacritic($Text)
  {
    return(str_replace(
      array('á', 'č', 'ď', 'é', 'ě', 'í', 'ľ', 'ň', 'ó', 'ř', 'š', 'ť', 'ú', 'ů', 'ý', 'ž', 'Á', 'Č', 'Ď', 'É', 'Ě', 'Í', 'Ľ', 'Ň', 'Ó', 'Ř', 'Š', 'Ť', 'Ú', 'Ů', 'Ý', 'Ž'),
      array('a', 'c', 'd', 'e', 'e', 'i', 'l', 'n', 'o', 'r', 's', 't', 'u', 'u', 'y', 'z', 'A', 'C', 'D', 'E', 'E', 'I', 'L', 'N', 'O', 'R', 'S', 'T', 'U', 'U', 'Y', 'Z'),
      $Text));
  }
}

?>
