<?php

$ScriptTimeStart = GetMicrotime();

// SQL injection hack protection
foreach($_POST as $Index => $Item) $_POST[$Index] = addslashes($Item);
foreach($_GET as $Index => $Item) $_GET[$Index] = addslashes($Item);

if(isset($_SERVER['REMOTE_ADDR'])) session_start();
include('config.php');
include('database.php');
include('error.php');
include('code.php');
$Database = new Database($Config['Database']['Host'], $Config['Database']['User'], $Config['Database']['Password'], $Config['Database']['Database']);
$Database->Prefix = $Config['Database']['Prefix'];
$Database->charset($Config['Database']['Charset']);
include('module.php');
include('page.php');
include('log.php');
include('types/include.php');
include('form.php');
include('table.php');
include('server.php');
include('emulator.php');
include('mangos_configuration_file.php');
include('task.php');

$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' => 0,
    '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', 'sekunda', 1),
      array('min', 'minuta', 60),
      array('hod', 'hodina', 60 * 60) ,
      array('den', 'den', 24 * 60 * 60),
      array('týd', 'týden', 7 * 24 * 60 * 60),
      array('měs', 'měsíc', 30 * 24 * 60 * 60),
      array('rok', 'rok', 364 * 24 * 60 * 60),
      array('des', 'desetiletí', 10 * 364 * 24 * 60 * 60),
      array('sta', 'staletí', 100 * 364 * 24 * 60 * 60),
      array('tis', 'tisiciletí', 10000 * 364 * 24 * 60 * 60),
    ),
  ),
);

class System extends Module
{
  var $Modules = array(); 

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

  function AddModule($Module)
  {
    global $Database;

    //echo('Přidávám modul '.get_class($Module).'<br />');
    $Module->System = &$this;
    $Module->Database = &$Database;
    $this->Modules[get_class($Module)] = $Module;
  }
  
  function AddEmailToQueue($Address, $Subject, $Content, $Headers = '')
  {
    $this->Database->insert('EmailQueue', array('Address' => $Address, 'Subject' => $Subject, 'Content' => $Content, 'Time' => 'NOW()', 'Headers' => $Headers));
  }
  
  function MailUTF8($To, $Subject = '(No subject)', $Message = '', $Header = '') 
  {
    $Header = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=UTF-8' . "\r\n".$Header;
    mail($To, '=?UTF-8?B?'.base64_encode($Subject).'?=', $Message, $Header);
    //echo('mail('.$To.', =?UTF-8?B?'.base64_encode($Subject).'?=, '.$Message.', '.$Header.')<br/>');
  }

  function ProcessEmailQueue()
  {
    $Output = '';
    $DbResult = $this->Database->select('EmailQueue', '*', 'Archive=0');
    while($DbRow = $DbResult->fetch_assoc())
    {      
      $this->MailUTF8($DbRow['Address'], $DbRow['Subject'], $DbRow['Content'], $DbRow['Headers']);
      //echo('mail('.$DbRow['Address'].', '.$DbRow['Subject'].', '.$DbRow['Content'].', FromUTF8('.$DbRow['Headers'].', \'iso2\'));');
      $this->Database->update('EmailQueue', 'Id='.$DbRow['Id'], array('Archive' => 1));
      $this->Modules['Log']->NewRecord('System', 'SendEmail', $DbRow['Id']);
      $Output .= 'To: '.$DbRow['Address'].'  Subject: '.$DbRow['Subject'].'<br />';
    }    
    return($Output);
  }
  
  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;

    if(($Unit == '') and ($PrefixType != 'Time')) return($this->TruncateDigits($Value, $Digits));
    $I = $PrefixMultipliers[$PrefixType]['BaseIndex'];
    if($Value > 0) $II = 1; 
    else if($Value < 0) $II = -1;
    else $II = 0;
    while((($Value / $PrefixMultipliers[$PrefixType]['Definition'][$I + $II][2]) > $II) and (($I + $II) >= 0) and (($I + $II) <= count($PrefixMultipliers[$PrefixType]['Definition']))) $I = $I + $II;
    $Value = $Value / $PrefixMultipliers[$PrefixType]['Definition'][$I][2];

    // Truncate digits count
    $Value = $this->TruncateDigits($Value, $Digits);

    return($Value.' '.$PrefixMultipliers[$PrefixType]['Definition'][$I][0].$Unit);
  }
}

$System = new System();
$System->Config = $Config;
$System->Database = &$Database;
include_once('log.php');
$System->AddModule(new Log());
include_once('user.php');
$System->AddModule(new User());
if(isset($_SERVER['REMOTE_ADDR'])) $System->Modules['User']->Check();

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

$UnitNames = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
 
function HumanSize($Value)
{
  global $UnitNames;

  $UnitIndex = 0;
  while($Value > 1024)
  {
    $Value = round($Value / 1024, 3);
    $UnitIndex++;
  }
  return($Value.' '.$UnitNames[$UnitIndex]);
}

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

function ShowArray($Pole)
{
  echo('<pre style="font-size: 8pt;">');
  print_r($Pole);
  echo('</pre>');
}

function ToVpnIp($Host)
{ 
  if($Host['external_ip'] == '') 
  {
    $Parts = explode('.', $Host['IP']);
    return('172.16.'.$Parts[2].'.'.$Parts[3]);
  } else 
  {
    return($Host['external_ip']);
  }
}

function TimeToMysqlDateTime($Time)
{
  return(date('Y-m-d H:i:s', $Time));  
}

function MysqlDateTimeToTime($Time)
{
  $Parts = explode(' ', $Time);
  $DateParts = explode('-', $Parts[0]); 
  $TimeParts = explode(':', $Parts[1]);
  $Result = mktime($TimeParts[0], $TimeParts[1], $TimeParts[2], $DateParts[1], $DateParts[2], $DateParts[0]); 
  return($Result);  
}

function MysqlDateToTime($Time)
{
  return(MysqlDateTimeToTime($Time.' 0:0:0'));  
}

function HumanDate($Time)
{
  $Date = explode(' ', $Time);
  $Parts = explode('-', $Date[0]);
  if($Date != '0000-00-00') return(($Parts[2]*1).'.'.($Parts[1]*1).'.'.$Parts[0]);
  else return('&nbsp;');
}

// Zobrazení číselný seznamu stránek
function PagesList($URL, $Page, $TotalCount, $CountPerPage, $Around = 10)
{
  $Count = ceil($TotalCount / $CountPerPage);
  $Result = '';
  if($Count > 1)
  {
    if($Page > 0) 
    {
      $Result .= '<a href="'.$URL.'0">&lt;&lt;</a> ';
      $Result .= '<a href="'.$URL.($Page - 1).'">&lt;</a> ';
    }
    $PagesMax = $Count - 1;
    $PagesMin = 0;
    if($PagesMax > ($Page + $Around)) $PagesMax = $Page + $Around;
    if($PagesMin < ($Page - $Around))
    {
      $Result.= ' .. ';
      $PagesMin = $Page - $Around;
    }
    for($i = $PagesMin; $i <= $PagesMax; $i++)
    {
      if($i == $Page) $Result .= '<strong>';
      $Result .= '<a href="'.$URL.$i.'">'.($i + 1).'</a> ';
      if($i == $Page) $Result .= '</strong>';
    }
    if($PagesMax < ($Count - 1)) $Result .= ' .. ';
    if($Page < ($Count - 1)) 
    {
      $Result .= '<a href="'.$URL.($Page + 1).'">&gt;</a> ';
      $Result .= '<a href="'.$URL.($Count - 1).'">&gt;&gt;</a>';
    }
  }
  return($Result);
}

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 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));
}

function NotBlank($Text)
{
  if($Text == '') return('&nbsp'); else return($Text);
}

function MakeLink($Target, $Title)
{
  return('<a href="'.$Target.'">'.$Title.'</a>'); 
}

function Table($Table, $Class)
{
  $Result = '<table class="'.$Class.'">';
  if(array_key_exists('Header', $Table))
  {
    $Result .= '<tr>';
    foreach($Table['Header'] as $Item)
      $Result .= '<th>'.$Item.'</th>';
    $Result .= '</tr>';
  }
  foreach($Table['Rows'] as $Row)
  {
    $Result .= '<tr>';
    foreach($Row as $Index => $Item)
    {
      if($Index == 0) $Class = ' class="Header"'; else $Class = '';
      $Result .= '<td'.$Class.'>'.$Item.'</td>';
    }
    $Result .= '</tr>';
  }
  $Result .= '</table>';
  return($Result);
}

?>
