<?php
/*
RSSAd class - knihovna pro zobrazování článků ze systému RSSAd
Copyright (C) 2006 Acci

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
class rssad {
  var $id; // ID přidělené v systému RSSAd
  var $uri; // Adresa, na které se zobrazuje adresa
  var $pocet = 5; // Počet zobrazovaných
  var $cache = true; // Zapnout cache
  var $cache_cesta; // Kde ukládat cache
  var $cache_cas = '30'; // Počet minut, po které se budou články uchovávat v cache
  var $server = 'http://rssad.mazlo.org/get.php'; // Odkud stahovat soubor s reklamou
  var $kodovani = 'UTF-8'; // kódování webu
  var $curl = false; // Používat knihovnu CURL, pokud je zakázáno otvírání vzdálených souborů



  function _cache($soubor) {
    if(!$this->cache)
      return false;

    // nastavení


    $hash = md5($soubor).'.html';
    $cas = time()-60*$this->cache_cas;

    $obsah = is_file($this->cache_cesta.$hash) ? $this->_get($this->cache_cesta.$hash) : null;
    if(!$obsah)
      return false;
    $obsah = unserialize($obsah); // array


    if($obsah['cas'] > $cas)
      return $obsah['data'];
    else

      return false;
  }

  function _get($soubor, $vzdaleny=false) {
    if($this->curl && $vzdaleny) {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $soubor);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $obsah = curl_exec($curl);
      curl_close($curl);
    }
    else
      $obsah = @file_get_contents($soubor);
    if(!$obsah)
      return false;
    return $obsah;
  }

  function _put($filename, $s) {
    if (function_exists('file_put_contents'))
      file_put_contents($filename, $s);
    else {
      $f = fopen($filename, 'w');
      flock($f, 1);
      fwrite($f, $s);
      flock($f, 3);
      fclose($f);
    }
  }

  function zobraz() {
    $soubor = $this->server.'?id='.$this->id.'&limit='.$this->pocet.'&uri='.$this->uri;
    $obsah = $this->_cache($soubor);
    if($obsah)
      echo $obsah;
    else {
      $obsah = $this->_get($soubor, true);
      if($this->kodovani != 'UTF-8')
        $obsah = iconv('UTF-8', $this->kodovani, $obsah);
      echo $obsah;
      $tofile = serialize(array('cas' => time(), 'data' => $obsah));
      $this->_put($this->cache_cesta.md5($soubor).'.html', $tofile);
    }

  }
}


?>