<?php
 
// Specifikace API: http://www.fio.cz/docs/cz/API_Bankovnictvi.pdf

include('GPC.php');
 
class FioAPI
{
  var $Token;
  var $Encoding;
  
  function __construct()
  {
    $this->Encoding = 'utf-8';
  }
 
  function Import($TimeFrom, $TimeTo)
  {
    if($this->Token == '') throw new Exception('Missing value for Token property.');
 
    // URL format: https://www.fio.cz/ib_api/rest/periods/{token}/{datum od}/{datum do}/transactions.{format}
    $fp = fsockopen('ssl://www.fio.cz', 443, $errno, $errstr, 30);
    if(!$fp) 
    {
      throw new Exception('Connection error: '.$errstr);
    } else 
    {
      // Send request
      $RequestURL = '/ib_api/rest/periods/'.$this->Token.'/'.
        date('Y-m-d', $TimeFrom).'/'.date('Y-m-d', $TimeTo).'/transactions.gpc';
      $Request = "GET ".$RequestURL." HTTP/1.1\r\n";
      $Request .= "Host: www.fio.cz\r\n";
      $Request .= "User-Agent: PHP Script\r\n";
      $Request .= "Content-Type: text/html\r\n";
      $Request .= "Connection: Close\r\n\r\n";
      fwrite($fp, $Request);
 
      // Read response
      $Response = array();
      while(!feof($fp)) 
        $Response .= trim(fgets($fp, 1024))."\n";
      fclose($fp);      
      $Response = iconv('windows-1250', $this->Encoding, $Response);
      $Response = explode("\n", $Response);
 
      // Strip HTTP header
      while($Response[0] != '') array_shift($Response);
      array_shift($Response); // Remove empty line
      //echo(implode("\n", $Response));
 
      // Parse all GPC lines
      $GPC = new GPC();
      $Result = array();
      foreach($Response as $Index => $Line)
      {
	if(($Index == 0) and (substr($Line, 0, strlen(GPC_TYPE_REPORT)) != GPC_TYPE_REPORT)) $this->NoValidDataError($Response);
        $GPCLine = $GPC->ParseLine($Line);
        if($GPCLine != NULL) $Result[] = $GPCLine;
      }
      return($Result);
    }
  }
 
  function NoValidDataError($Response)
  {
    // Try to get error message
    // If something go wrong fio show HTML login page and display error message
	$Response = implode('', $Response);
    $ErrorMessageStart = '<div id="oldform_warning">';
    if(strpos($Response, $ErrorMessageStart) !== false) 
	{
	  $Response = substr($Response, strpos($Response, $ErrorMessageStart) + strlen($ErrorMessageStart));
	  $ErrorMessage = trim(substr($Response, 0, strpos($Response, '</div>')));
	} else $ErrorMessage = '';
	throw new Exception('No valid GPC data: '.$ErrorMessage);
  }
}
 
?>
