<?php

$ScriptStartTime = GetMicrotime();

if(isset($_SERVER['REMOTE_ADDR'])) session_start();

// SQL injection hack protection
foreach($_POST as $Index => $Item)
{
  if(is_array($_POST[$Index])) 
    foreach($_POST[$Index] as $Index2 => $Item2) $_POST[$Index][$Index2] = addslashes($Item2);
  else $_POST[$Index] = addslashes($_POST[$Index]);
}
foreach($_GET as $Index => $Item) $_GET[$Index] = addslashes($_GET[$Index]);

include_once(dirname(__FILE__).'/global_function.php');
if(file_exists(dirname(__FILE__).'/config.php')) include_once(dirname(__FILE__).'/config.php');
  else die('Nenalezen konfigurační soubor config.php ve složce includes. Vytvořte jej zkopírováním vzoru config.sample.php.');
date_default_timezone_set($Config['Web']['Timezone']);
include_once(dirname(__FILE__).'/Database.php');
include_once(dirname(__FILE__).'/rss.php');
include_once(dirname(__FILE__).'/system.php');
include_once(dirname(__FILE__).'/user.php');

$System = new System();
$System->Init();
$User = new User($System);

include_once(dirname(__FILE__).'/error.php');

$TranslationTree = GetTranslationTree();
$LanguageList = GetLanguageList();

LogReferrer();

function GetMicrotime()
{
  list($Usec, $Sec) = explode(' ', microtime());
  return ((float)$Usec + (float)$Sec);
}

function ShowShoutbox()
{
  global $System, $Config, $User, $System;
  
  $Output = '<strong><a href="'.$System->Link('/action.php?action=ShoutBoxView').'">Kecátko:</a></strong>';
  if($User->Licence(LICENCE_USER)) 
    $Output .= ' <a href="'.$System->Link('/action.php?action=shoutbox').'">Vložit</a>';
  $Output .= '<div class="box"><table>';
  $DbResult = $System->Database->query('SELECT * FROM `ShoutBox` ORDER BY `ID` DESC LIMIT 30');
  while($Line = $DbResult->fetch_assoc())
    $Output .= '<tr><td><strong>'.$Line['UserName'].'</strong>: '.MakeActiveLinks($Line['Text']).'</td></tr>';
  $Output .= '</table></div>';
  return($Output);
}

function ShowTopBar()
{
  global $Config, $System, $User, $System;
  
  echo('<div class="Menu">');
  echo('<span class="MenuItem"></span>');
  if($User->Licence(LICENCE_USER))
  {
    //$DbResult = $System->Database->query('SELECT `Id`, `Name` FROM `Team` WHERE `Id`='.$User->Team);
    //$Team = $DbResult->fetch_assoc();
    //echo('<span class="MenuItem">Moje překlady: <a href="">Dokončené</a> <a href="">Rozpracované</a> <a href="">Exporty</a> Tým: <a href="">'.$Team['name'].'</a></span>');
    echo('<span class="MenuItem2">'.$User->Name.' <a href="'.$System->Link('/?action=logout').'">Odhlášení</a> <a href="'.$System->Link('/Options.php').'">Nastavení</a>');
    echo(' <a title="Vámi přeložené texty" href="'.$System->Link('/TranslationList.php?user='.$User->Id.'&amp;group=0&amp;state=2&amp;text=&amp;entry=').'">Přeložené</a>');
    echo(' <a title="Vaše rozpracované text" href="'.$System->Link('/TranslationList.php?user='.$User->Id.'&amp;group=0&amp;state=3&amp;text=&amp;entry=').'">Rozpracované</a>');
    echo(' <a title="Nikým nepřeložené texty" href="'.$System->Link('/TranslationList.php?user=0&amp;group=0&amp;state=1&amp;text=&amp;entry=').'">Nepřeložené</a>');
    echo('</span>');
  } else 
  {
    echo('<span class="MenuItem2"><form action="?action=login" method="post"> Jméno: <input type="text" name="LoginUser" size="8 " /> Heslo: <td><input type="password" name="LoginPass" size="8" /> <input type="submit" value="Přihlásit" /></form> &nbsp; <a href="'.$System->Link('/registrace.php').'">Registrace</a></span>');
  }
  echo('</div>');
}

function ShowLoginBox()
{
  global $User;
  
  if($User->Licence(LICENCE_USER)) 
  {
     // echo 'Jste přihlášen jako: <b>'.$User->Id.'</b> <a href="index.php?Logout">Odhlásit</a>';
  } else 
  {
    echo('<strong>Přihlášení:</strong>
  <form action="" method="post">
  <table>
    <tr>
      <td><input type="text" name="LoginUser" size="13" /></td>
    </tr>
    <tr>
      <td><input type="password" name="LoginPass" size="13" /></td>
    </tr>
    <tr>
      <th><input type="submit" value="Přihlásit" /></th>
    </tr>
  </table>
  </form>');
  }
}

function ShowSearchBox()
{
  global $System;
  
  echo('<strong>Hledání:</strong>'.
  '<form action="'.$System->Link('/action.php').'" method="get"><div>'.
  '<input type="hidden" name="action" value="search" />'.
  '<table>'.
  '<tr>'.
      '<td><input type="text" name="search" size="13" /></td>'.
    '</tr>'.
    '<tr>'.
      '<th><input type="submit" value="Hledat" /></th>'.
    '</tr>'.
  '</table></div>'.
  '</form>');
}

function ShowMainMenu()
{ 
  global $TranslationTree, $Config, $User, $System;
  
  $Menu = array
  (
    $System->Link('/') => array(LICENCE_ANONYMOUS, 'Hlavní stránka', 'Domů'),
    $System->Link('/dictionary.php') => array(LICENCE_ANONYMOUS, 'Slovník WoW výrazů', 'Slovníček'),
    $System->Link('/statistic.php') => array(LICENCE_ANONYMOUS, 'Stav dokončení překládů', 'Stav dokončení'),
    $System->Link('/userlist.php?action=nofilter') => array(LICENCE_ANONYMOUS, 'Seznam registrovaných uživatelů', 'Překladatelé'),
    $System->Link('/team.php?search=') => array(LICENCE_ANONYMOUS, 'Seznam překladatelských týmů', 'Týmy'),
    $System->Link('/serverlist.php') => array(LICENCE_ANONYMOUS, 'Seznam serverů, kde je nasazena čeština v praxi', 'Servery'),
    $System->Link('/export/') => array(LICENCE_ANONYMOUS, 'Zde si můžete stáhnout přeložené texty', 'Exporty'),
    $System->Link('/download.php') => array(LICENCE_ANONYMOUS, 'Stahování různých pomocných souborů a programů', 'Soubory'),
    $System->Link('/info.php') => array(LICENCE_ANONYMOUS, 'Informace k překladu hry', 'Informace'),
    $System->Link('/TranslationList.php?action=grouplist') => array(LICENCE_ANONYMOUS, 'Informace o překladových skupinách', 'Zdroje dat'), 
    $System->Link('/banners.php') => array(LICENCE_ANONYMOUS, 'Informace k propagaci tohoto projektu', 'Propagace'),
    $System->Link('/promotion.php') => array(LICENCE_ANONYMOUS, 'Prezentace a motivace překladu', 'Prezentace'),
    $System->Link('/version.php') => array(LICENCE_ANONYMOUS, 'Seznam verzí herního klienta', 'Verze hry'), 
    $System->Link('/aowow/') => array(LICENCE_ANONYMOUS, 'Vyhledávací databáze podobná WoWHead s překlady', 'AoWoW'), 
'http://embed.mibbit.com/?server=game.zdechov.net%3A6667&amp;channel=%23wowpreklad&amp;forcePrompt=true&amp;charset=utf-8' => array(LICENCE_ANONYMOUS, 'IRC chat pro překladatele', 'Chat'),
    $System->Link('/admin/') => array(LICENCE_ADMIN, 'Volby pro správu', 'Administrace'), 
  );
  
  echo('<strong>Hlavní menu:</strong>'.
    '<div class="verticalmenu"><ul>'); 
  foreach($Menu as $MenuTarget => $MenuItem)
  {
    if(isset($MenuItem[3])) $OnClick = ' onclick="'.$MenuItem[3].'"'; 
      else $OnClick = '';
    if($User->Licence($MenuItem[0])) echo('<li><a class="verticalmenua" title="'.$MenuItem[1].'" href="'.$MenuTarget.'"'.$OnClick.'>'.$MenuItem[2].'</a></li>');
  }    
  echo('</ul></div>');
}

function ShowTranslatedMenu()
{
  global $TranslationTree, $User, $System;

  echo('<strong>Překladové skupiny:</strong><br /><div id="TranslationMenu">');
  foreach($TranslationTree as $Group)
  {
    echo('<div id="menuitem-group'.$Group['Id'].'" onmousemove="show(\'group'.$Group['Id'].'\')" onmouseout="hide(\'group'.$Group['Id'].'\')">'.
      '<a href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;action=filter').'">'.$Group['Name'].'</a></div>'.
      '<div id="group'.$Group['Id'].'" class="hidden-menu-item" onmousemove="show(\'group'.$Group['Id'].'\')" onmouseout="hide(\'group'.$Group['Id'].'\')">');
    echo('&nbsp;<a title="Zde můžete začít překládat" href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=1&amp;user=0&amp;entry=&amp;text=').'">Nepřeložené</a><br />'.
    '&nbsp;<a title="Přeložené texty, můžete zde hlasovat, nebo opravovat překlady" href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=2&amp;user=0&amp;entry=&amp;text=').'">Přeložené</a><br />'); 
    if($User->Licence(LICENCE_USER)) 
    {
      echo('&nbsp;<a title="Nedokončené překlady" href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=3').'">Rozepsané</a><br />
        &nbsp;<a title="Všechny překlady, které jste přeložil" href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=1&amp;user='.$User->Id).'&amp;entry=&amp;text=">Vlastní</a><br />');
    }
    echo('&nbsp;<a title="Sestavit speciální filtr" href="'.$System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;action=filter').'">Filtr</a><br />');
    echo('</div>');
  }
  echo ('</div>');
}

function ShowOnlineUserList()
{
  global $System, $Moderators, $User;
  
  echo('Online překladatelé:<br />');
  $DbResult = $System->Database->query('SELECT `Name`, `GM`, `ID` FROM `User` WHERE `LastLogin` >= NOW() - 300 AND ((`LastLogout` < `LastLogin`) OR (ISNULL(`LastLogout`)))');
  while($DbUser = $DbResult->fetch_assoc())
  {
    if($User->Licence(LICENCE_MODERATOR)) $Name = '<a href="user.php?user='.$DbUser['ID'].'">'.$DbUser['Name'].'</a>';
    else $Name = $DbUser['Name'];
    $TextGM = '';
    echo('<strong>'.$Name.'</strong>'.$TextGM.'<br />');
  }
}

function ShowPage()
{
  global $User, $RSSChannels, $PageFooterRequested, $System;  
  
  echo('<?xml version="1.0" encoding="'.$System->Config['Web']['Charset'].'"?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cz">'.
'<head>'.
'<meta http-equiv="content-type" content="application/xhtml+xml; charset='.$System->Config['Web']['Charset'].'" />'.
'<meta name="keywords" content="wow, quest, questy, questů, preklad, mangos, překlad, překládání, přeložený, přeložení, čeština, world of warcraft, open source, free, addon" />'.
'<meta name="description" content="'.$System->Config['Web']['Title'].'" />'.
'<meta name="robots" content="all" />'.
'<link rel="stylesheet" href="'.$System->Link('/style/style.css').'" type="text/css" media="all" />'.
'<script type="text/javascript" src="'.$System->Link('/style/global.js').'"></script>'.
'<link rel="shortcut icon" href="'.$System->Link('/images/favicon.ico').'" />');
  if(isset($RSSChannels)) 
  foreach($RSSChannels as $Channel)
    echo(' <link rel="alternate" title="'.$Channel['Title'].'" href="'.$Channel['URL'].'" type="application/rss+xml" />');
  echo('<title>'.$System->Config['Web']['Title'].'</title>
</head>
<body>');
/*
echo('<table id="bannertable"><tr>'.
  '<td id="banner1"></td>'.
  '<td id="banner"><div id="bannertitle">'.$Config['Web']['Title'].'</div></td>'.
  '<td id="banner2"></td></tr>'.
'</table>');
*/

  if(array_key_exists('action', $_GET))
  {
    if($_GET['action'] == 'login')
    {
      if(array_key_exists('LoginUser', $_POST) and array_key_exists('LoginPass', $_POST))
      {
        $User->Login($_POST['LoginUser'], $_POST['LoginPass']);
        if($User->Role == LICENCE_ANONYMOUS) 
        {
          $Message = 'Jméno nebo heslo bylo zadáno špatně.';  
          $MessageType = MESSAGE_CRITICAL;
        } else 
        {
          $Message = 'Přihlášení proběhlo úspěšně. Vítej <strong>'.$User->Name.'</strong>!';  
          $MessageType = MESSAGE_INFORMATION;
        } 
      } else 
      {
        $Message = 'Nebylo zadáno jméno a heslo.';  
        $MessageType = MESSAGE_CRITICAL;
      }  
    } else 
    if($_GET['action'] == 'logout')
    {
      if($User->Role != LICENCE_ANONYMOUS)
      {
        WriteLog('Odhlášení', LOG_TYPE_USER);
        $User->Logout();
        $Message = 'Byl jsi odhlášen.';  
        $MessageType = MESSAGE_INFORMATION;
      }
    }
  }
  ShowTopBar();

  echo('<table class="page"><tr><td class="menu">');
  ShowMainMenu();
  ShowOnlineUserList();
  echo('<br />');
  ShowSearchBox();
  echo('</td><td id="border-left"></td><td class="content">');
  $PageFooterRequested = true;
  if(isset($Message)) ShowMessage($Message, $MessageType);
}

$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 ShowFooter()
{
  global $System, $ScriptStartTime, $PageFooterRequested, $User;

  if(isset($PageFooterRequested)) 
  {
    $ScriptGenerateDuration = round(GetMicrotime() - $ScriptStartTime, 2);

    echo('</td>');
    echo('<td class="menu2">');
    ShowTranslatedMenu();
    echo('</td>'.
    '</tr><tr>'.
    '<td colspan="4" class="page-bottom">Autoři: '.$System->Config['Web']['Authors'].
    ' &nbsp; <a href="http://svn.zdechov.net/trac/wowpreklad/browser/trunk">Zdrojové soubory</a> &nbsp; '.
    '<a href="http://svn.zdechov.net/trac/wowpreklad/log/trunk?verbose=on">Novinky</a> &nbsp; '.
    $System->Config['Web']['WebCounter']);
  
    echo('</td></tr>');
    if($System->Config['Web']['ShowRuntimeInfo'] == true) echo('<tr><td colspan="3" style="text-align: center;">Doba generování: '.$ScriptGenerateDuration.' s / '.ini_get('max_execution_time').' s &nbsp;&nbsp; Použitá paměť: '.HumanSize(memory_get_peak_usage(FALSE)).' / '.ini_get('memory_limit').'B &nbsp;&nbsp; <a href="http://validator.w3.org/check?uri='.htmlentities('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING']).'">HTML validator</a></td></tr>');
    echo('</table>'.
      '</body>'.
      '</html>');
    $User->Store();
  } 
}

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('&', $Parts));
}

?>
