<?php

// this file reads the rss feed from Logaholic.com and return it in json, 
// it also caches the news for 24 hours

include_once "../common.inc.php";

class LogaholicNews {

    public static function getFeed() {
        global $http;
        $xml=("{$http}://www.logaholic.com/feed/rss");
        $xmlDoc = new DOMDocument();
        if (@!$xmlDoc->load($xml)) {
            die("{}");
        }

        $x=$xmlDoc->getElementsByTagName('item');
        $res=[];

        for ($i=0; $i<=4; $i++) {
            if (!$x->item($i)) {
                continue;
            }
            $item_title=$x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
            $item_link=$x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
            $item_desc=$x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
            $item_date=$x->item($i)->getElementsByTagName('pubDate')->item(0)->childNodes->item(0)->nodeValue;
            $item_date=substr($item_date, 0, -15);
            $res[$i] = array("link" => $item_link, "title" => $item_title, "desc" => $item_desc, "date" => $item_date);            
        }

        $res["md5"] = md5(json_encode($res));
        $res["lastupdate"] = time();    
        setGlobalSetting("LogaholicRSS", json_encode($res));    
        return $res;
    }
}

$news = json_decode(getGlobalSetting("LogaholicRSS","{}"), true);
# We need allow_url_fopen = On
$ini = ini_get('allow_url_fopen');

if(empty($ini)){
    $new = array(
        "link" => "https://www.logaholic.com/manual/installation/php-settings/",
        "title" => "We can't get Logaholic news!",
        "desc" => "<p>You need to have `allow_url_fopen` on to get our news feed.</p>",
        "date" => date("D, d M Y", time())
    );
    $news = array( $new, "md5" => md5(json_encode($new)), "lastupdate" => time() );
}

if (!isset($news["lastupdate"]) || (time()-$news["lastupdate"])>86400 ) {
    if(!empty($ini)){
        $news = LogaholicNews::getFeed();
    }
}
echo json_encode($news);
?>