-
Notifications
You must be signed in to change notification settings - Fork 8
/
calendar.php
5231 lines (4646 loc) · 179 KB
/
calendar.php
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
PHPCalFeed
A calendar feed script
Copyright (C) 2014 Mark Frimston
*/
// TODO: move heavy lifting to included file?
// TODO: events which started in the past but are still ongoing are excluded from feeds
// TODO: Filename in config for local files
// TODO: sql database input using pdo
// TODO: icalendar proper timezone construction
// TODO: CalDAV
// TODO: format for screen readers
// TODO: format for printing
// TODO: facebook input
// TODO: wordpress api
// TODO: eventbrite input
// TODO: yaml input
// TODO: yaml output
// TODO: atom output
// TODO: yaml output
// TODO: s-expression input
// TODO: textpattern api
// TODO: web-based UI for config
// TODO: web-based UI input
// TODO: microformat shouldn't have multiple events for day-spanning event
// TODO: browser cache headers
// TODO: need better way to handle incrementing from start time
// TODO: internationalisation
abstract class InputFormat {
/* name
description
url
events (required)
name (required)
date (required) (year,month,day)
time (hour, minute, second)
duration (days,hours,minutes,seconds)
description
url
recurring-events
name (required)
recurrence (required,list) (start,[end],[count],week-start,rules)
excluding (list) (start,[end],[count],week-start,rules)
duration (days,hours,minutes,seconds)
description
url */
public abstract function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config);
public abstract function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config);
protected function file_read_due($filepath,$cachedtime,$oldestinputok){
return $cachedtime <= @filemtime($filepath) || $cachedtime <= $oldestinputok;
}
protected function url_read_due($cachedtime,$oldestinputok){
return $cachedtime <= $oldestinputok;
}
protected function get_error_filename($scriptdir,$scriptname){
return "$scriptname.error";
}
protected function check_cached_error($scriptdir,$scriptname){
$errorfile = $this->get_error_filename($scriptdir,$scriptname);
$errortime = @filemtime($errorfile);
if($errortime===FALSE) return;
if(time() - $errortime > 20*60){ // error file is valid for 20 minutes
unlink($errorfile);
return;
}
$error = @file_get_contents($errorfile);
if($error===FALSE) return;
return $error;
}
protected function cache_error($scriptdir,$scriptname,$error){
$errorfile = $this->get_error_filename($scriptdir,$scriptname);
$handle = @fopen($errorfile,"w");
if($handle===FALSE) return;
fwrite($handle,$error);
fclose($handle);
}
}
class NoInput extends InputFormat {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "none") return FALSE;
return $this->get_empty_data();
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
$result = write_config($scriptdir,$scriptname,array("format"=>"none"));
if($result) return $result;
return $this->get_empty_data();
}
private function get_empty_data(){
$data = new stdClass();
$data->events = array();
$data->{"recurring-events"} = array();
return $data;
}
}
abstract class HtmlInputBase extends InputFormat {
/*
name xpath
description xpath
url xpath
event xpath
name xpath
description xpath
start datetime xpath
start time xpath
duration xpath
end datetime xpath
end time xpath
url xpath
(no recurring)
Defaults to hcalendar spec
*/
protected function is_available(){
return extension_loaded("libxml") && extension_loaded("dom");
}
private function el_with_class_xp($elname,$classname){
$classname = trim($classname);
return $elname."[contains(concat(' ',normalize-space(@class),' '),' $classname ')]";
}
private function el_contents_with_class_xp($prefix,$classname){
return $prefix.$this->el_with_class_xp("img",$classname)."/@alt"
." | ".$prefix.$this->el_with_class_xp("area",$classname)."/@alt"
." | ".$prefix.$this->el_with_class_xp("data",$classname)."/@value"
." | ".$prefix.$this->el_with_class_xp("abbr",$classname)."/@title"
." | ".$prefix.$this->el_with_class_xp("*",$classname)."//text()";
}
private function std_el_contents_with_class_xp($classname){
return $this->el_contents_with_class_xp(".//".$this->el_with_class_xp("*",$classname)."//","value")
." | ".$this->el_contents_with_class_xp(".//",$classname);
}
private function anchor_contents_with_class_xp($classname){
return $this->el_contents_with_class_xp(".//".$this->el_with_class_xp("*",$classname)."//","value")
." | ".".//".$this->el_with_class_xp("a",$classname)."/@href"
." | ".".//".$this->el_with_class_xp("link",$classname)."/@href"
." | ".$this->el_contents_with_class_xp(".//",$classname);
}
private function date_contents_with_class_xp($classname){
return $this->el_contents_with_class_xp(".//".$this->el_with_class_xp("*",$classname)."//","value")
." | ".".//".$this->el_with_class_xp("del",$classname)."/@datetime"
." | ".".//".$this->el_with_class_xp("ins",$classname)."/@datetime"
." | ".".//".$this->el_with_class_xp("time",$classname)."/@datetime"
." | ".$this->el_contents_with_class_xp(".//",$classname);
}
private function get_xpath_result($node,$context,$xpath){
$results = $context->query($xpath,$node);
if($results===FALSE) return "HTML: Bad XPath expression '$xpath'";
return $results;
}
private function resolve_single_xpath($node,$context,$xpath){
$results = $this->get_xpath_result($node,$context,$xpath);
if(is_string($results)) return $results;
foreach($results as $result){
$text = $result->nodeValue;
if(strlen(trim($text))==0) continue;
return array( "text"=> $text );
}
return FALSE;
}
private function resolve_concat_xpath($node,$context,$xpath){
$bits = array();
$results = $this->get_xpath_result($node,$context,$xpath);
if(is_string($results)) return $results;
foreach($results as $result){
$text = $result->nodeValue;
if(strlen(trim($text))==0) continue;
array_push($bits,trim($text));
}
if(sizeof($bits)==0) return FALSE;
return array( "text" => implode(" ",$bits) );
}
private function resolve_duration_xpath($node,$context,$xpath){
$results = $this->get_xpath_result($node,$context,$xpath);
if(is_string($results)) return $results;
foreach($results as $result){
$text = $result->nodeValue;
$duration = parse_duration($text);
if($duration===FALSE) continue;
return $duration;
}
return FALSE;
}
private function resolve_date_xpath($node,$context,$xpath){
$date = NULL;
$time = NULL;
$gotspectime = FALSE;
$results = $this->get_xpath_result($node,$context,$xpath);
if(is_string($results)) return $results;
foreach($results as $result){
$text = $result->nodeValue;
$parsed = parse_time($text);
if($parsed!==FALSE){
// time without date found - override existing time if it was part of
// a datetime as it may have been the default time
if(!$gotspectime){
$time = array( "hour"=>$parsed["hour"], "minute"=>$parsed["minute"],
"day"=>$parsed["day"] );
$gotspectime = TRUE;
if($date!==NULL && $time!==NULL) break;
}
}else{
$parsed = parse_datetime($text);
if($parsed===FALSE) continue;
if($date===NULL){
$date = array( "year"=>$parsed["year"], "month"=>$parsed["month"],
"day"=>$parsed["day"] );
}
if($time===NULL){
$time = array( "hour"=>$parsed["hour"], "minute"=>$parsed["minute"],
"second"=>$parsed["second"] );
}
// don't break, as we might find a more specific time value
}
}
if($date===NULL || $time===NULL) return FALSE;
return array( "date"=>$date, "time"=>$time );
}
protected abstract function get_calendar_url($resource_name,$config);
protected function stream_to_event_data($filehandle,$resource_name,$config){
$xp_cal_summary = "/html/head/title//text()";
$xp_cal_description = "/html/head/meta[@name='description']/@content";
$xp_cal_url = NULL;
$xp_event = "//".$this->el_with_class_xp("*","vevent"); // defines context element for event properties
$xp_ev_summary = $this->std_el_contents_with_class_xp("summary");
$xp_ev_description = $this->std_el_contents_with_class_xp("description");
$xp_ev_url = $this->anchor_contents_with_class_xp("url");
$xp_ev_dtstart = $this->date_contents_with_class_xp("dtstart");
$xp_ev_dtend = $this->date_contents_with_class_xp("dtend");
$xp_ev_duration = $this->std_el_contents_with_class_xp("duration");
if(isset($config["html-markers"])){
$markers = $config["html-markers"];
if(isset($markers["cal-name-class"])) $xp_cal_summary = $this->std_el_contents_with_class_xp($markers["cal-name-class"]);
if(isset($markers["cal-name-xpath"])) $xp_cal_summary = $markers["cal-name-xpath"];
if(isset($markers["cal-description-class"])) $xp_cal_description = $this->std_el_contents_with_class_xp($markers["cal-description-class"]);
if(isset($markers["cal-description-xpath"])) $xp_cal_description = $markers["cal-description-xpath"];
if(isset($markers["cal-url-class"])) $xp_cal_url = $this->std_el_contents_with_class_xp($markers["cal-url-class"]);
if(isset($markers["cal-url-xpath"])) $cap_cal_xpath = $markers["cal-url-xpath"];
if(isset($markers["cal-event-class"])) $xp_event = "//".$this->el_with_class_xp("*",$markers["cal-event-class"]);
if(isset($markers["cal-event-xpath"])) $xp_event = $markers["cal-event-xpath"];
if(isset($markers["ev-name-class"])) $xp_ev_summary = $this->std_el_contents_with_class_xp($markers["ev-name-class"]);
if(isset($markers["ev-name-xpath"])) $xp_ev_summary = $markers["ev-name-xpath"];
if(isset($markers["ev-description-class"])) $xp_ev_description = $this->std_el_contents_with_class_xp($markers["ev-description-class"]);
if(isset($markers["ev-description-xpath"])) $xp_ev_description = $markers["ev-description-xpath"];
if(isset($markers["ev-url-class"])) $xp_ev_url = $this->anchor_contents_with_class_xp($markers["ev-url-class"]);
if(isset($markers["ev-url-xpath"])) $xp_ev_url = $markers["ev-url-xpath"];
if(isset($markers["ev-start-class"])) $xp_ev_dtstart = $this->date_contents_with_class_xp($markers["ev-start-class"]);
if(isset($markers["ev-start-xpath"])) $xp_ev_dtstart = $markers["ev-start-xpath"];
if(isset($markers["ev-end-class"])) $xp_ev_dtend = $this->date_contents_with_class_xp($markers["ev-end-class"]);
if(isset($markers["ev-end-xpath"])) $xp_ev_dtend = $markers["ev-end-xpath"];
if(isset($markers["ev-duration-class"])) $xp_ev_duration = $this->std_el_contents_with_class_xp($markers["ev-duration-class"]);
if(isset($markers["ev-duration-xpath"])) $xp_ev_duration = $markers["ev-duration-xpath"];
}
$html = stream_get_contents($filehandle);
if($html===FALSE) return "HTML: Failed to read stream";
$doc = new DOMDocument();
@$doc->loadHTML($html);
if($doc===FALSE) return "HTML: Failed to parse page";
$xpath = new DOMXPath($doc);
$data = new stdClass();
$calname = $this->resolve_concat_xpath($doc->documentElement,$xpath,$xp_cal_summary);
if(is_string($calname)) return $calname;
if($calname!==FALSE) $data->name = $calname["text"];
$caldesc = $this->resolve_concat_xpath($doc->documentElement,$xpath,$xp_cal_description);
if(is_string($caldesc)) return $caldesc;
if($caldesc!==FALSE) $data->description = $caldesc["text"];
if($xp_cal_url!==NULL){
$calurl = $this->resolve_single_xpath($doc->documentElement,$xpath,$xp_cal_url);
if(is_string($calurl)) return $calurl;
if($calurl!==FALSE) $data->url = $calurl["text"];
}else{
$calurl = $this->get_calendar_url($resource_name,$config);
if($calurl!==FALSE) $data->url = $calurl;
}
$event_els = $this->get_xpath_result($doc->documentElement,$xpath,$xp_event);
if(is_string($event_els)) return $event_els;
$data->events = array();
foreach($event_els as $event_el){
$event = new stdClass();
$name = $this->resolve_concat_xpath($event_el,$xpath,$xp_ev_summary);
if(is_string($name)) return $name;
if($name===FALSE) continue;
$event->name = $name["text"];
$description = $this->resolve_concat_xpath($event_el,$xpath,$xp_ev_description);
if(is_string($description)) return $description;
if($description!==FALSE) $event->description = $description["text"];
$url = $this->resolve_single_xpath($event_el,$xpath,$xp_ev_url);
if(is_string($url)) return $url;
if($url!==FALSE) $event->url = $url["text"];
$start = $this->resolve_date_xpath($event_el,$xpath,$xp_ev_dtstart);
if(is_string($start)) return $start;
if($start===FALSE) continue;
$event->date = $start["date"];
$event->time = $start["time"];
$end = $this->resolve_date_xpath($event_el,$xpath,$xp_ev_dtend);
if(is_string($end)) return $end;
if($end!==FALSE){
$event->duration = calc_approx_diff($event->date,$event->time,$end["date"],$end["time"]);
}else{
$duration = $this->resolve_duration_xpath($event_el,$xpath,$xp_ev_duration);
if(is_string($duration)) return $duration;
if($duration!==FALSE){
$event->duration = $duration;
}else{
$event->duration = array( "days"=>1, "hours"=>0, "minutes"=>0, "seconds"=>0 );
}
}
array_push($data->events,$event);
}
$data->{"recurring-events"} = array();
return $data;
}
}
class LocalHtmlInput extends HtmlInputBase {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "html-local") return FALSE;
if(!$this->is_available()) return FALSE;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config);
if($result === FALSE) return TRUE;
return $result;
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
if(!$this->is_available()) return FALSE;
if(!file_exists($this->get_filepath($scriptdir,$scriptname))) return FALSE;
$result = write_config($scriptdir,$scriptname,array("format"=>"html-local"));
if($result) return $result;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config);
if($result === FALSE) return TRUE;
return $result;
}
private function get_filepath($scriptdir,$scriptname){
return $scriptdir."/".$scriptname."-master.html";
}
protected function get_calendar_url($filepath,$config){
$url = get_file_protocolless_url($filepath,$config);
if($url===FALSE) return FALSE;
return "http:".$url;
}
private function do_input($filepath){
$handle = @fopen($filepath,"r");
if($handle===FALSE) return "HTML: failed to open '$filepath'";
$result = $this->stream_to_event_data($handle,$filepath,$config);
fclose($handle);
return $result;
}
private function input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
$filepath = $this->get_filepath($scriptdir,$scriptname);
if(!$this->file_read_due($filepath,$cachedtime,$oldestinputok)) return FALSE;
$error = $this->check_cached_error($scriptdir,$scriptname);
if($error) return $error;
$result = $this->do_input($filepath);
if(is_string($result)) $this->cache_error($scriptdir,$scriptname,$result);
return $result;
}
}
class RemoteHtmlInput extends HtmlInputBase {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "html-remote") return FALSE;
if(!$this->is_available()) return FALSE;
if(!isset($config["url"])) return "HTML: missing config parameter: 'url'";
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config["url"],$config);
if($result === FALSE) return TRUE;
return $result;
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
if(!isset($config["url"])) return FALSE;
if(strtolower(substr($config["url"],-4,4)) != ".htm" && strtolower(substr($config["url"],-5,5)) != ".html") return FALSE;
$result = write_config($scriptdir,$scriptname,array("format"=>"html-remote","url"=>$config["url"]));
if($result) return $result;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config["url"],$config);
if($result === FALSE) return TRUE;
return $result;
}
protected function get_calendar_url($url,$config){
return $url;
}
private function do_input($url){
$handle = http_request($url);
if(is_string($handle)) return "HTML: $handle";
$result = $this->stream_to_event_data($handle,$url,$config);
fclose($handle);
}
public function input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$url,$config){
if(!$this->url_read_due($cachedtime,$oldestinputok)) return FALSE;
$error = $this->check_cached_error($scriptdir,$scriptname);
if($error) return $error;
$result = $this->do_input($url);
if(is_string($result)) $this->cache_error($scriptdir,$scriptname,$result);
return $result;
}
}
abstract class ICalendarInputBase extends InputFormat {
protected function feed_to_event_data($filehandle){
$parser = new ICalendarParser();
$cal = $parser->parse($filehandle);
if(is_string($cal)) return "ICalendar: Invalid ICalendar feed: $cal";
$calobj = new stdClass();
$calobj->events = array();
$calobj->{"recurring-events"} = array();
if($cal["name"]!="VCALENDAR"){
return "ICalendar: Expected VCALENDAR component but found".$cal["name"];
}
if(isset($cal["properties"]["calscale"])
&& strtolower($cal["properties"]["calscale"][0]["value"][0]) != "gregorian"){
return "ICalendar: Non-gregorian calendar not supported";
}
if(isset($cal["properties"]["x-wr-calname"])){
$calobj->name = $cal["properties"]["x-wr-calname"][0]["value"][0];
}
if(isset($cal["properties"]["x-wr-caldesc"])){
$calobj->description = $this->concat_prop_values($cal["properties"]["x-wr-caldesc"]);
}
if(isset($cal["properties"]["x-original-url"])){
$calobj->url = $cal["properties"]["x-original-url"][0]["value"][0];
}
if(isset($cal["components"]["VEVENT"])){
foreach($cal["components"]["VEVENT"] as $vevent){
$eventobj = new stdClass();
if(isset($vevent["properties"]["summary"])){
$eventobj->name = $this->concat_prop_values($vevent["properties"]["summary"]);
}else{
$eventobj->name = "Unnamed event";
}
if(isset($vevent["properties"]["description"])
&& strlen($vevent["properties"]["description"][0]["value"][0])>0){
$eventobj->description = $this->concat_prop_values($vevent["properties"]["description"]);
}
if(isset($vevent["properties"]["url"])){
$eventobj->url = $vevent["properties"]["url"][0]["value"];
}
if(!isset($vevent["properties"]["dtstart"])){
continue; // ignore if no start time
}
$starttimes = $this->convert_datetime($vevent["properties"]["dtstart"][0]);
if(is_string($starttimes)) return $starttimes;
$starttime = $starttimes[0];
$eventobj->date = array( "year"=>$starttime["year"], "month"=>$starttime["month"], "day"=>$starttime["day"] );
$eventobj->time = array( "hour"=>$starttime["hour"], "minute"=>$starttime["minute"], "second"=>$starttime["second"] );
if(isset($vevent["properties"]["duration"])){
// duration specified
$duration = $this->convert_duration($vevent["properties"]["duration"][0]);
if(is_string($duration)) return $duration;
$eventobj->duration = $duration;
}elseif(isset($vevent["properties"]["dtstart"])){
$dtstart = $vevent["properties"]["dtstart"][0];
if(isset($vevent["properties"]["dtend"])){
// start and end specified
$starttimes = $this->convert_datetime($dtstart);
if(is_string($starttimes)) return $starttimes;
$starttime = $starttimes[0];
$endtimes = $this->convert_datetime($vevent["properties"]["dtend"][0]);
if(is_string($endtimes)) return $endtimes;
$endtime = $endtimes[0];
$eventobj->duration = calc_approx_diff(
array( "year"=>$starttime["year"], "month"=>$starttime["month"], "day"=>$starttime["day"] ),
array( "hour"=>$starttime["hour"], "minute"=>$starttime["minute"], "second"=>$starttime["second"] ),
array( "year"=>$endtime["year"], "month"=>$endtime["month"], "day"=>$endtime["day"] ),
array( "hour"=>$endtime["hour"], "minute"=>$endtime["minute"], "second"=>$endtime["second"] )
);
}elseif(isset($dtstart["parameters"]["value"]) && strtolower($dtstart["parameters"]["value"])=="date"){
// start specified as date
$eventobj->duration = array("days"=>1,"hours"=>0,"minutes"=>0, "seconds"=>0);
}else{
// start specified as datetime
$eventobj->duration = array("days"=>0,"hours"=>0,"minutes"=>0, "seconds"=>0);
}
}else{
return "ICalendar: Cannot determine duration for '".$eventobj->name."'";
}
array_push($calobj->events,$eventobj);
$rrules = isset($vevent["properties"]["rrule"]) ? $vevent["properties"]["rrule"] : NULL;
$exrules = isset($vevent["properties"]["exrule"]) ? $vevent["properties"]["exrule"] : NULL;
$rdates = isset($vevent["properties"]["rdate"]) ? $vevent["properties"]["rdate"] : NULL;
$exdates = isset($vevent["properties"]["exdate"]) ? $vevent["properties"]["exdate"] : NULL;
if($rrules!==NULL || $exrules!==NULL || $rdates!==NULL || $exdates!==NULL){
$convrecur = $this->convert_recurrence($rrules,$exrules,$rdates,$exdates,$starttime);
if(is_string($convrecur)) return $convrecur;
$eventobj->recurrence = $convrecur["include"];
$eventobj->excluding = $convrecur["exclude"];
array_push($calobj->{"recurring-events"},$eventobj);
}
}
}
return $calobj;
}
private function concat_prop_values($properties){
$result = "";
foreach($properties as $prop){
foreach($prop["value"] as $value){
$result .= $value;
}
}
return $result;
}
private function convert_datetime($property){
if(isset($property["parameters"]["value"]) && strtolower($property["parameters"]["value"])=="date"){
# date only
$result = array();
foreach($property["value"] as $date){
array_push($result, array( "year"=>$date["year"], "month"=>$date["month"], "day"=>$date["day"],
"hour"=>0, "minute"=>0, "second"=>0));
}
return $result;
}else{
# date and time
$result = array();
foreach($property["value"] as $value){
$datetime = $this->convert_datetime_value($value,$property["parameters"]);
if(is_string($datetime)) return $datetime;
array_push($result,$datetime);
}
return $result;
}
}
private function convert_datetime_value($value,$parameters){
if($value["isutc"]){
$timezone = new DateTimeZone("UTC");
}elseif(isset($parameters["tzid"])){
$tzid = $parameters["tzid"];
try {
$timezone = new DateTimeZone($tzid);
}catch(Exception $e){
return "ICalendar: timezone '$tzid' unknown and timezone construction not implemented";
}
}else{
$newdate = new DateTime();
$timezone = $newdate->getTimezone();
}
$cal = new DateTime($value["year"]."-".$value["month"]."-".$value["day"]
." ".$value["hour"].":".$value["minute"].":".$value["second"], $timezone);
$cal = new DateTime("@".$cal->getTimestamp());
return array( "year"=>(int)$cal->format("Y"), "month"=>(int)$cal->format("n"), "day"=>(int)$cal->format("j"),
"hour"=>(int)$cal->format("G"), "minute"=>(int)$cal->format("i"), "second"=>(int)$cal->format("s") );
}
private function convert_duration($property){
$dur = $property["value"][0];
return array( "days"=>$dur["weeks"]*7+$dur["days"], "hours"=>$dur["hours"],
"minutes"=>$dur["minutes"], "seconds"=>$dur["seconds"] );
}
private function convert_recur_rule($rrule,$starttime){
if(!isset($rrule["freq"])) return "ICalendar: RRULE without FREQ parameter";
$result = array( "start"=>$starttime, "rules"=>array(), "week-start"=>1 );
if(isset($rrule["until"])){
$result["end"] = $this->convert_datetime_value($rrule["until"],array());
}
if(isset($rrule["count"])){
$result["count"] = $rrule["count"] - 1; // internal format doesnt include dtstart occurence
}
if(isset($rrule["wkst"])){
switch($rrule["wkst"]){
case "mo": $daynum = 1; break;
case "tu": $daynum = 2; break;
case "we": $daynum = 3; break;
case "th": $daynum = 4; break;
case "fr": $daynum = 5; break;
case "sa": $daynum = 6; break;
case "su": $daynum = 7; break;
default: return "ICalendar: invalid WKST value '".$rrule["wkst"]."'";
}
$result["week-start"] = $daynum;
}
if(isset($rrule["interval"])){
switch($rrule["freq"]){
case "yearly": $rulename="year-ival"; break;
case "monthly": $rulename="month-ival"; break;
case "weekly": $rulename="week-ival"; break;
case "daily": $rulename="day-ival"; break;
case "hourly": $rulename="hour-ival"; break;
case "minutely": $rulename="minute-ival"; break;
case "secondly": $rulename="second-ival"; break;
default: return "ICalendar: Unknown FREQ value '".$rrule["freq"]."'";
}
$result["rules"][$rulename] = $rrule["interval"];
}
if(isset($rrule["bysecond"])){
$result["rules"]["minute-second"] = $rrule["bysecond"];
}
if(isset($rrule["byminute"])){
$result["rules"]["hour-minute"] = $rrule["byminute"];
}
if(isset($rrule["byhour"])){
$result["rules"]["day-hour"] = $rrule["byhour"];
}
if(isset($rrule["byday"])){
$rulebits = array();
foreach($rrule["byday"] as $byday){
switch($byday["day"]){
case "mo": $daynum = 1; break;
case "tu": $daynum = 2; break;
case "we": $daynum = 3; break;
case "th": $daynum = 4; break;
case "fr": $daynum = 5; break;
case "sa": $daynum = 6; break;
case "su": $daynum = 7; break;
default: return "ICalendar: invalid day value '".$byday["day"]."'";
}
$rulebit = array( "day"=>$daynum );
if(isset($byday["number"])){
$rulebit["number"] = $byday["number"];
}
array_push($rulebits,$rulebit);
}
if($rrule["freq"]=="monthly" || ($rrule["freq"]=="yearly" && isset($rrule["bymonth"]))){
$result["rules"]["month-week-day"] = $rulebits;
}else{
$result["rules"]["year-week-day"] = $rulebits;
}
}
if(isset($rrule["bymonthday"])){
$result["rules"]["month-day"] = $rrule["bymonthday"];
}
if(isset($rrule["byyearday"])){
$result["rules"]["year-day"] = $rrule["byyearday"];
}
if(isset($rrule["byweekno"])){
$result["rules"]["year-week"] = $rrule["byweekno"];
}
if(isset($rrule["bymonth"])){
$result["rules"]["year-month"] = $rrule["bymonth"];
}
if(isset($rrule["bysetpos"])){
$poses = $rrule["bysetpos"];
switch($rrule["freq"]){
case "yearly": $result["rules"]["year-match"] = $poses; break;
case "monthly": $result["rules"]["month-match"] = $poses; break;
case "weekly": $result["rules"]["week-match"] = $poses; break;
case "daily": $result["rules"]["day-match"] = $poses; break;
case "hourly": $result["rules"]["hour-match"] = $poses; break;
case "minutely": $result["rules"]["minute-match"] = $poses; break;
case "secondly": $result["rules"]["second-match"] = $poses; break;
default: return "ICalendar: invalid FREQ value '".$rrule["freq"]."'";
}
}
// fill in remaining rules from dtstart
switch($rrule["freq"]){
case "yearly":
if(!isset($result["rules"]["year-month"]) && !isset($result["rules"]["year-week"])
&& !isset($result["rules"]["year-day"]) && !isset($result["rules"]["year-week-day"])
&& !isset($result["rules"]["month-day"]) && !isset($result["rules"]["month-week-day"])
&& !isset($result["rules"]["day-hour"]) && !isset($result["rules"]["hour-minute"])
&& !isset($result["rules"]["minute-second"])){
$result["rules"]["year-month"] = array( $starttime["month"] );
}
// fall through
case "monthly":
if(!isset($result["rules"]["year-week"]) && !isset($result["rules"]["year-day"])
&& !isset($result["rules"]["year-week-day"]) && !isset($result["rules"]["month-day"])
&& !isset($result["rules"]["month-week-day"]) && !isset($result["rules"]["day-hour"])
&& !isset($result["rules"]["hour-minute"]) && !isset($result["rules"]["minute-second"])){
$result["rules"]["month-day"] = array( $starttime["day"] );
}
// fall through
case "weekly":
if(!isset($result["rules"]["year-day"]) && !isset($result["rules"]["year-week-day"])
&& !isset($result["rules"]["month-day"]) && !isset($result["rules"]["month-week-day"])
&& !isset($result["rules"]["day-hour"]) && !isset($result["rules"]["hour-minute"])
&& !isset($result["rules"]["minute-second"])){
$cal = new DateTime($starttime["year"]."-".$starttime["month"]."-".$starttime["day"]
." ".$starttime["hour"].":".$starttime["minute"].":".$starttime["second"]);
$dow = $cal->format("N");
$result["rules"]["year-week-day"] = array( array("day"=>$dow) );
}
// fall through
case "daily":
if(!isset($result["rules"]["day-hour"]) && !isset($result["rules"]["hour-minute"])
&& !isset($result["rules"]["minute-second"])){
$result["rules"]["day-hour"] = array( $starttime["hour"] );
}
// fall through
case "hourly":
if(!isset($result["rules"]["hour-minute"]) && !isset($result["rules"]["minute-second"])){
$result["rules"]["hour-minute"] = array( $starttime["minute"] );
}
// fall through
case "minutely":
if(!isset($result["rules"]["minute-second"])){
$result["rules"]["minute-second"] = array( $starttime["second"] );
}
// fall through
case "secondly":
break; // nothing
default: return "ICalendar: invalid FREQ value '".$rrule["freq"]."'";
}
return $result;
}
private function convert_recurrence($rruleprops,$exruleprops,$rdateprops,$exdateprops,$starttime){
if($rruleprops===NULL && $rdateprops===NULL) return "ICalendar: Must specify RRULE or RDATE";
$results = array( "include"=>array(), "exclude"=>array() );
if($rruleprops!==NULL){
foreach($rruleprops as $rruleprop){
foreach($rruleprop["value"] as $rrule){
$result = $this->convert_recur_rule($rrule,$starttime);
if(is_string($result)) return $result;
array_push($results["include"],$result);
}
}
}
if($exruleprops!==NULL){
foreach($exruleprops as $exruleprop){
foreach($exruleprop["value"] as $exrule){
$result = $this->convert_recur_rule($exrule,$starttime);
if(is_string($result)) return $result;
array_push($results["exclude"],$result);
}
}
}
if($rdateprops!==NULL){
foreach($rdateprops as $rdateprop){
$rdtimes = $this->convert_datetime($rdateprop);
if(is_string($rdtimes)) return $rdtimes;
foreach($rdtimes as $rdtime){
$result = array( "start"=>$starttime, "rules"=>array(
"year"=>array($rdtime["year"]), "year-month"=>array($rdtime["month"]),
"month-day"=>array($rdtime["day"]),"day-hour"=>array($rdtime["hour"]),
"hour-minute"=>array($rdtime["minute"]), "minute-second"=>array($rdtime["second"])
), "week-start"=>1 );
array_push($results["include"],$result);
}
}
}
if($exdateprops!==NULL){
foreach($exdateprops as $exdateprop){
$edtimes = $this->convert_datetime($exdateprop);
if(is_string($edtimes)) return $edtimes;
foreach($edtimes as $edtime){
$result = array( "start"=>$starttime, "rules"=>array(
"year"=>array($edtime["year"]), "year-month"=>array($edtime["month"]),
"month-day"=>array($edtime["day"]),"day-hour"=>array($edtime["hour"]),
"hour-minute"=>array($edtime["minute"]), "minute-second"=>array($edtime["second"])
), "week-start"=>1 );
array_push($results["exclude"],$result);
}
}
}
return $results;
}
}
class LocalICalendarInput extends ICalendarInputBase {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "icalendar-local") return FALSE;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok);
if($result === FALSE) return TRUE;
return $result;
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
if(!file_exists($this->get_filepath($scriptdir,$scriptname))) return FALSE;
$result = write_config($scriptdir,$scriptname,array("format"=>"icalendar-local"));
if($result) return $result;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok);
if($result === FALSE) return TRUE;
return $result;
}
private function get_filepath($scriptdir,$scriptname){
return $scriptdir."/".$scriptname."-master.ics";
}
private function do_input($filepath){
$handle = @fopen($filepath,"r");
if($handle === FALSE) return "ICalendar: Failed to open '$filepath'";
$data = $this->feed_to_event_data($handle);
fclose($handle);
return $data;
}
private function input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok){
$filepath = $this->get_filepath($scriptdir,$scriptname);
if(!$this->file_read_due($filepath,$cachedtime,$oldestinputok)) return FALSE;
$error = $this->check_cached_error($scriptdir,$scriptname);
if($error) return $error;
$data = $this->do_input($filepath);
if(is_string($data)) $this->cache_error($scriptdir,$scriptname,$data);
return $data;
}
}
class RemoteICalendarInput extends ICalendarInputBase {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "icalendar-remote") return FALSE;
if(!isset($config["url"])) return "ICalendar: missing config parameter: 'url'";
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config["url"]);
if($result === FALSE) return TRUE;
return $result;
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
if(!isset($config["url"])) return FALSE;
if(strtolower(substr($config["url"],-4,4)) != ".ics"
&& strtolower(substr($config["url"],-5,5)) != ".ical"
&& strtolower(substr($config["url"],-10,10)) != ".icalendar")
return FALSE;
$result = write_config($scriptdir,$scriptname,array("format"=>"icalendar-remote","url"=>$config["url"]));
if($result) return $result;
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config["url"]);
if($result === FALSE) return TRUE;
return $result;
}
private function do_input($url){
$handle = http_request($url);
if(is_string($handle)) return "ICalendar: $handle";
$result = $this->feed_to_event_data($handle);
fclose($handle);
return $result;
}
protected function input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$url){
if(!$this->url_read_due($cachedtime,$oldestinputok)) return FALSE;
$error = $this->check_cached_error($scriptdir,$scriptname);
if($error) return $error;
$result = $this->do_input($url);
if(is_string($result)) $this->cache_error($scriptdir,$scriptname,$result);
return $result;
}
}
class RemoteOpenACalendarInput extends RemoteICalendarInput {
public function attempt_handle_by_name($scriptdir,$scriptname,$formatname,$cachedtime,$oldestinputok,$config){
if($formatname != "openacalendar-remote") return FALSE;
if(!isset($config["url"])) return "OpenACalendar: missing config parameter: 'url'";
$url = 'http://' . $config['url'] . '/api1';
if (isset($config['group']) && $config['group']) {
$url .= '/group/'. $config['group'];
} else if (isset($config['venue']) && $config['venue']) {
$url .= '/venue/'.$config['venue'];
} else if (isset($config['area']) && $config['area']) {
$url .= '/area/'.$config['area'];
} else if (isset($config['curated_list']) && $config['curated_list']) {
$url .= '/curatedlist/'.$config['curated_list'];
} else if (isset($config['country']) && $config['country']) {
$url .= '/country/'.$config['country'];
}
$url .= '/events.ical';
$result = $this->input_if_necessary($scriptdir,$scriptname,$cachedtime,$oldestinputok,$url);
if($result === FALSE) return TRUE;
return $result;
}
public function attempt_handle_by_discovery($scriptdir,$scriptname,$cachedtime,$oldestinputok,$config){
return FALSE; // discovery not supported
}
}
abstract class CsvInputBase extends InputFormat {
protected $COL_PATTERNS = array(
"name" => "/^\\s*(name|title|summary|subject)\\s*$/i",
"description" => "/^\\s*(desc(ription)?)\\s*$/i",
"url" => "/^\\s*(url|uri|href|link|website)\\s*$/i",
"start-date" => "/^\\s*(date|start\\W*date|dtstart|start)\\s*$/i",
"start-time" => "/^\\s*(time|start\\W*time)\\s*$/i",
"end-date" => "/^\\s*(end\\W*date|dtend|end)\\s*$/i",
"end-time" => "/^\\s*(end\\W*time)\\s*$/i",
"duration" => "/^\\s*(dur(ation)?|length)\\s*$/i",
);
protected function stream_to_event_data($handle,$delimiter){
$header = @fgetcsv($handle,0,$delimiter);
if($header === FALSE){
return "CSV: Failed to read header row";
}
if(sizeof($header)==0){
return "CSV: No columns in header row";
}
$colmap = array();
foreach($header as $index => $label){
foreach($this->COL_PATTERNS as $col => $pattern){
if(preg_match($pattern,$label)){
$colmap[$col] = $index;
break;
}
}
}
foreach(array("name","start-date") as $req_key){
if(!array_key_exists($req_key,$colmap)){
return "CSV: Required column '$req_key' not found in header";
}
}
$data = new stdClass();
$data->events= array();
$data->{"recurring-events"} = array();
while( ($row = fgetcsv($handle,0,$delimiter)) !== FALSE ){
if(sizeof($row)==0 || (sizeof($row)==1 && $row[0]==NULL)) continue; # ignore blank lines
while(sizeof($row) < sizeof($colmap)) array_push($row,"");
$event = new stdClass();
$namestr = trim($row[$colmap["name"]]);
if(strlen($namestr)==0) return "CSV: Missing 'name' value";
$event->name = $namestr;
$starttime = array( "hour"=>0, "minute"=>0, "second"=>0 );
if(array_key_exists("start-time",$colmap)){
$starttstr = trim($row[$colmap["start-time"]]);
if(strlen($starttstr) > 0){
$parsed = parse_time($starttstr);
if($parsed===FALSE) return "CSV: Invalid start time format - expected 'hh:mm' or similar";
$starttime = $parsed;
}
}
$startdate = NULL;
$startdstr = trim($row[$colmap["start-date"]]);
if(strlen($startdstr)==0) return "CSV: Missing 'start-date' value";
$parsed = parse_datetime($startdstr);
if($parsed!==FALSE){
$startdate = $parsed;
$event->date = array( "year"=>$startdate["year"], "month"=>$startdate["month"],
"day"=>$startdate["day"] );
if($starttime["hour"]!=0 || $starttime["minute"]!=0 || $starttime["second"]!=0){
$event->time = $starttime;
}else{
$event->time = array( "hour"=>$startdate["hour"], "minute"=>$startdate["minute"],
"second"=>$startdate["second"] );
}
}else{
$parser = new RecurrenceParser();
$recur = $parser->parse(strtolower($startdstr),$starttime);
if($recur===FALSE){
return "CSV: Invalid start date format - expected date ('yyyy-mm-dd' or similar), or recurrence syntax";
}