<?php
/*
*    get-invia-xml.php    v0.3            Milan Kryl | http://kryl.info | 3. 7. 2007
*    --------------------------------------------------------------------------------------------------
*    Soubor pro stahovani XML exportu serveru Invia a jeho zobrazeni v PHP.
*    Kod je mozne dale upravovat a sirit bez omezeni. Puvodni kod a pripadne
*    aktualizace lze nalezt na adrese http://kryl.info/invia/
*
*    INSTRUKCE PRO INSTALACI
*    =========================
*    1. nahradte nize text URL_XML_SOUBORU_INVIA adresou vygenerovanou v administracnim rozhrani Invia.cz
*    2. nakopirujte tento soubor na server
*    3. vytvorte adresar pro docasne ukladani reklamy invia-cache
*    4. pridejte adresari prava pro zapis (CHMOD 777 / rwxrwxrwx)
*    5. vlozte nasledujici kod do PHP stranky, kde chcete nabidky zobrazovat
        <?php
            $invia_select = 'invia';        // nastav jmeno odkazu v konfiguraci
            // $invia_maxcount = 10;        // nastaveni maximalniho poctu polozek
            // $invia_config[] = "NOUNIQUEPHOTO";    // vystup NEfiltrovat unikatni fotografie
            // $invia_config[] = "NOSORT";        // vystup NEtridit dle data
            require($_SERVER['DOCUMENT_ROOT'].'/get-invia-xml.php');
        ?>
*
*    6. Pritomnost parametru v promenne invia_config zamezi trideni dle data odjezdu NOSORT nebo
*       zunikatneni dle fotografie NOUNIQUEPHOTO. Vychozi nastaveni tridi a odstranuje duplicity
*
*    WHAT'S NEW
*    =======================
*     8. 5. 2008    Pridano parsovani poplatku (tax)
*    28. 3. 2008    Osetreni neexistujiciho souboru v cache pri nepovedenem importu
*    26.12. 2007    FIX pouziti cache, kdyz invia nefunguje
*    23.12. 2007    zobrazeni terminu i kdy je aktivovan NOSORT
*    22.12. 2007    oprava pro vkladani do Wordpressu pres Exec-PHP
*     3. 7. 2007    uprava formatu terminu term => from, to, destination & price, currency
*    26. 6. 2007    podpora vice XML souboru
*/


if ( count($INVIA_CONFIG) == )
    
$INVIA_CONFIG = array(
            
"invia" => "URL_XML_SOUBORU_INVIA",
            
"empty" => ""    // ignorujte :) pro pridani dalsiho zaznamu kopirujte predchozi radek
                    // a vyplnte jine pojmenovani (viz vychozi "invia")
        
);
if (!isset(
$invia_cache)) {
    
$CACHE_DIRECTORY $_SERVER['DOCUMENT_ROOT'].'/invia-cache';    // jmeno adresare (bez koncoveho lomitka!), kde jsou docasne ukladany stazene XML kody (na 4 hodiny)
} else {
    
$CACHE_DIRECTORY $invia_cache;
}

/*
*    NEMODIFIKUJTE do dalsiho odelovace
*
*    --------------------------------------------------------------------------------------------------
*
*
*/


    
if ($INVIA_CONFIG[$invia_select] == '') {
        
// get first if none selected
        
list($invia_select$input_url) = each($INVIA_CONFIG);
    } else {
        
$input_url $INVIA_CONFIG[$invia_select];
    }

    
$local_xml_file $CACHE_DIRECTORY.'/'.$invia_select.'.xml';

    
$defined_items = array("hotel","image""destination""from""to""price""tax""food""url");
    
$items_structure = array(
                    
"destination" => array("country""locality")
                );

    
$currency = array(
                    
"" => ",-",
                    
"CZK" => "K&#x010D;"
                
);

    if (!
file_exists($CACHE_DIRECTORY)) die('<b>CHYBA:</b> vytvorte adresar '.$CACHE_DIRECTORY.' - postupujte podle navodu ve skriptu!');
    if (!
is_writable($CACHE_DIRECTORY)) die('<b>CHYBA:</b> nastavte adresari prava zapisu - postupujte podle navodu ve skriptu!');



    
/* thanks to dgx ! http://www.dgx.cz/trine/ */
    // function 'file_put_contents' is missing in PHP 4
    
if (!function_exists('file_put_contents')) {
      function 
file_put_contents($fileName$s)
      {
        
$f fopen($fileName'w');
        
fwrite($f$s);
        
fclose($f);
      }
    }


    function 
get_content_from_url($url$timeout 3) {

        
$result "";
        
$url parse_url($url);

        if (
$fs = @fsockopen ($url['host'], 80)) {

            if ( 
function_exists("socket_set_timeout") ) {
                
socket_set_timeout($fs$timeout0);
            } else if ( 
function_exists("stream_set_timeout") ) {
                
stream_set_timeout($fs$timeout0);
            }

            
$http_get_cmd "GET ".$url['path']."?".$url['query']." HTTP/1.0\r\n".
                            
"Host: ".$url['host']."\r\n".
                            
"Connection: Close\r\n\r\n";

            
fwrite ($fs$http_get_cmd);
            while (!
feof($fs)) {
                
$result .= @fread($fs40960);
            }
            
fclose($fs);

            return 
$result;

        } else {

            return 
false;

        }
    }

    function 
parse_invia_xml($xml_content$defined_items$items_structure) {

        
preg_match_all('~<offer(.*?)>(.*?)</offer>~si'$xml_content$items);

        
$offer $items[2];

        
$items = array();

        foreach (
$offer as $k => $v) {
            
// parse each offer
            
$off = array();
            foreach (
$defined_items as $l => $u) {

                
preg_match("~<$u(.*?)>(.*?)</$u>~si"$v$temp);

                
// parse atributes
                
if ($temp[1] != '') {
                    
preg_match_all('~[ ]*([^ ]*)="([^"]*)"~si'$temp[1], $params);

                    foreach (
$params[1] as $m => $w) {
                        
$off[$u."_".$w] = $params[2][$m];
                    }
                }
                
// parse value and store

                
if ( (is_array($items_structure[$u])) && (count($items_structure[$u]) > 0) ) {

                    foreach (
$items_structure[$u] as $j) {

                        
preg_match("~<$j(.*?)>(.*?)</$j>~si"trim($temp[2]), $stemp);

                        if (
$stemp[1] != '') {
                            
preg_match_all('~[ ]*([^ ]*)="([^"]*)"~si'$stemp[1], $params);

                            foreach (
$params[1] as $m => $w) {
                                
$off[$j."_".$w] = $params[2][$m];
                            }
                        }
                        if (
$stemp[2] != ''$off[$j] = trim($stemp[2]);
                    }
                } else {
                if (
$temp[2] != ''$off[$u] = trim($temp[2]);

                }
            }
            if ( 
$off[$defined_items[0]] != '' $items[] = $off;
        }

        return 
$items;
    }

    if (
         ( !
file_exists($local_xml_file) || filemtime($local_xml_file) < (time() - 3600*24) || filesize($local_xml_file) < 15 ) ) {

        
$offers = array();
        if ( ( 
$xml_content get_content_from_url($input_url) ) == true ) {

            
$offers parse_invia_xml($xml_content$defined_items$items_structure);
        }
        if (
count($offers) > 0) {
            
file_put_contents($local_xml_fileserialize($offers));
        }
    } 

    if ( (
file_exists($local_xml_file)) && (count($offers) < 1) && (( $xml_content file_get_contents($local_xml_file) ) == true ) ) {
        
$offers unserialize($xml_content);
    }
    

    
// uniq offers
    
if (! is_array($invia_config) || ! in_array("NOUNIQUEPHOTO"$invia_config) ) {
        
$uniq_offers = array();
        foreach (
$offers as $k => $v) {
            
$uniq_offers[$v['image']] = $v;
        }
        
$offers $uniq_offers;
    }

    
// parse terms
    
$sort_offers = array();
    
$i 0;
    foreach (
$offers as $k => $v) {
        
// parse FROM date
        
if ( preg_match('/([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})/'$v['from'], $t) ) {
            
$fy $t[1];
            
$fm $t[2];
            
$fd $t[3];
        }

        
// parse TO date
        
if ( preg_match('/([0-9]{2,4})-([0-9]{1,2})-([0-9]{1,2})/'$v['to'], $t) ) {
            
$ty $t[1];
            
$tm $t[2];
            
$td $t[3];
        }


        if ( (
$fy != '') && ($ty != '') ) {

            
$timehash $ty.$tm.$td.$fy.$fm.$fd.'-'.$i;
            
$fd intval($fd);
            
$fm intval($fm);
            
$fy intval($fy);

            
$td intval($td);
            
$tm intval($tm);
            
$ty intval($ty);

            
$v['term'] = $fd.'.'.$fm.'.'.(($fy != $ty)?$fy:"").'-'.$td.'.'.$tm.'.'.$ty.' ';

            
$sort_offers[$timehash] = $v;
            
$offers[$k] = $v;
            
$i++;
        }
    }
    
// sort offers
    
if (! is_array($invia_config) || ! in_array("NOSORT"$invia_config) ) {
        
$offers $sort_offers;
        
ksort($offers);
    }

    if (
$invia_maxcount 0$offers array_slice($offers0$invia_maxcount);


if (
count($offers) > 0) {

/*
*    kod nize MUZETE zmenit pro zmenu formatu vypisu
*    --------------------------------------------------------------------------------------------------
*    pripadne kod nize smazte a ve strance pokracujte ve zpracovani vytvoreneho pole $offers
*/

        
echo '<table class="invia-table" style="width: 100%;">';
        foreach (
$offers as $k => $v) {
            echo 
"<tr>";
            echo 
'<td><a href="'.$v['url'].'"><img src="'.$v['image'].'" alt="'.$v['image_alt'].'" class="foto" /></a></td>';
            echo 
"<td><h3><a href=\"".$v['url']."\">".$v['hotel']."</a></h3>".
                 
"".$v['food']."<br />".
                 
"".$v['term']."<br />".
                 
"".$v['price']." ".$currency[$v['price_currency']]."<br />";
                 
"</td>";
            echo 
"</tr>";
        }
        echo 
"</table>";

/*
*    --------------------------------------------------------------------------------------------------
*/

}    // end if (count($offers) > 0)

?>