<?php

include_once(dirname(__FILE__).'/Routerboard.php');
include_once(dirname(__FILE__).'/RouterboardAPI.php');
include_once(dirname(__FILE__).'/Generators/Common.php');

// Config actions
include_once(dirname(__FILE__).'/Generators/Signal.php');
include_once(dirname(__FILE__).'/Generators/DHCP.php');
include_once(dirname(__FILE__).'/Generators/DNS.php');
include_once(dirname(__FILE__).'/Generators/Netwatch.php');
include_once(dirname(__FILE__).'/Generators/NetwatchImport.php');
include_once(dirname(__FILE__).'/Generators/FirewallFilter.php');
include_once(dirname(__FILE__).'/Generators/FirewallNAT.php');
include_once(dirname(__FILE__).'/Generators/FirewallMangle.php');
include_once(dirname(__FILE__).'/Generators/Queue.php');

class ModuleNetworkConfigRouterOS extends AppModule
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'NetworkConfigRouterOS';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Mikrotik RouterOS configuration';
    $this->Dependencies = array('NetworkConfig');
  }

  function DoInstall()
  {
  }

  function DoUnInstall()
  {
  }

  function DoStart()
  {
    $this->System->Pages['zdarma'] = 'PageFreeAccess';
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-dns', 'ConfigRouterOSDNS');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-dhcp', 'ConfigRouterOSDHCP');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-signal', 'ConfigRouterOSSignal');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-netwatch', 'ConfigRouterOSNetwatch');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-netwatch-import', 'ConfigRouterOSNetwatchImport');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-filter', 'ConfigRouterOSFirewallFilter');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-nat', 'ConfigRouterOSFirewallNAT');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-mangle', 'ConfigRouterOSFirewallMangle');
    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-queue', 'ConfigRouterOSQueue');
  }
}

class PageFreeAccess extends Page
{
  var $FullTitle = 'Přístup zdarma k Internetu';
  var $ShortTitle = 'Internet zdarma';
  var $ParentClass = 'PagePortal';
  var $AddressList = 'free-access';
  var $Timeout;

  function __construct($System)
  {
    parent::__construct($System);
    $this->Timeout = 24 * 60 * 60;
  }

  function Show()
  {
    $IPAddress = GetRemoteAddress();
    $Output = 'Vaše IP adresa je: '.$IPAddress.'<br/>';
    if(IsInternetAddr($IPAddress)) {
      $Output .= '<p>Internet zdarma je dostupný pouze z vnitřní sítě.</p>';
      return($Output);
    }
    $Time = time();

    $DbResult = $this->Database->select('NetworkFreeAccess', '*', '(IPAddress="'.$IPAddress.
      '") ORDER BY Time DESC LIMIT 1');
    if($DbResult->num_rows > 0)
    {
      $DbRow = $DbResult->fetch_assoc();
      $ActivationTime = MysqlDateTimeToTime($DbRow['Time']);
      if(($ActivationTime + $this->Timeout) < $Time)
      {
        $Activated = false;
      } else $Activated = true;
    } else $Activated = false;

    if(array_key_exists('a', $_GET))
    {
      if($_GET['a'] == 'activate')
      {
        if($Activated == false)
        {
          $DbResult = $this->Database->insert('NetworkFreeAccess',
            array('IPAddress' => $IPAddress, 'Time' => TimeToMysqlDateTime(time()),
            'Configured' => 0));
          $ActivationTime = $Time;
          $Activated = true;
        }
      }
    }
    $Output .= '<div style="text-align:center;"><h3>Vítejte v síti ZděchovNET</h3></div>';
    $Output .= '<p>Pro přístup k Internetu zdarma sdílenou rychlostí 128/128 kbit/s klikněte na odkaz níže.
      Internet bude zpřístupněn po dobu 24 hodin. Po uplynutí této doby je potřeba provést novou aktivaci.</p>';
    $Output .= '<p>Pokud jste platícím zákazníkem a přesto se vám zobrazuje tato stránka, tak pravděpodobně nemáte registrovano v síti vaše klientské zařízení.</p>';

    $PrefixMultiplier = new PrefixMultiplier();
    if($Activated) $Output .= 'Aktivováno. Vyprší za '.$PrefixMultiplier->Add($ActivationTime + $this->Timeout - $Time, '', 4, 'Time');
      else $Output .= '<a href="?a=activate">Aktivovat</a>';

    return($Output);
  }
}

class ScheduleConfigureFreeAccess extends SchedulerTask
{
  function Execute()
  {
    $Output = '';
    $Commands = array();
    $DbResult = $this->Database->select('NetworkFreeAccess', '`Id`, `IPAddress`', '(`Configured`=0)');
    while($DbRow = $DbResult->fetch_assoc())
    {
      $Commands[] = '/ip firewall address-list add address='.$DbRow['IPAddress'].
      ' list=free-access timeout=1d';
    }
    $DbResult = $this->Database->update('NetworkFreeAccess', '`Configured`=0', array('Configured' => 1));

    $Routerboard = new Routerboard($this->System->Config['MainRouter']['HostName']);
    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
    $Routerboard->Debug = true;
    $Routerboard->ExecuteBatch(implode(';', $Commands));

    return($Output);
  }
}