hackcal/index.php

66 lines
No EOL
2.5 KiB
PHP

<?php
# requirements
require_once 'include/config.php';
require_once 'include/ICal/ICal.php';
require_once 'include/ICal/Event.php';
# Fix relative path
$cachefile = 'cache/'.$cachefile;
# Init Calendar
$ical = new \ICal\ICal();
# Caching and load calendar
if (!file_exists($cachefile) || (filemtime($cachefile) + $cachetime < time())) {
$context = stream_context_create(['http' => ['timeout' => 10]]);
$ical_str = @file_get_contents($ical_url, false, $context);
if ($ical_str !== false && strpos($ical_str, 'BEGIN:VCALENDAR') !== false) {
file_put_contents($cachefile, $ical_str);
$ical->initString($ical_str);
} else {
if (file_exists($cachefile)) $ical->initFile($cachefile);
}
} else {
$ical->initFile($cachefile);
}
# Load calendar entries
$period_val = filter_input(INPUT_GET, 'period', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 12]]) ?: 1;
$filter = filter_input(INPUT_GET, 'filter', FILTER_SANITIZE_SPECIAL_CHARS); // FILTER_UNSAFE_RAW
$events = $ical->sortEventsWithOrder($ical->eventsFromInterval($period_val . ' month'));
$result = [];
foreach ($events as $event) {
$cat = $event->categories ?? '';
if ($filter && stripos($cat, $filter) === false) continue;
if (stripos($cat, "hidden") !== false) continue;
$start = new DateTime($event->dtstart);
$end = new DateTime($event->dtend);
$uid = $event->uid;
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$date = $dt->format("Y-m-d");
$result[$date][$uid] = [
"dtstart" => $start->format(DateTime::ATOM), //$ical->iCalDateToDateTime($event->dtstart_array[3])->format(DateTime::ATOM);
"dtend" => $end->format(DateTime::ATOM), //$ical->iCalDateToDateTime($event->dtend_array[3])->format(DateTime::ATOM);
"datestr" => (isset($event->dtstart_array[0]["VALUE"]) && $event->dtstart_array[0]["VALUE"] == 'DATE') ? '' : $start->format('H:i'),
"summary" => mb_strimwidth($event->summary, 0, 255, "..."),
"location" => mb_strimwidth($event->location ?? '', 0, 255, "..."),
"description" => mb_strimwidth($event->description ?? '', 0, 255, "...")
];
if(!empty($cat)) $result[$date][$uid]["categories"] = $cat;
}
}
# Allow every page to load this json
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=utf-8");
echo json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);