<?php

$Revision = 

/* @var $System System */
$System = NULL;
/* @var $Database Database */
$Database = NULL;
      
$ConfigFileName = dirname(__FILE__).'/../config.php';
if(file_exists($ConfigFileName)) include_once($ConfigFileName);
include_once(dirname(__FILE__).'/Version.php');
include_once(dirname(__FILE__).'/Update.php');
include_once(dirname(__FILE__).'/VarDumper.php');
include_once(dirname(__FILE__).'/Module.php');
include_once(dirname(__FILE__).'/AppModule.php');
include_once(dirname(__FILE__).'/Database.php');
include_once(dirname(__FILE__).'/Code.php');
include_once(dirname(__FILE__).'/Mail.php');
include_once(dirname(__FILE__).'/Log.php');
include_once(dirname(__FILE__).'/User.php');
include_once(dirname(__FILE__).'/Page.php');
include_once(dirname(__FILE__).'/Form/Form.php');
include_once(dirname(__FILE__).'/../finance/bills.php');
include_once(dirname(__FILE__).'/../finance/finance.php');
include_once(dirname(__FILE__).'/../form_classes.php');

  
// Application modules
include_once(dirname(__FILE__).'/../Modules/Error/Error.php');
include_once(dirname(__FILE__).'/../Modules/File/File.php');
include_once(dirname(__FILE__).'/../Modules/Meteostation/Meteostation.php');
include_once(dirname(__FILE__).'/../Modules/Portal/Portal.php');
include_once(dirname(__FILE__).'/../Modules/IS/IS.php');
include_once(dirname(__FILE__).'/../Modules/Network/Network.php');
include_once(dirname(__FILE__).'/../Modules/TV/TV.php');
include_once(dirname(__FILE__).'/../Modules/OpeningHours/OpeningHours.php');
include_once(dirname(__FILE__).'/../Modules/Map/Map.php');
include_once(dirname(__FILE__).'/../Modules/Chat/Chat.php');
include_once(dirname(__FILE__).'/../Modules/WebCam/WebCam.php');
include_once(dirname(__FILE__).'/../Modules/User/User.php');
include_once(dirname(__FILE__).'/../Modules/Finance/Finance.php');
include_once(dirname(__FILE__).'/../Modules/FinanceBankAPI/FinanceBankAPI.php');
include_once(dirname(__FILE__).'/../Modules/NetworkShare/NetworkShare.php');
include_once(dirname(__FILE__).'/../Modules/News/News.php');
include_once(dirname(__FILE__).'/../Modules/Meals/Meals.php');
include_once(dirname(__FILE__).'/../Modules/NetworkTopology/NetworkTopology.php');

class System extends Module
{
  var $Modules; 
  /** @var Type */
  var $Type;
  var $Pages;
  /** @var AppModuleManager */
  var $ModuleManager;
  var $PathItems;

  function __construct()
  {
    parent::__construct();
    $this->Modules = array();
    $this->Pages = array();
    $this->ModuleManager = new AppModuleManager();
    $this->Database = new Database();
    $this->FormManager = new FormManager($this->Database);
  }  
  
  function RegisterPage($Path, $Handler)
  {
    $this->Pages[$Path] = $Handler;
  }
  
  function SearchPage($PathItems, $Pages)
  {
    $PathItem = $PathItems[0];
    if(array_key_exists($PathItem, $Pages))
    {
      if(is_array($Pages[$PathItem])) 
      {
        array_shift($PathItems);
        return($this->SearchPage($PathItems, $Pages[$PathItem]));
      } else return($Pages[$PathItem]);
    } else return('');
  }
  
  function ShowPage()
  {
    /* @var $Page Page */
    $ClassName = $this->SearchPage($this->PathItems, $this->Pages);     
    if($ClassName != '') 
    {
      $Page = new $ClassName();
      $Page->System = &$this;
      $Page->Database = &$this->Database;
      $Page->GetOutput();
    } else echo('Page '.implode('/', $this->PathItems).' not found.');
  }
  
  function ModulePresent($Name)
  {
    return(array_key_exists($Name, $this->Modules));
  }

  function AddModule($Module)
  {
    //echo('Přidávám modul '.get_class($Module).'<br />');
    $Module->System = &$this;
    $Module->Database = &$this->Database;
    $this->Modules[get_class($Module)] = $Module;
  }
  
  function AddEmailToQueue($To, $Subject, $Content, $From, $AttachmentFileId = '')
  {
    $Values = array('To' => $To, 
      'Subject' => $Subject, 'Content' => $Content, 'Time' => 'NOW()', 
      'From' => $From);
    if($AttachmentFileId != '') $Values['AttachmentFile'] = $AttachmentFileId;
    $this->Database->insert('EmailQueue', $Values);
  }
  
  function ProcessEmailQueue()
  {
    $Output = '';
    $DbResult = $this->Database->select('EmailQueue', '*', 'Archive=0');
    while($DbRow = $DbResult->fetch_assoc())
    {      
      $Mail = new Mail();
      $Mail->AddToCombined($DbRow['To']);
      $Mail->Subject = $DbRow['Subject'];
      $Mail->From = $DbRow['From'];
      $Mail->AddBody(strip_tags($DbRow['Content']), 'text/plain');
      $Mail->AddBody($DbRow['Content'], 'text/html');
      if($DbRow['AttachmentFile'] != '')
      {
        $DbResult2 = $this->Database->select('File', '*', 'Id='.$DbRow['AttachmentFile']);
        while($File = $DbResult2->fetch_assoc())
          $Mail->AttachFile($this->Config['Web']['FileRootFolder'].$File['DrivePath'], $File['MimeType']);
      }
      $Mail->Send();
      $this->Database->update('EmailQueue', 'Id='.$DbRow['Id'], array('Archive' => 1));
      $this->Modules['Log']->NewRecord('System', 'SendEmail', $DbRow['Id']);
      $Output .= 'To: '.$DbRow['To'].'  Subject: '.$DbRow['Subject'].'<br />';
    }    
    return($Output);
  }
  
  function HumanDate($Time)
  {
    return(date('j.n.Y', $Time));
  }
  
  function Link($Target)
  {
    global $Config;
   
    return($Config['Web']['RootFolder'].$Target);
  }   
}

function GlobalInit()
{
  global $Config, $Database, $System, $ScriptTimeStart, $ConfigFileName, $Mail, $Type,
    $DatabaseRevision;
  
  date_default_timezone_set('Europe/Prague');
  $ScriptTimeStart = GetMicrotime();
  
  if(!isset($Config)) die('Systém není nainstalován. Pokračujte v instalaci <a href="admin/">zde</a>.');
   
  // 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();

  $System = new System();
  $System->Config = &$Config;
  $System->Database->Connect($Config['Database']['Host'], $Config['Database']['User'], $Config['Database']['Password'], $Config['Database']['Database']);
  $System->Database->Prefix = $Config['Database']['Prefix'];
  $System->Database->charset($Config['Database']['Charset']);
  $System->Database->ShowSQLError = $Config['Web']['ShowSQLError'];
  $System->Database->ShowSQLQuery = $Config['Web']['ShowSQLQuery'];
  
  // Check database persistence structure
  $UpdateManager = new UpdateManager();
  $UpdateManager->Database = &$System->Database;
  $UpdateManager->Revision = $DatabaseRevision;
  if(!$UpdateManager->IsInstalled()) die('Systém vyžaduje instalaci databáze.');
  if(!$UpdateManager->IsUpToDate()) die('Systém vyžaduje aktualizaci databáze.');
  
  // Init old modules
  $System->AddModule(new Log());
  $System->AddModule(new User());
  if(isset($_SERVER['REMOTE_ADDR'])) $System->Modules['User']->Check();
  $System->AddModule(new Bill());
  $System->AddModule(new Finance());
  $System->Modules['Finance']->MainSubject = $Config['Finance']['MainSubjectId'];
  $System->Modules['Finance']->DirectoryId = $Config['Finance']['DirectoryId'];
  $System->Modules['Finance']->LoadMonthParameters(0);
  $System->Modules['Log']->Database->LastQuery = 'ssd';
  RegisterFormClasses($System->FormManager);
  
  
  // Register new modules
  $System->ModuleManager->RegisterModule(new ModuleError($System));
  $System->ModuleManager->RegisterModule(new ModuleFile($System));
  $System->ModuleManager->RegisterModule(new ModuleMeteostation($System));
  $System->ModuleManager->RegisterModule(new ModulePortal($System));
  $System->ModuleManager->RegisterModule(new ModuleIS($System));
  $System->ModuleManager->RegisterModule(new ModuleNetwork($System));
  $System->ModuleManager->RegisterModule(new ModuleTV($System));
  $System->ModuleManager->RegisterModule(new ModuleOpeningHours($System));
  $System->ModuleManager->RegisterModule(new ModuleMap($System));
  $System->ModuleManager->RegisterModule(new ModuleChat($System));
  $System->ModuleManager->RegisterModule(new ModuleWebCam($System));
  $System->ModuleManager->RegisterModule(new ModuleUser($System));
  $System->ModuleManager->RegisterModule(new ModuleFinance($System));
  $System->ModuleManager->RegisterModule(new ModuleFinanceBankAPI($System));
  $System->ModuleManager->RegisterModule(new ModuleNetworkShare($System));
  $System->ModuleManager->RegisterModule(new ModuleNews($System));
  $System->ModuleManager->RegisterModule(new ModuleMeals($System));
  $System->ModuleManager->RegisterModule(new ModuleNetworkTopology($System));
  $System->ModuleManager->StartAll();
}

$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 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)
{
  $Count = ceil($TotalCount / $CountPerPage);
  $Around = 10;
  $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 ExtractTime($Time)
{ 
  return(array(
  	'Year' => date('Y', $Time), 
  	'Month' => date('n', $Time), 
  	'Day' => date('j', $Time),
  	'Hour' => date('h', $Time),
  	'Minute' => date('i', $Time),
  	'Second' => date('s', $Time)
  ));
}

function GetQueryStringArray($QueryString)
{
  $Result = array();
  $Parts = explode('&', $QueryString);
  foreach($Parts as $Part)
  {
    if($Part != '')
    {
      if(!strpos($Part, '=')) $Part .= '=';
      $Item = explode('=', $Part);
      $Result[$Item[0]] = $Item[1];
    }
  }
  return($Result);
}

function SetQueryStringArray($QueryStringArray)
{
  $Parts = array();
  foreach($QueryStringArray as $Index => $Item)
  {
    $Parts[] = $Index.'='.$Item;
  }
  return(implode('&amp;', $Parts));
}

function GetPageList($TotalCount)
{
  global $System;
    
  $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
  
  $Result = '';
  if(array_key_exists('all', $QueryItems)) 
  {
    $PageCount = 1;
    $ItemPerPage = $TotalCount;    
  } else 
  {
    $ItemPerPage = $System->Config['Web']['ItemsPerPage'];
    $Around = round($System->Config['Web']['VisiblePagingItems'] / 2);
    $PageCount = floor($TotalCount / $ItemPerPage) + 1;
  }
  
  if(!array_key_exists('Page', $_SESSION)) $_SESSION['Page'] = 0;
  if(array_key_exists('page', $_GET)) $_SESSION['Page'] = $_GET['page'] * 1;
  if($_SESSION['Page'] < 0) $_SESSION['Page'] = 0;
  if($_SESSION['Page'] >= $PageCount) $_SESSION['Page'] = $PageCount - 1;
  $CurrentPage = $_SESSION['Page'];
  
        
  $Result .= 'Počet položek: <strong>'.$TotalCount.'</strong> &nbsp; Stránky: ';

  $Result = '';
  if($PageCount > 1)
  {
    if($CurrentPage > 0) 
    {
      $QueryItems['page'] = 0;      
      $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;&lt;</a> ';
      $QueryItems['page'] = ($CurrentPage - 1);
      $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;</a> ';
    }
    $PagesMax = $PageCount - 1;
    $PagesMin = 0;
    if($PagesMax > ($CurrentPage + $Around)) $PagesMax = $CurrentPage + $Around;
    if($PagesMin < ($CurrentPage - $Around))
    {
      $Result.= ' ... ';
      $PagesMin = $CurrentPage - $Around;
    }
    for($i = $PagesMin; $i <= $PagesMax; $i++)
    {
      if($i == $CurrentPage) $Result.= '<strong>'.($i + 1).'</strong> ';
      else {
       $QueryItems['page'] = $i;
       $Result .= '<a href="?'.SetQueryStringArray($QueryItems).'">'.($i + 1).'</a> ';
      }
    } 
    if($PagesMax < ($PageCount - 1)) $Result .= ' ... ';
    if($CurrentPage < ($PageCount - 1)) 
    {
      $QueryItems['page'] = ($CurrentPage + 1);
      $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;</a> ';
      $QueryItems['page'] = ($PageCount - 1);
      $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;&gt;</a>';
    }
  }
  $QueryItems['all'] = '1';
  if($PageCount > 1) $Result.= ' <a href="?'.SetQueryStringArray($QueryItems).'">Vše</a>';
  
  $Result = '<div style="text-align: center">'.$Result.'</div>';
  return(array('SQLLimit' => ' LIMIT '.$CurrentPage * $ItemPerPage.', '.$ItemPerPage, 
    'Page' => $CurrentPage,
    'Output' => $Result,
  ));
}

$OrderDirSQL = array('ASC', 'DESC');
$OrderArrowImage = array('sort_asc.png', 'sort_desc.png');

function GetOrderTableHeader($Columns, $DefaultColumn, $DefaultOrder = 0)
{
  global $OrderDirSQL, $OrderArrowImage, $Config, $System;
  
  if(array_key_exists('OrderCol', $_GET)) $_SESSION['OrderCol'] = $_GET['OrderCol'];
  if(array_key_exists('OrderDir', $_GET)) $_SESSION['OrderDir'] = $_GET['OrderDir'];
  if(!array_key_exists('OrderCol', $_SESSION)) $_SESSION['OrderCol'] = $DefaultColumn;
  if(!array_key_exists('OrderDir', $_SESSION)) $_SESSION['OrderDir'] = $DefaultOrder;
  
  // Check OrderCol
  $Found = false;
  foreach($Columns as $Column)
  {
    if($Column['Name'] == $_SESSION['OrderCol'])
    {
      $Found = true;    
      break;
    }
  }
  if($Found == false)
  {
    $_SESSION['OrderCol'] = $DefaultColumn;
    $_SESSION['OrderDir'] = $DefaultOrder;
  }
  // Check OrderDir
  if(($_SESSION['OrderDir'] != 0) and ($_SESSION['OrderDir'] != 1)) $_SESSION['OrderDir'] = 0;
  
  $Result = '';
  $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
  foreach($Columns as $Index => $Column)
  {
    $QueryItems['OrderCol'] = $Column['Name'];
    $QueryItems['OrderDir'] = 1 - $_SESSION['OrderDir'];
    if($Column['Name'] == $_SESSION['OrderCol']) $ArrowImage = '<img style="vertical-align: middle; border: 0px;" src="'.$System->Link('/images/'.$OrderArrowImage[$_SESSION['OrderDir']]).'" alt="order arrow">';
      else $ArrowImage = '';
    if($Column['Name'] == '') $Result .= '<th>'.$Column['Title'].'</th>';
      else $Result .= '<th><a href="?'.SetQueryStringArray($QueryItems).'">'.$Column['Title'].$ArrowImage.'</a></th>';
  }
  return(array(
    'SQL' => ' ORDER BY `'.$_SESSION['OrderCol'].'` '.$OrderDirSQL[$_SESSION['OrderDir']],
    'Output' => '<tr>'.$Result.'</tr>',
    'Column' => $_SESSION['OrderCol'],
    'Direction' => $_SESSION['OrderDir'],
  ));
}

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 IsInternetAddr()
{
  $RemoteAddr = GetRemoteAddress();
  $RemoteAddr = explode('.', $RemoteAddr);
//  return(!(($RemoteAddr[0] == 10) and ($RemoteAddr[1] == 145)));
  return(!(($RemoteAddr[0] == 10)));
}

function GetMemberByIP($IP)
{
  global $Database;
  
  $DbResult = $Database->query('SELECT Id FROM Member WHERE (SELECT Member FROM NetworkDevice WHERE (SELECT Device FROM NetworkInterface WHERE LocalIP = "'.$IP.'") = NetworkDevice.Id) = Member.Id');
  if($DbResult->num_rows > 0)
  {
    $DbRow = $DbResult->fetch_assoc();  
    return($DbRow['Id']);
  } else return('');
}

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 RouterOSIdent($Name)
{
  return(strtr(strtolower(trim($Name)), array(' ' => '-', '.' => '', '(' => '-', ')' => '-',
  'č' => 'c', 'š' => 's', 'ě' => 'e', 'ř' => 'r', 'ž' => 'z', 'ý' => 'y', 'á' => 'a', 'í' => 'i', 'é' => 'e', 'ů' => 'u', 'ú' => 'u', 'ď' => 'd', 'ť' => 't', 'ň' => 'n', 'ó' => 'o',
  'Č' => 'c', 'Š' => 's', 'Ě' => 'e', 'Ř' => 'r', 'Ž' => 'z', 'Ý' => 'y', 'Á' => 'a', 'Í' => 'i', 'É' => 'e', 'Ů' => 'u', 'Ú' => 'u', 'Ď' => 'd', 'Ť' => 't', 'Ň' => 'n', 'Ó' => 'o',
)));
}

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

function strip_cdata($string)
{
  preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
  return str_replace($matches[0], $matches[1], $string);
} 

function html2txt($document)
{
  $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
               '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
               '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
               '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
  );
  $text = preg_replace($search, '', $document);
  return $text;
} 

function ProcessURL()
{
  if(array_key_exists('REDIRECT_QUERY_STRING', $_SERVER))
    $PathString = $_SERVER['REDIRECT_QUERY_STRING'];
    else $PathString = '';
  if(substr($PathString, -1, 1) == '/') $PathString = substr($PathString, 0, -1);
  $PathItems = explode('/', $PathString);
  if(strpos($_SERVER['REQUEST_URI'], '?') !== false)
    $_SERVER['QUERY_STRING'] = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1);
    else $_SERVER['QUERY_STRING'] = '';    
  parse_str($_SERVER['QUERY_STRING'], $_GET);
  return($PathItems);
}

GlobalInit();

?>
