<?php

class Html
{
  private $values;
  private $db;

  public function __construct($values, $db)
  {
    $this->db = &$db;
    // default config
    $this->html_cfg = array
    (
/*      "charset" => "utf-8",
      "author" => "Zork",
      "copyright" => "(C) 2008 Heroes of Fantasy, All rights reserved.",
      "favicon" => "imgs/fav",
      "title" => "Heroes of Fantasy",
      "description" => "Heroes of Fantasy free WoW server běžící na programu MaNGOS",
      "keywords" => "wowserver, world of warcraft, free, wow, server, hof, heroes of fantasy, zdechov, mangos"
*/    );

    if((count($values) > 1) or ($values[0] != 0) and ($values[0] != 0))
    {
      $result_cfg = array_merge ($this->html_cfg, $values);
      foreach($result_cfg as $name => $value)
        $this->{$name} = $value;
    } else
    {
      foreach($this->html_cfg as $name => $value)
        $this->{$name} = $value;
    }
  }
  
  function Link($Path)
  {
    global $Config;
    
    if(substr($Path, 0, 1) == '/') return($Config['Web']['BaseURL'].$Path);
    return($Path);
  }

  private function CfgChck($value)
  {
    if(isset($this->{$value}))
    {
      return($this->{$value});
    } else
    {
      return('Undefined');
    }
  }

  public function Start()
  {
    global $Config;
    
    $code = '<?xml version="1.0" encoding="utf-8"?>'.
    '<!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="cs">'.
    '<head>'.
    '<meta http-equiv="content-type" content="application/xhtml+xml; charset='.$Config['Web']['Charset'].'" />'.
    '<meta http-equiv="content-Language" content="cs" />'.
    '<meta name="robots" content="index,follow" />'.
    '<meta name="googlebot" content="index,follow,snippet,archive" />'.
    '<link href="imgs/fav.ico" rel="shortcut icon" />'.
    '<title>'.$Config['Web']['Title'].'</title>'.
    '<meta name="description" content="'.$Config['Web']['Description'].'" />'.
    '<meta name="keywords" content="'.$Config['Web']['Keywords'].'" />'.
    '<link rel="stylesheet" type="text/css" href="'.$this->Link('/styles/style.css.php').'" />'.
    '<link href="'.$this->Link('/inc/teamspeakdisplay/teamspeakdisplay.css').'" rel="stylesheet" type="text/css" />'.
    '<link rel="alternate" title="Články" href="'.$this->Link('/rss.php?category=articles').'" type="application/rss+xml" />'.
    '<link rel="alternate" title="Finanční přispěvky" href="'.$this->Link('rss.php?category=finance').'" type="application/rss+xml" />'.
    '<script type="text/javascript" src="'.$this->Link('/styles/global.js').'"></script>'.
    '<!--[if IE]><link rel="stylesheet" type="text/css" href="'.$this->Link('styles/ie.css').'" /><![endif]-->'.
    '</head>'.
    '<body>';
    $this->TimerStart();
    echo($code);
  }

  private function TimerStart()
  {
    $time_start = microtime(); 
    $time_start = explode(' ', $time_start); 
    $time_start = $time_start[1] + $time_start[0]; 
    $this->time_start = $time_start;
  }

  private function TimerStop()
  {
    $round = 100000;
    $time_start = $this->time_start;
    $time_stop = microtime();
    $time_stop = explode(' ', $time_stop); 
    $time_stop = $time_stop[1] + $time_stop[0]; 
    $deltatime = $time_stop - $time_start; 
    $deltatime = (round(($deltatime * $round))) / $round; 
    return($deltatime);
  } 
  
  public function Stop()
  {
    $time = $this->TimerStop();
    $code = '<!-- Vygenerováno za : ".$time." s -->'.
    '</body></html>';
    echo($code);
  }

  public function PrgStart()
  {
    global $html;
    
    echo('<table align="center" width="346" height="417" border="0" style="background-image: url('.$html->Link('/imgs/web/prg.gif').');">
          <tr height="80">
            <td width="20"></td>
            <td align="center">
            <h3>Správa účtu</h3>
            </td>
            <td width="20"></td>
          </tr>
          <tr>
            <td width="20"></td>
            <td align="center" valign="top">');  
  }

  public function PrgStop()
  {
    echo('</td>
        <td width="20"></td>
      </tr>
      <tr height="30">
        <td width="20"></td>
        <td></td>
        <td width="20"></td>
      </tr>
      </table>');
  }

  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;');
  }
  
  function ShowNews()
  {
    global $Config, $db;
    
    $db->select_db($Config['Database']['Database']);
    $Output = '';

    /*$Output = '<table class="NewsCategoryTable">'.
      '<tr>';
    $DbResult = $db->query('SELECT * FROM ArticleCategory');
    while($Category = $DbResult->fetch_assoc())
    {
      $Output .= '<td><a href="?category='.$Category['Id'].'">'.$Category['Name'].'</a></td>';
    }
    $Output .= '<td><a href="?">Vše</a></td>'.
      '</tr></table><br />';
    */
    $this->QuickNew();

    $db->select_db($Config['Database']['Database']);

    if(array_key_exists('category', $_GET)) $Filter = ' WHERE `category` = '.$_GET['category'];
      else $Filter = '';
    
    $this->db->select_db($Config['Database']['Database']);
    $limit = 5;
    
    if(array_key_exists('page_index', $_GET)) $Page = $_GET['page_index'];
      else $Page = 0; 
    
    $DbResult = $db->query('SELECT COUNT(*) FROM `Article`'.$Filter);
    $DbRow = $DbResult->fetch_row();
    $TotalCount = $DbRow[0];
    
    $DbResult = $db->query('SELECT Article.*, ArticleCategory.Name AS CategoryName FROM Article LEFT JOIN ArticleCategory ON ArticleCategory.Id = Article.Category '.$Filter.' ORDER BY Time DESC LIMIT '.($Page * $Config['Web']['TableRowPerPage']).', '.$Config['Web']['TableRowPerPage']);
    while($Article = $DbResult->fetch_assoc())
    {
      $Content = str_replace('&', '&amp;', $Article['Content']);
      $Content = str_replace('<br>', '<br/>', $Content);
      $Content = str_replace('</br>', '<br/>', $Content);
      $Content = str_replace('</ br>', '<br/>', $Content);
      $Output .= '<table class="NewsQuickInfoTable">'.
          '<tr>'.
          '<td><strong>'.$Article['Title'].'</strong></td>'.
          '<td style="width: 100px">'.$this->HumanDate($Article['Time']).'</td>'.
          '</tr>'.
          '<tr>'.
          '<td colspan="2">'.$Content.'</td>'.
          '</tr>'.
          /*'<tr>'.
          '<td>Sekce : <a href="category='.$Article['Category'].'">'.$Article['CategoryName'].'</a></td>'.
          '<td>'.$Article['Author'].'</td>'.
          '</tr>'.*/
          '</table>'.
          '<br />';
    }
    $Output .= '<div class="Center">'.$this->PageList('page_index', $Page, $TotalCount, $Config['Web']['TableRowPerPage'], 10).'</div>';

    return($Output);
  }

  function QuickNew()
  {
    global $server, $Config, $System, $html;
    
    // Check servers online state.
    $DbResult = $System->Database->query('SELECT COUNT(*) FROM Logon WHERE Online = 1 AND Enabled=1');
    $DbRow = $DbResult->fetch_row();
    $OnlineState = $DbRow[0] > 0; // Report online state if one of all servers is online.

    if(isset($_COOKIE['hof-quick']) AND $_COOKIE['hof-quick'] == 'no')
    {
    } else
    {
      echo('<table class="NewsQuickInfoTable">'.
        '<tr>'.
        '<td><strong>Rychlý přehled</strong></td>'.
        '<td style="width: 100px;">'.date('d.m.Y', time()).'</td>'.
        '</tr>'.
        '<tr>'.
        '<td colspan="2">'.
        '<strong>Server : </strong>'.$server->OnlineStateImage($OnlineState).'<b> (<a href="'.$html->Link('/online-hraci/').'">'.$server->OnlineCharactersCount().' hráčů celkem</a>) | Patch '.$Config['Mangos']['ClientVersion'].' | <a href="'.$html->Link('/pages/realmlist.wtf').'">Realmlist</a> | <a href="'.$html->Link('/server/').'">Server</a> | <a href="'.$html->Link('/svety/').'">Světy</a></b>'.
        '</td></tr></table><br />');
    }
  }  
  
  function GetQueryStringArray()
  {
    $Result = array();
    $Parts = explode('&', $_SERVER['QUERY_STRING']);
    foreach($Parts as $Part)
    {
      if($Part != '')
      {
        $Item = explode('=', $Part);
        if(count($Item) > 1) $Result[$Item[0]] = $Item[1];
          else $Result[$Item[0]] = '';
      }
    }
    return($Result);
  }

  function SetQueryStringArray($QueryStringArray)
  {
    $Parts = array();
    foreach($QueryStringArray as $Index => $Item)
    {
      $Parts[] = $Index.'='.$Item;
    }
    return(implode('&', $Parts));
  }

  // Zobrazení číselný seznamu stránek
  function PageList($QueryStringVar, $Page, $TotalCount, $CountPerPage, $Around = 10)
  { 
    $QueryStringArray = $this->GetQueryStringArray();
    $Count = ceil($TotalCount / $CountPerPage);
    $Result = '';
    if($Count > 1)
    {
      if($Page > 0) 
      {
        $QueryStringArray[$QueryStringVar] = 0;
        $Result .= '<a href="?'.$this->SetQueryStringArray($QueryStringArray).'">&lt;&lt;</a> ';
        $QueryStringArray[$QueryStringVar] = $Page - 1;
        $Result .= '<a href="?'.$this->SetQueryStringArray($QueryStringArray).'">&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>';
        $QueryStringArray[$QueryStringVar] = $i;
        $Result .= '<a href="?'.$this->SetQueryStringArray($QueryStringArray).'">'.($i + 1).'</a> ';
        if($i == $Page) $Result .= '</strong>';
      }
      if($PagesMax < ($Count - 1)) $Result .= ' .. ';
      if($Page < ($Count - 1)) 
      {
        $QueryStringArray[$QueryStringVar] = $Page + 1;
        $Result .= '<a href="?'.$this->SetQueryStringArray($QueryStringArray).'">&gt;</a> ';
        $QueryStringArray[$QueryStringVar] = $Count - 1;
        $Result .= '<a href="?'.$this->SetQueryStringArray($QueryStringArray).'">&gt;&gt;</a>';
      }
    }
    return($Result);
  }
}

?>
