<?php

include_once('global.php');

class IndexPage extends Page
{
  var $Dependencies = array('News');
  var $FullTitle = '<strong>ZděchovNET</strong> - komunitní počítačová síť';
  var $ShortTitle = 'Rozcestník';
  var $Links = array(
    'main' => array('Síť',
      array('Finance', '/finance/', 'money.gif'),
      array('Statistika', 'http://stat.zdechov.net/centrala/', 'chart.gif'),
      //array('Prohledat sdílení', '/share/', 'prohledavac_sdileni.gif', array('Share', 'Display')),
      array('Seznam uživatelů', '/userlist.php', 'comp.gif'),
      array('Seznam počítačů', '/hostlist.php', 'comp.gif'),
      array('Sdílení souborů', 'http://wiki.zdechov.net/index.php/DC_hub', 'prohledavac_sdileni.gif'),
      array('Historie chatu', '/chat/history.php', 'sunrisechat.gif', array('Chat', 'Display')),
      array('Webový chat', 'http://embed.mibbit.com/?server=game.zdechov.net%3A6667&amp;channel=%23zdechov&amp;forcePrompt=true&amp;charset=utf-8', 'sunrisechat.gif'),
      array('Fotogalerie', '/galerie/', ''),
      array('Diskusní fórum', '/forum/', 'discus.gif'),
      array('WebMail', 'https://mail.zdechov.net/', 'openwebmail.gif'),
      array('Jídelníček', '/jidelna/', 'apple.gif'),
      //array('Televize', 'http://tv.zdechov.net/', ''),
      //array('Telefonní seznam', '/telseznam.php', 'tel.gif'),
      array('Mapa sítě', '/map/', 'clear.gif'),
      array('Otvírací doby', '/otevreno.php', 'otv_doby.gif'),
      array('Topologie sítě', '/is/topologie.php', 'topologie.gif'),
      array('Technické informace', '/network.php', 'tech.gif'),
      array('Webkamera', '/webcam/', 'clear.gif'),
      array('Vnější stránky sítě', 'http://www.zdechov.net/', ''),
      array('Kanály kabelovky', '/tkr.php', 'tv.gif'),
      array('Historie sítě', '/history.php', ''),
      array('Měřič spotřeby', '/merak.php', 'electric.gif'),
      array('Plány do budoucna', '/ukoly.php', ''),
    ),
    'local' => array('Místní organizace',
      array('Obecní úřad', 'http://www.zdechov.cz/', 'obec_zdechov.ico'),
      array('Motokrosová grapa', 'http://zdechovskagrapa.sweb.cz/', ''),
      array('Snowpark', 'http://www.snbzdechov.com/', 'www_snbzdechov_com.ico'),
      array('Sbor dobrovolných hasičů', 'http://www.sdhzdechov.wz.cz/', ''),
      array('TJ Sokol', 'http://fotbal.zdechov.net/', 'socer.gif'),   
      array('Farnost', 'http://farnost.zdechov.net/', 'cfix.gif'),
    ),
    'citizen' => array('Stránky občanů',
       array('Staněk Tatra team', 'http://www.stanek-tatra.cz/', 'www_stanek-tatra_cz.ico'),
       array('Zděchov.eu', 'http://www.zdechov.eu/', 'obec_zdechov.ico'),
     ),
    'search' => array('Vyhledávání',
      array('Google', 'http://www.google.cz/', 'www_google_com.gif'),
      array('Morfeo', 'http://morfeo.centrum.cz/', 'morfeo.png'),
      array('Centrum', 'http://www.centrum.cz/', 'www_centrum_cz.gif'),
      array('Seznam', 'http://www.seznam.cz/', 'www_seznam_cz.gif'),
      array('Atlas', 'http://www.atlas.cz/', 'www_atlas_cz.gif'),
      array('Tiscali', 'http://www.tiscali.cz/', 'www_tiscali_cz.gif'),
    ),
    'usefull' => array('Užitečné',
      array('Mapa ČR', 'http://www.mapy.cz/', 'www_mapy_cz.ico'),
      array('Online TV', 'http://www.tvinfo.cz/live/televize/evropa/cz', 'www_tvinfo_cz.gif'),
      array('Jízdní řády', 'http://jizdnirady.idnes.cz/', 'www_idos_cz.gif'),
      array('TV programy', 'http://tv.atlas.cz/', 'www_atlas_cz.gif'),
      array('ICQ', 'javascript:openClient(\'flash\')', 'www_icq_com.gif'),
      array('Slovníky', 'http://www.slovnik.cz/', 'www_slovnik_cz.ico'),
      array('Počasí', 'http://www.meteopress.cz/', 'pocasi.gif'),
      array('T-Mobile SMS', 'http://www.tzones.cz/', 'www_tzones_cz.gif'),
      array('Knihovna&nbsp;Vsetín', 'http://www.mvk.cz/', 'www_mvk_cz.png'),    
    ),
    'fun' => array('Zábava',
      array('Youtube', 'http://www.youtube.com/', 'www_youtube_com.png'),
      array('Stream.cz', 'http://www.stream.cz/', 'www_stream_cz.png'),
      array('Last.fm', 'http://www.last.fm/', ''),    
    ),
    'hosted' => array('Hostované weby',
      array('Heroes of Fantasy', 'http://www.heroesoffantasy.cz/', 'cube.gif'),
      array('WoW překlad', 'http://wowpreklad.zdechov.net/', 'cube.gif'),
      array('Temné časy', 'http://temnecasy.zdechov.net/', 'cube.gif'),
      array('Sharp MZ community web', 'http://sharp.zdechov.net/', 'clear.gif'),
    ),
    /*'computers' => array('Prodej počítačů',
      array('SOFTCOM', 'http://www.softcom.cz/', 'www_computershop_cz.png'),
      array('Alfacomp', 'http://www.alfacomp.cz/php/zbozi.php?akc=2', 'www_alfacomp_cz.gif'),
      array('Petracomp', 'http://www.petracomp.cz/', 'www_petracomp_cz.png'),
      array('TS Bohemia', 'http://interlink.tsbohemia.cz/', 'www_tsbohemia_cz.png'),
    ),
      */
  );
  
  function ShowLinks($LinkGroup)
  {
    $Result = '';
    //foreach($this->Links as $LinkGroup)
    //{
      $Title = array_shift($LinkGroup);
      //$Result .= '<h3>'.$Title.'</h3>';
      foreach($LinkGroup as $Link)
      {
        if($Link[2] == '') $Link[2] = 'clear.gif';
        if(substr($Link[1], 0, 4) != 'http') $Link[1] = $this->System->Config['Web']['RootFolder'].$Link[1];
        if(!isset($Link[3]) or (isset($Link[3]) and $this->System->Modules['User']->CheckPermission($Link[3][0], $Link[3][1])))
        
        $Result .= '<img alt="'.$Link[0].'" src="images/favicons/'.$Link[2].'" width="16" height="16" /> <a href="'.$Link[1].'">'.$Link[0].'</a><br />';
      }
    //}
    return($this->Panel($Title, $Result));
  }

  function InfoBar()
  {
    global $Config;
    
    $Database->select_db($Config['Database']['Database']);

    $Output2 = '';

    $DbResult = $this->Database->query('SELECT COUNT(*) FROM NetworkDevice LEFT JOIN NetworkDeviceType ON NetworkDeviceType.Id = NetworkDevice.Type WHERE NetworkDeviceType.ShowOnline = 1');
    $DbRow = $DbResult->fetch_array();
    $TotalComputers = $DbRow[0];

    $DbResult = $this->Database->query('SELECT COUNT(*) FROM NetworkDevice LEFT JOIN NetworkDeviceType ON NetworkDeviceType.Id = NetworkDevice.Type WHERE (NetworkDeviceType.ShowOnline = 1) AND (NetworkDevice.Online = 1)');
    $DbRow = $DbResult->fetch_array();
    $OnlineComputers = $DbRow[0];

    $Output = '<img alt="" src="images/favicons/comp.gif" width="16" height="16" /> '.$OnlineComputers.' / '.$TotalComputers.' &nbsp;  &nbsp; ';

    $DbResult = $this->Database->select('Member', 'COUNT(*)', 'MemberState=0');
    $DbRow = $DbResult->fetch_array();
    $TotalUser = $DbRow[0];

    $DbResult = $this->Database->query('SELECT COUNT(DISTINCT(Member)) FROM NetworkDevice LEFT JOIN NetworkDeviceType ON NetworkDeviceType.Id = NetworkDevice.Type WHERE NetworkDeviceType.ShowOnline = 1 AND NetworkDevice.Online = 1');
    $DbRow = $DbResult->fetch_array();
    $OnlineUser = $DbRow[0];

    $Output .= '<img alt="" src="images/favicons/house.gif" width="16" height="16" /> '.$OnlineUser.' / '.$TotalUser.' &nbsp;  &nbsp; ';

    $NetworkUsage = 0;
    $Output .= '<img alt="" src="images/favicons/usage.gif" width="16" height="16" /> '.$NetworkUsage.' % &nbsp;  &nbsp; ';

    //$Output .= 'Server běží: '.$this->GetServerUptime().' &nbsp;  &nbsp; ';

    if($this->System->Modules['User']->CheckPermission('Finance', 'DisplaySubjectState'))
    {
      $DbResult = $this->Database->select('Subject', 'Money', 'Id=(SELECT Subject FROM Member WHERE Id=(SELECT Member FROM User WHERE Id='.$this->System->Modules['User']->User['Id'].'))');
      if($DbResult->num_rows > 0)
      {
        $DbRow = $DbResult->fetch_assoc();
        $Output2 .= ' &nbsp;  &nbsp; <img alt="" src="images/favicons/money.gif" width="16" height="16" /> '.$DbRow['Money'].' Kč';
      }
    }

    $Output = '<div class="Navigation"><span class="MenuItem">'.$Output.'</span><div class="MenuItem2">&nbsp;'.$Output2.'</div></div>';
    return($Output);
  }

  function UserPanel()
  {
    $Output = '<a href="'.$this->System->Config['Web']['RootFolder'].'/?Action=UserOptions">Nastavení uživatele</a><br />';
    if($this->System->Modules['User']->CheckPermission('Finance', 'MemberOptions')) 
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'?Action=MemberOptions">Nastavení domácnosti</a><br />';
    if($this->System->Modules['User']->CheckPermission('Finance', 'DisplaySubjectState')) 
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/finance/user_state.php">Stav financí</a><br />';
    if($this->System->Modules['User']->CheckPermission('Network', 'RegistredHostList')) 
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/network/user_hosts.php">Registrované počítače</a><br />';
    if($this->System->Modules['User']->CheckPermission('News', 'Insert')) 
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/aktuality/?action=add">Vložení aktuality</a><br />';
    if($this->System->Modules['User']->CheckPermission('EatingPlace', 'Edit'))
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/jidelna/menuedit.php">Editace jídelníčků</a><br />';
    if($this->System->Modules['User']->CheckPermission('Finance', 'Manage'))
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/finance/manage.php">Správa financí</a><br />';
    if($this->System->Modules['User']->CheckPermission('Network', 'Administration'))
      $Output .= '<a href="'.$this->System->Config['Web']['RootFolder'].'/network/administration.php">Správa sítě</a><br />';
    return($Output);
  }

  function WebcamPanel()
  {
    $Output = $this->System->Modules['Webcam']->ShowImage();
    return($Output);
  }

  function OnlineHostList()
  {
    $Output = '<span style="font-size: smaller;">';
    $DbResult = $this->Database->query('SELECT NetworkDevice.Name FROM NetworkDevice LEFT JOIN NetworkDeviceType ON NetworkDeviceType.Id = NetworkDevice.Type WHERE (NetworkDeviceType.ShowOnline = 1) AND (NetworkDevice.Online = 1) ORDER BY NetworkDevice.Name');
    while($Device = $DbResult->fetch_array())
    {
      $Output .= $Device['Name'].'<br />';
    }
    $Output .= '</span>';
    return($Output);
  }

  function ShowBadPayerList()
  {
    $Output .= '<div class="PanelTitle">Dlužníci:</div><span style="font-size: smaller;">';
    $DbResult = $Database->select('Subject', 'Name', 'Money < 0 ORDER BY Money');
    while($Row = $DbResult->fetch_array())
    {
      $Output .= $Row['Name'].'<br />';
    }
    $Output .= '</span>';
    return($Output);
  }

  function GetServerUptime()
  {
    $Data = explode(' ', exec('uptime'));
    $Data = array_slice($Data, 3, -8);
    $Uptime = '';
    foreach($Data as $Item)
    {
      if(strpos($Item, ':')) $Uptime .= substr($Item, 0, -1).' hodin';
      else $Uptime .= $Item.' ';
    }
    $Uptime = str_replace('2 days,', '2 dny a', $Uptime);
    $Uptime = str_replace('3 days,', '3 dny a', $Uptime);
    $Uptime = str_replace('4 days,', '4 dny a', $Uptime);
    $Uptime = str_replace('days,', 'dní a', $Uptime);
    $Uptime = str_replace('day,', 'den a', $Uptime);
    $Uptime = str_replace('min,', 'minut', $Uptime);
    return($Uptime);
  }
  
  function Panel($Title, $Content, $Menu = array())
  {
    if(count($Menu) > 0) 
      foreach($Menu as $Item)
        $Title .= '<div class="Action">'.$Item.'</div>';
    return('<div class="Panel"><div class="Title">'.$Title.'</div><div class="Content">'.$Content.'</div></div>');
  }

  function Show()
  {
    global $Database, $Config, $User;

    $Output = '';
    if(array_key_exists('Action', $_GET))
    {
      if($_GET['Action'] == 'CustomizeNewsSave')
      {
        $Output .= $this->System->Modules['News']->CustomizeSave();
      } else
      if($_GET['Action'] == 'LoginForm')
      {
        $Form = new Form('UserLogin');
        $Form->OnSubmit = '?Action=Login';
        $Output .= $Form->ShowEditForm();
        $Output .= '<div class="Centred"><a href="?Action=UserRegister">Registrovat se</a> '.
        '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
      } else
      if($_GET['Action'] == 'Login')
      {
        $Form = new Form('UserLogin');
        $Form->OnSubmit = '?Action=Login';
        $Result = $this->System->Modules['User']->Login($_POST['Username'], $_POST['Password']);
        $Output .= $this->SystemMessage('Přihlášení', $Result);
        if($Result <> USER_LOGGED_IN)
        {
          $Form->LoadValuesFromForm();
          $Form->Values['Password'] = '';
          $Output .= $Form->ShowEditForm();
          $Output .= '<div class="Centred"><a href="?Action=UserRegister">Registrovat se</a> '.
            '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
        }
      } else 
      if($_GET['Action'] == 'Logout')
      {
        $Output .= $this->SystemMessage('Odhlášení', $this->System->Modules['User']->Logout());
      } else
      if($_GET['Action'] == 'UserOptions')
      { 
        $UserOptions = new Form('UserOptions');
        $UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        $UserOptions->OnSubmit = '?Action=UserOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      } else
      if($_GET['Action'] == 'UserOptionsSave')
      {
        $UserOptions = new Form('UserOptions', array());
        $UserOptions->LoadValuesFromForm();
        $UserOptions->SaveValuesToDatabase($this->System->Modules['User']->User['Id']);
        $Output .= $this->SystemMessage('Nastavení', 'Nastavení uloženo.');
        $this->System->Modules['Log']->NewRecord('User', 'Nastavení uživatele změněno', $UserOptions->Values['Name']);
        $UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        $UserOptions->OnSubmit = '?Action=UserOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      }
      if($_GET['Action'] == 'UserRegister')
      {
        $Form = new Form('UserRegister');
        $Form->LoadValuesFromForm();
        $Form->OnSubmit = '?Action=UserRegisterSave';
        $Output .= $Form->ShowEditForm();
      } else
      if($_GET['Action'] == 'UserRegisterConfirm')
      {
        $Output .= $this->SystemMessage('Potvrzení registrace', $this->System->Modules['User']->RegisterConfirm($_GET['User'], $_GET['H']));
      } else
      if($_GET['Action'] == 'PasswordRecovery')
      {
        $Form = new Form('PasswordRecovery');
        $Form->OnSubmit = '?Action=PasswordRecovery2';
        $Output .= $Form->ShowEditForm();
      } else
      if($_GET['Action'] == 'PasswordRecovery2')
      {
        $Form = new Form('PasswordRecovery');
        $Form->LoadValuesFromForm();
        $Result = $this->System->Modules['User']->PasswordRecoveryRequest($Form->Values['Name'], $Form->Values['Email']);
        $Output .= $this->SystemMessage('Obnova hesla', $Result);
        if($Result <> USER_PASSWORD_RECOVERY_SUCCESS)
        {
          $Output .= $Form->ShowEditForm();
        }        
      } else
      if($_GET['Action'] == 'PasswordRecoveryConfirm')
      {
        $Output .= $this->SystemMessage('Obnova hesla', $this->System->Modules['User']->PasswordRecoveryConfirm($_GET['User'], $_GET['H'], $_GET['P']));
      } else
      if($_GET['Action'] == 'UserRegisterSave')
      {
        $Form = new Form('UserRegister', array());
        $Form->LoadValuesFromForm();
        $Result = $this->System->Modules['User']->Register($Form->Values['Login'], $Form->Values['Password'], $Form->Values['Password2'], $Form->Values['Email'], $Form->Values['Name'], $Form->Values['PhoneNumber'], $Form->Values['ICQ']);
        $Output .= $this->SystemMessage('Registrace nového účtu', $Result);
        if($Result <> USER_REGISTRATED) 
        {
          $Form->OnSubmit = '?Action=UserRegisterSave';
          $Output .= $Form->ShowEditForm();
        }
      } else
      if($_GET['Action'] == 'MemberOptions')
      {
        $UserOptions = new Form('MemberOptions');
        $DbResult = $this->Database->query('SELECT Member.Id, Member.InternetTariffNextMonth, Member.FamilyMemberCount, Member.BillingPeriodNext, Subject.Name, Subject.AddressStreet, Subject.AddressTown, Subject.AddressPSC, Subject.IC, Subject.DIC FROM Member JOIN Subject ON Subject.Id = Member.Subject WHERE Member.Id='.$this->System->Modules['User']->User['Member']);
        $DbRow = $DbResult->fetch_array();
        foreach($UserOptions->Definition['Items'] as $Index => $Item)
        {
          $UserOptions->Values[$Index] = $DbRow[$Index];
        }
        $UserOptions->OnSubmit = '?Action=MemberOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      } else
      if($_GET['Action'] == 'MemberOptionsSave')
      {
        $UserOptions = new Form('MemberOptions');
        $UserOptions->LoadValuesFromForm();
        if($UserOptions->Values['FamilyMemberCount'] < 0)
          $UserOptions->Values['FamilyMemberCount'] = 0;
        if($UserOptions->Values['BillingPeriodNext'] < 2)
          $UserOptions->Values['BillingPeriodNext'] = 2;
          
        $DbResult = $this->Database->update('Member', 'Id='.$this->System->Modules['User']->User['Member'], array('InternetTariffNextMonth' => $UserOptions->Values['InternetTariffNextMonth'], 'FamilyMemberCount' => $UserOptions->Values['FamilyMemberCount'], 'BillingPeriodNext' => $UserOptions->Values['BillingPeriodNext']));
        $DbResult = $this->Database->query('SELECT Subject FROM Member WHERE Id='.$this->System->Modules['User']->User['Member']);
        $Member = $DbResult->fetch_assoc();
        $DbResult = $this->Database->update('Subject', 'Id='.$Member['Subject'], array('Name' => $UserOptions->Values['Name'], 'AddressStreet' => $UserOptions->Values['AddressStreet'], 'AddressTown' => $UserOptions->Values['AddressTown'], 'AddressPSC' => $UserOptions->Values['AddressPSC'], 'IC' => $UserOptions->Values['IC'], 'DIC' => $UserOptions->Values['DIC']));
        $Output .= $this->SystemMessage('Nastavení', 'Nastavení domácnosti uloženo.');
        $this->System->Modules['Log']->NewRecord('Member+Subject', 'Nastavení člena/subjektu změněno', $UserOptions->Values['Name']);
        $DbResult = $this->Database->query('SELECT Member.Id, Member.InternetTariffNextMonth, Member.FamilyMemberCount, Member.BillingPeriodNext, Subject.Name, Subject.AddressStreet, Subject.AddressTown, Subject.AddressPSC, Subject.IC, Subject.DIC FROM Member JOIN Subject ON Subject.Id = Member.Subject WHERE Member.Id='.$this->System->Modules['User']->User['Member']);
        $DbRow = $DbResult->fetch_array();
        foreach($UserOptions->Definition['Items'] as $Index => $Item)
        {
          $UserOptions->Values[$Index] = $DbRow[$Index];
        }
        $UserOptions->OnSubmit = '?Action=MemberOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      }
    }

    $Database->select_db($Config['Database']['Database']);

    //$Output .= $this->InfoBar();
    $Output .= '<table id="MainTable"><tr><td valign="top">';
    $Output .= $this->ShowLinks($this->Links['main']);
    $Output .= $this->ShowLinks($this->Links['hosted']);
    $Output .= '</td><td valign="top">';
    $Output .= $this->ShowLinks($this->Links['search']);
    $Output .= $this->ShowLinks($this->Links['usefull']);
    $Output .= $this->ShowLinks($this->Links['fun']);
    $Output .= $this->ShowLinks($this->Links['local']);
    $Output .= $this->ShowLinks($this->Links['citizen']);
    $Output .= '</td><td id="NewsColumn" valign="top">';
    $Output .= $this->Panel('Aktuality', $this->System->Modules['News']->Show(), array('<a href="?Action=CustomizeNews">Upravit</a>'));
    $Output .= '</td><td valign="top">';
    if($this->System->Modules['User']->User['Id'] != $this->System->Modules['User']->AnonymousUserId) 
    $Output .= $this->Panel('Nabídka uživatele', $this->UserPanel());
    $Output .= $this->Panel('Kamery', $this->WebcamPanel());
    $Output .= $this->Panel('Online počítače', $this->OnlineHostList());
    $Output .= '<br />';
    $Output .= '</td></tr></table>';
    //if(IsInternetAddr()) echo('Internet'); else echo('LAN');
    return($Output);
  }
}

$System->AddModule(new IndexPage());
$System->Modules['IndexPage']->GetOutput();

?>
