-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathics.php
More file actions
399 lines (351 loc) · 15 KB
/
Copy pathics.php
File metadata and controls
399 lines (351 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<?php
// ============================================================
// CONFIG
//
// Usage: ics_transform.php?cal=mycalendar&pw=secret
//
// Reads: mycalendar.yaml (password, source URL, and rules)
// ============================================================
require_once __DIR__ . '/yaml.php';
// ── ?cal parameter ──────────────────────────────────────────
$cal = $_GET['cal'] ?? '';
if ($cal === '' || !preg_match('/^[a-zA-Z0-9_-]+$/', $cal)) {
http_response_code(400);
header('Content-Type: text/plain');
exit('Missing or invalid "cal" parameter.');
}
// ── Load calendar YAML ──────────────────────────────────────
$yamlFile = __DIR__ . '/' . $cal . '.yaml';
if (!is_readable($yamlFile)) {
http_response_code(404);
header('Content-Type: text/plain');
exit('Calendar "' . htmlspecialchars($cal) . '" not found.');
}
$config = Spyc::YAMLLoad($yamlFile);
define('PASSWORD', $config['password'] ?? '');
define('SOURCE_ICS', $config['source_ics'] ?? '');
$rules = $config['rules'] ?? [];
// ── AUTH ────────────────────────────────────────────────────
if (!isset($_GET['pw']) || $_GET['pw'] !== PASSWORD) {
http_response_code(401);
header('Content-Type: text/plain');
exit('Unauthorized');
}
$debug = isset($_GET['debug']);
$text = isset($_GET['text']);
// ============================================================
// FETCH SOURCE
// ============================================================
$raw = @file_get_contents(SOURCE_ICS);
if ($raw === false) {
http_response_code(502);
header('Content-Type: text/plain');
exit('Could not fetch source calendar.');
}
// ============================================================
// HELPERS
// ============================================================
const DAY_MAP = [
'mon' => 1,
'tue' => 2,
'wed' => 3,
'thu' => 4,
'fri' => 5,
'sat' => 6,
'sun' => 7,
];
/**
* Parse DTSTART value.
*
* Returns:
* ['allday' => true, 'weekday' => 1–7]
* ['allday' => false, 'weekday' => 1–7, 'time' => 'HH:MM']
* null on failure
*/
function parseDtstart(string $value): ?array
{
// Date-time: 20240313T110000[Z] or TZID=…:20240313T110000
if (preg_match('/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/i', $value, $m)) {
$ts = mktime(0, 0, 0, (int)$m[2], (int)$m[3], (int)$m[1]);
return [
'allday' => false,
'weekday' => (int)date('N', $ts),
'time' => $m[4] . ':' . $m[5],
'date' => $m[1] . '-' . $m[2] . '-' . $m[3], // YYYY-MM-DD
];
}
// Date-only (all-day): VALUE=DATE:20240313 or bare 20240313
if (preg_match('/(\d{4})(\d{2})(\d{2})\s*$/', trim($value), $m)) {
$ts = mktime(0, 0, 0, (int)$m[2], (int)$m[3], (int)$m[1]);
return [
'allday' => true,
'weekday' => (int)date('N', $ts),
'date' => $m[1] . '-' . $m[2] . '-' . $m[3],
];
}
return null;
}
function timeToMinutes(string $hhmm): int
{
[$h, $m] = explode(':', $hhmm);
return (int)$h * 60 + (int)$m;
}
/** YYYY-MM-DD → integer YYYYMMDD for easy comparison */
function dateToInt(string $date): int
{
return (int)str_replace('-', '', $date);
}
/**
* Returns true when $event matches ALL non-null criteria in $filter.
*
* time/date/name filters are lists of condition objects:
* [{type: range, from: HH:MM, to: HH:MM}]
* [{type: exact, starts: HH:MM}]
* [{type: before, at: HH:MM}]
* [{type: allday}]
* [{type: startswith, text: Foo}]
* [{type: exact, at: YYYY-MM-DD}]
* All conditions in the list must match (AND).
*/
function matchesFilter(array $filter, array $event): bool
{
$dtstart = isset($event['DTSTART']) ? parseDtstart($event['DTSTART']) : null;
// ── days ────────────────────────────────────────────────
if (($filter['days'] ?? null) !== null) {
if ($dtstart === null) return false;
$days = (array)$filter['days'];
$allowed = array_map(fn($d) => DAY_MAP[strtolower($d)] ?? 0, $days);
if (!in_array($dtstart['weekday'], $allowed, true)) return false;
}
// ── time ────────────────────────────────────────────────
if (($filter['time'] ?? null) !== null) {
if ($dtstart === null) return false;
foreach ((array)$filter['time'] as $cond) {
$type = $cond['type'] ?? '';
if ($type === 'allday') {
if (!$dtstart['allday']) return false;
continue;
}
// For timed comparisons, all-day events are treated as 00:00
$eventMin = $dtstart['allday'] ? 0 : timeToMinutes($dtstart['time']);
switch ($type) {
case 'exact':
if (isset($cond['starts']) && $eventMin !== timeToMinutes($cond['starts'])) return false;
break;
case 'range':
if ($eventMin < timeToMinutes($cond['from']) || $eventMin > timeToMinutes($cond['to'])) return false;
break;
case 'before':
if ($eventMin >= timeToMinutes($cond['at'])) return false;
break;
case 'after':
if ($eventMin <= timeToMinutes($cond['at'])) return false;
break;
}
}
}
// ── date ────────────────────────────────────────────────
if (($filter['date'] ?? null) !== null) {
if ($dtstart === null) return false;
$eventDate = dateToInt($dtstart['date']);
foreach ((array)$filter['date'] as $cond) {
switch ($cond['type'] ?? '') {
case 'exact':
if ($eventDate !== dateToInt($cond['at'])) return false;
break;
case 'range':
if ($eventDate < dateToInt($cond['from']) || $eventDate > dateToInt($cond['to'])) return false;
break;
case 'before':
if ($eventDate >= dateToInt($cond['at'])) return false;
break;
case 'after':
if ($eventDate <= dateToInt($cond['at'])) return false;
break;
}
}
}
// ── busy_status ─────────────────────────────────────────
if (($filter['busy_status'] ?? null) !== null) {
$actual = strtoupper($event['X-MICROSOFT-CDO-BUSYSTATUS'] ?? '');
if ($actual !== strtoupper($filter['busy_status'])) return false;
}
// ── name ────────────────────────────────────────────────
if (($filter['name'] ?? null) !== null) {
$summary = $event['SUMMARY'] ?? '';
foreach ((array)$filter['name'] as $cond) {
$needle = $cond['text'] ?? '';
switch ($cond['type'] ?? '') {
case 'exact':
if ($summary !== $needle) return false;
break;
case 'contains':
if (stripos($summary, $needle) === false) return false;
break;
case 'startswith':
if (stripos($summary, $needle) !== 0) return false;
break;
case 'endswith':
$len = strlen($needle);
if ($len > 0 && substr_compare($summary, $needle, -$len, $len, true) !== 0) return false;
break;
}
}
}
// ── recurrent ───────────────────────────────────────────
if (($filter['recurrent'] ?? null) !== null) {
$isRecurrent = isset($event['RRULE']) || isset($event['RECURRENCE-ID']);
if ($filter['recurrent'] !== $isRecurrent) return false;
}
return true;
}
/**
* Replace or insert a property inside a VEVENT block string.
* Correctly handles folded (multi-line) property values.
*/
function setProperty(string $block, string $prop, string $value): string
{
// Match property including any folded continuation lines
$pattern = '/^' . preg_quote($prop, '/') . '(?:;[^:]*)?:.*?(?=\r?\n[^ \t\r\n])/ms';
$line = $prop . ':' . $value;
if (preg_match($pattern, $block)) {
return preg_replace($pattern, $line, $block);
}
// Property not present → insert before END:VEVENT
return str_replace("\r\nEND:VEVENT", "\r\n" . $line . "\r\nEND:VEVENT", $block);
}
/**
* Parse a VEVENT block into a key→value map.
* Unfolds RFC 5545 folded lines; uses base property keys (strips parameters).
*/
function parseVEvent(string $block): array
{
$unfolded = preg_replace('/\r?\n[ \t]/', '', $block);
$props = [];
foreach (explode("\n", $unfolded) as $line) {
$line = rtrim($line, "\r");
if ($line === '' || $line === 'BEGIN:VEVENT' || $line === 'END:VEVENT') continue;
$colon = strpos($line, ':');
if ($colon === false) continue;
$baseKey = strtok(substr($line, 0, $colon), ';');
$props[$baseKey] = substr($line, $colon + 1);
}
return $props;
}
// ============================================================
// TRANSFORM
// ============================================================
$timeStart = hrtime(true);
$linesBefore = substr_count($raw, "\n");
$countTotal = 0;
$countChanged = 0;
$countRemoved = 0;
$eventLog = []; // [{summary, date, status}]
$output = preg_replace_callback(
'/BEGIN:VEVENT\r?\n.*?END:VEVENT/s',
function (array $matches) use ($rules, &$countTotal, &$countChanged, &$countRemoved, &$eventLog): string {
$block = $matches[0];
$event = parseVEvent($block);
$countTotal++;
$summary = $event['SUMMARY'] ?? '(no title)';
$dtRaw = $event['DTSTART'] ?? '';
$dt = parseDtstart($dtRaw);
$timeCol = $dt ? ($dt['allday'] ? '(allday)' : $dt['time']) : '?';
$dateStr = $dt ? ($dt['date'] . "\t\t" . str_pad($timeCol, 10)) : "?\t\t?\t\t";
$isRecurring = isset($event['RRULE']) || isset($event['RECURRENCE-ID']);
foreach ($rules as $ruleIndex => $rule) {
if (!matchesFilter($rule['filter'], $event)) {
continue;
}
$apply = $rule['apply'] ?? [];
if (!empty($apply['remove'])) {
$countRemoved++;
$eventLog[] = ['summary' => $summary, 'date' => $dateStr, 'status' => 'removed', 'rule' => $ruleIndex, 'recurring' => $isRecurring];
return '';
}
$modified = $block;
if (!empty($apply['name'])) {
$modified = setProperty($modified, 'SUMMARY', $apply['name']);
}
if (!empty($apply['busy_status'])) {
$modified = setProperty($modified, 'X-MICROSOFT-CDO-BUSYSTATUS', $apply['busy_status']);
}
if (!empty($apply['location'])) {
$modified = setProperty($modified, 'LOCATION', $apply['location']);
}
if (isset($apply['reminder'])) {
$minutes = (int)$apply['reminder'];
$valarm = "\r\nBEGIN:VALARM"
. "\r\nTRIGGER:-PT{$minutes}M"
. "\r\nACTION:DISPLAY"
. "\r\nDESCRIPTION:Reminder"
. "\r\nEND:VALARM";
// Remove any existing VALARM first, then insert before END:VEVENT
$modified = preg_replace('/\r?\nBEGIN:VALARM.*?END:VALARM/s', '', $modified);
$modified = str_replace("\r\nEND:VEVENT", $valarm . "\r\nEND:VEVENT", $modified);
}
if ($modified !== $block) {
$countChanged++;
$newSummary = parseVEvent($modified)['SUMMARY'] ?? $summary;
$displaySummary = $newSummary !== $summary ? $summary . ' --> ' . $newSummary : $summary;
$eventLog[] = ['summary' => $displaySummary, 'date' => $dateStr, 'status' => 'changed', 'rule' => $ruleIndex, 'recurring' => $isRecurring];
} else {
$eventLog[] = ['summary' => $summary, 'date' => $dateStr, 'status' => 'matched/unchanged', 'rule' => $ruleIndex, 'recurring' => $isRecurring];
}
return $modified;
break; // first matching rule wins
}
$eventLog[] = ['summary' => $summary, 'date' => $dateStr, 'status' => 'unchanged', 'rule' => null, 'recurring' => $isRecurring];
return $block;
},
$raw
);
// Tidy up blank lines left by removed events
$output = preg_replace('/(\r?\n){3,}/', "\r\n", $output) ?? $output;
$linesAfter = substr_count($output, "\n");
$timeMs = round((hrtime(true) - $timeStart) / 1e6, 2);
// ============================================================
// OUTPUT
// ============================================================
header('Cache-Control: no-store');
if ($debug) {
header('Content-Type: text/plain; charset=utf-8');
$total = $countTotal ?: 1; // avoid division by zero
$pct = fn(int $n) => $n . ' (' . round($n / $total * 100) . '%)';
$linesIn = $linesBefore ?: 1;
$sep = str_repeat('─', 80);
$lines = [
'calendar : ' . $cal,
'events : ' . $countTotal,
'changed : ' . $pct($countChanged),
'removed : ' . $pct($countRemoved),
'unchanged: ' . $pct($countTotal - $countChanged - $countRemoved),
'',
'lines in : ' . $linesBefore,
'lines out: ' . $linesAfter . ' (' . round($linesAfter / $linesIn * 100) . '%)',
'',
'duration : ' . $timeMs . ' ms',
'',
];
$groups = ['removed' => [], 'changed' => [], 'matched/unchanged' => [], 'unchanged' => []];
foreach ($eventLog as $e) $groups[$e['status']][] = $e;
foreach ($groups as $status => $entries) {
if (empty($entries)) continue;
$lines[] = strtoupper($status) . ' (' . count($entries) . ')';
$lines[] = $sep;
foreach ($entries as $e) {
$ruleLabel = $e['rule'] !== null ? '[rule ' . $e['rule'] . ']' : '';
$recLabel = $e['recurring'] ? ' ↻' : '';
$lines[] = ' ' . $e['date'] . "\t\t" . str_pad($ruleLabel, 10) . "\t\t" . $e['summary'] . $recLabel;
}
$lines[] = '';
}
echo implode("\n", $lines);
} elseif ($text) {
header('Content-Type: text/plain; charset=utf-8');
echo $output;
} else {
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: inline');
echo $output;
}