<?php
session_start();
$data_to_rss = array();


function addCounent($start_date,$end_date,$name, $text ,$location)
{ 
    global $data_to_rss;
    $int_array = array();
    $int_array["Start_date"] =  date("H:i", ($start_date));
    $int_array["End_date"] =  date("H:i", ($end_date));
    $int_array["name"]  =htmlentities( (stripslashes($name)));
    $int_array["text"] = htmlentities(stripslashes($text));
    $int_array["location"] = htmlentities(stripslashes($location));
    $int_array["date"] =date("D, d M Y H:i:s O", ($start_date));
    array_push($data_to_rss,$int_array);
}



function str_insert($insertstring, $intostring, $offset)
{
    $part1 = substr($intostring, 0, $offset);
    $part2 = substr($intostring, $offset);
    
    $part1 = $part1 . $insertstring;
    $whole = $part1 . $part2;
    return $whole;
}



function getSslKey($url,$client_id,$client_secret) {
    
    
    $output=null;
    $retval=null;
    exec("cd /tmp; curl --location --request POST '$url'  --header 'Content-Type: application/x-www-form-urlencoded'  --data-urlencode 'grant_type=client_credentials'  --data-urlencode 'client_secret=$client_secret' --data-urlencode 'client_id=$client_id'  --data-urlencode 'scope=https://graph.microsoft.com/.default'
", $output, $retval);
    
    
    return $output[0];
}


function getSslCalenderar($url,$auth) {
    
    
    $output=null;
    $retval=null;
    
    exec("curl --location '$url' --header 'authorization: Bearer $auth'  --header 'Europe/Berlin'  ", $output, $retval);

    
    return $output[0];
}







$client_id = '3fedd094-8f09-419d-9f93-7f363ae08677';
$client_secret = '4x2iNQ7y9ZwZ.tDe..1p.Hfxnkv3qn5qv5';
$redirect_uri = 'https://graph.microsoft.com/v1.0/users/infoskarm.umea@regionvasterbotten.se/calendar/events/';



$url = 'https://login.microsoftonline.com/12517306-9857-4dca-b594-6c370d359eb0/oauth2/v2.0/token';

if($_GET['key'] == "")
{

if($_SESSION["timeout"] >= strtotime("now") || !$_SESSION["timeout"] ) 
{
  

    $result = getSslKey($url,$client_id,$client_secret);
    
    
    $json_key = json_decode($result);
    

    $_SESSION["access_token"] = $json_key -> access_token;
    $_SESSION["timeout"] = strtotime("now") + floatval( $json_key->expires_in);

}

//echo  $_SESSION["access_token"];
// get calender cdata 
$Calenderar_data =  getSslCalenderar($redirect_uri,$_SESSION["access_token"]);

$Calenderar_json = json_decode($Calenderar_data);





foreach ($Calenderar_json->value as $key => $value) {
    
//var_dump($value->end);
    $subject="";
    $subject =$value->subject;
    $date_start =strtotime($value->start->dateTime);
    $date_end =strtotime($value->end->dateTime);
    $location = $value->location->displayName;
    
    //echo $date_end->format(DateTime::ISO8601), PHP_EOL;    
    
    //echo $subject." ".date("Y-md- H:i:s",$date_start)." / ".date("Y-md- H:i:s",$date_end)." loc: ".$location."<br />";
    

    if($date_start >= strtotime(date("Ymd")) &&  ($date_end) <= strtotime("+12 hour") )
   
    {
     
    
        addCounent($date_start ,$date_end,"",$subject,$location);
        
    }
   
    
}


$subject =$Calenderar_json->value[0]->subject;
$date_start =strtotime($Calenderar_json->value[0]->start->dateTime);
$date_end =strtotime($Calenderar_json->value[0]->end->dateTime);
$location = $Calenderar_json->value[0]->location->displayName;




require_once("FeedWriter.php");
//header('Content-Type: application/rss+xml; charset=utf-8');
//1. Instantiate new FeedWriter object, passing the title, description and link
//--------------------------------
$feed = new FeedWriter(
    (utf8_encode('Välkommen till Region Västerbotten')), 	//Feed Title
    'Generate an Atom 1.0', //Feed Description
    'http://www.infotavlorna.se/rss/cal1.php', //Feed Link
    6, //indent
    true, //Use CDATA
    null, //encoding
    false //enable validation
    );

//Enable debug
$feed->debug = true;

//Get the format to display in,
//set to RSS 2.0 as default or if format is not found
$format = RSS_1_0;
if(isset($_GET['format']) && $_GET['format'] != null)
{
    foreach($feed->getFeedFormats() as $curFormat)
    {
        if($curFormat[0] == $_GET['format'])
            $format = $curFormat[1];
    }
}

//Add channel data to the feed
$feed->set_language('SV-se');
$feed->set_date(date("D, d M Y H:i:s O", strtotime("today")),DATE_UPDATED);
$feed->set_author(null, 'info@regionvasterbotten.se','http://regionvasterbotten.se/');
$feed->set_selfLink('http://www.infotavlorna.se/rss/cal1.php');

//Set the item body/content output type to html for the selected output format
$feed->set_feedConstruct($format);
$feed->feed_construct->construct['itemContent']['type'] = 'html';

foreach($data_to_rss as $key => $value){
    
    
    
    
    $text=" <p>".$value["text"]."</p><p>". $value["location"]."</p>";
    $rubrik  = $value["Start_date"] ." -".$value["End_date"];
    //$j++;
    //	if((count($data_to_rss)-1) == $key)
    //	{
    $feed->add_item($rubrik ,$text,"http://regionvasterbotten.se/".$key  );
    $feed->set_date($value["date"], DATE_UPDATED);
    
}




echo $feed->getXML($format);




}

