/
Icalendar.php
1551 lines (1396 loc) · 52.8 KB
/
Icalendar.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
/**
* Copyright 2003-2015 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Mike Cochrane <mike@graftonhall.co.nz>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Icalendar
*/
/**
* Class representing iCalendar files.
*
* @author Mike Cochrane <mike@graftonhall.co.nz>
* @category Horde
* @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
* @package Icalendar
*/
class Horde_Icalendar
{
/**
* The component type of this class.
*
* @var string
*/
public $type = 'vcalendar';
/**
* The parent (containing) iCalendar object.
*
* @var Horde_Icalendar
*/
protected $_container = false;
/**
* The name/value pairs of attributes for this object (UID,
* DTSTART, etc.). Which are present depends on the object and on
* what kind of component it is.
*
* @var array
*/
protected $_attributes = array();
/**
* Any children (contained) iCalendar components of this object.
*
* @var array
*/
protected $_components = array();
/**
* According to RFC 2425, we should always use CRLF-terminated lines.
*
* @var string
*/
protected $_newline = "\r\n";
/**
* iCalendar format version (different behavior for 1.0 and 2.0 especially
* with recurring events).
*
* @var string
*/
protected $_version;
/**
* Whether entry is vcalendar 1.0, vcard 2.1 or vnote 1.1.
*
* These 'old' formats are defined by www.imc.org. The 'new' (non-old)
* formats icalendar 2.0 and vcard 3.0 are defined in rfc2426 and rfc2445
* respectively.
*/
protected $_oldFormat = true;
/**
* Constructor.
*
* @var string $version Version.
*/
public function __construct($version = '2.0')
{
$this->setAttribute('VERSION', $version);
}
/**
* Return a reference to a new component.
*
* @param string $type The type of component to return
* @param Horde_Icalendar $container A container that this component
* will be associated with.
*
* @return object Reference to a Horde_Icalendar_* object as specified.
*/
public static function newComponent($type, $container)
{
$type = Horde_String::lower($type);
$class = __CLASS__ . '_' . Horde_String::ucfirst($type);
if (class_exists($class)) {
$component = new $class();
if ($container !== false) {
$component->_container = $container;
// Use version of container, not default set by component
// constructor.
$component->setVersion($container->getAttribute('VERSION'));
}
} else {
// Should return an dummy x-unknown type class here.
$component = false;
}
return $component;
}
/**
* Sets the version of this component.
*
* @see $version
* @see $oldFormat
*
* @param string $version A float-like version string.
*/
public function setVersion($version)
{
$this->_oldFormat = $version < 2;
$this->_version = $version;
}
/**
* Sets the value of an attribute.
*
* @param string $name The name of the attribute.
* @param string $value The value of the attribute.
* @param array $params Array containing any addition parameters for
* this attribute.
* @param boolean $append True to append the attribute, False to replace
* the first matching attribute found.
* @param array $values Array representation of $value. For
* comma/semicolon seperated lists of values. If
* not set use $value as single array element.
*/
public function setAttribute($name, $value, $params = array(),
$append = true, $values = false)
{
// Make sure we update the internal format version if
// setAttribute('VERSION', ...) is called.
if ($name == 'VERSION') {
$this->setVersion($value);
if ($this->_container !== false) {
$this->_container->setVersion($value);
}
}
if (!$values) {
$values = array($value);
}
$found = false;
if (!$append) {
foreach (array_keys($this->_attributes) as $key) {
if ($this->_attributes[$key]['name'] == Horde_String::upper($name)) {
$this->_attributes[$key]['params'] = $params;
$this->_attributes[$key]['value'] = $value;
$this->_attributes[$key]['values'] = $values;
$found = true;
break;
}
}
}
if ($append || !$found) {
$this->_attributes[] = array(
'name' => Horde_String::upper($name),
'params' => $params,
'value' => $value,
'values' => $values
);
}
}
/**
* Sets parameter(s) for an (already existing) attribute. The
* parameter set is merged into the existing set.
*
* @param string $name The name of the attribute.
* @param array $params Array containing any additional parameters for
* this attribute.
*
* @return boolean True on success, false if no attribute $name exists.
*/
public function setParameter($name, $params = array())
{
$keys = array_keys($this->_attributes);
foreach ($keys as $key) {
if ($this->_attributes[$key]['name'] == $name) {
$this->_attributes[$key]['params'] = array_merge($this->_attributes[$key]['params'], $params);
return true;
}
}
return false;
}
/**
* Get the value of an attribute.
*
* @param string $name The name of the attribute.
* @param boolean $params Return the parameters for this attribute instead
* of its value.
*
* @return mixed (string) The value of the attribute.
* (array) The parameters for the attribute or
* multiple values for an attribute.
* @throws Horde_Icalendar_Exception
*/
public function getAttribute($name, $params = false)
{
if ($name == 'VERSION') {
return $this->_version;
}
$result = array();
foreach ($this->_attributes as $attribute) {
if ($attribute['name'] == $name) {
$result[] = $params
? $attribute['params']
: $attribute['value'];
}
}
if (!count($result)) {
throw new Horde_Icalendar_Exception('Attribute "' . $name . '" Not Found');
} elseif (count($result) == 1 && !$params) {
return $result[0];
}
return $result;
}
/**
* Get a single value of an attribute.
*
* If multiple values, is auto-determined by library which is preferred
* value to return.
*
* @since 2.1.0
*
* @param string $name The name of the attribute.
*
* @return string The value of the attribute.
* @throws Horde_Icalendar_Exception
*/
public function getAttributeSingle($name)
{
$out = $this->getAttribute($name, false);
return is_array($out)
? reset($out)
: $out;
}
/**
* Gets the values of an attribute as an array. Multiple values
* are possible due to:
*
* a) multiple occurences of 'name'
* b) (unsecapd) comma seperated lists.
*
* So for a vcard like "KEY:a,b\nKEY:c" getAttributesValues('KEY')
* will return array('a', 'b', 'c').
*
* @param string $name The name of the attribute.
*
* @return array Multiple values for an attribute.
* @throws Horde_Icalendar_Exception
*/
public function getAttributeValues($name)
{
$result = array();
foreach ($this->_attributes as $attribute) {
if ($attribute['name'] == $name) {
$result = array_merge($attribute['values'], $result);
}
}
if (!count($result)) {
throw new Horde_Icalendar_Exception('Attribute "' . $name . '" Not Found');
}
return $result;
}
/**
* Returns the value of an attribute, or a specified default value
* if the attribute does not exist.
*
* @param string $name The name of the attribute.
* @param mixed $default What to return if the attribute specified by
* $name does not exist.
*
* @return mixed (mixed) The value of $name.
* (mixed) $default if $name does not exist.
*/
public function getAttributeDefault($name, $default = '')
{
try {
return $this->getAttribute($name);
} catch (Horde_Icalendar_Exception $e) {
return $default;
}
}
/**
* Remove all occurences of an attribute.
*
* @param string $name The name of the attribute.
*/
public function removeAttribute($name)
{
foreach (array_keys($this->_attributes) as $key) {
if ($this->_attributes[$key]['name'] == $name) {
unset($this->_attributes[$key]);
}
}
}
/**
* Get attributes for all tags or for a given tag.
*
* @param string $tag Return attributes for this tag, or all attributes
* if not given.
*
* @return array An array containing all the attributes and their types.
*/
public function getAllAttributes($tag = false)
{
if ($tag === false) {
return $this->_attributes;
}
$result = array();
foreach ($this->_attributes as $attribute) {
if ($attribute['name'] == $tag) {
$result[] = $attribute;
}
}
return $result;
}
/**
* Add a vCalendar component (eg vEvent, vTimezone, etc.).
*
* @param mixed Either a Horde_Icalendar component (subclass) or an array
* of them.
*/
public function addComponent($components)
{
if (!is_array($components)) {
$components = array($components);
}
foreach ($components as $component) {
if ($component instanceof Horde_Icalendar) {
$component->_container = $this;
$this->_components[] = $component;
}
}
}
/**
* Retrieve all the components.
*
* @return array Array of Horde_Icalendar objects.
*/
public function getComponents()
{
return $this->_components;
}
/**
* TODO
*
* @return TODO
*/
public function getType()
{
return $this->type;
}
/**
* Return the classes (entry types) we have.
*
* @return array Hash with class names Horde_Icalendar_xxx as keys
* and number of components of this class as value.
*/
public function getComponentClasses()
{
$r = array();
foreach ($this->_components as $c) {
$cn = Horde_String::lower(get_class($c));
if (empty($r[$cn])) {
$r[$cn] = 1;
} else {
++$r[$cn];
}
}
return $r;
}
/**
* Number of components in this container.
*
* @return integer Number of components in this container.
*/
public function getComponentCount()
{
return count($this->_components);
}
/**
* Retrieve a specific component.
*
* @param integer $idx The index of the object to retrieve.
*
* @return mixed (boolean) False if the index does not exist.
* (Horde_Icalendar_*) The requested component.
*/
public function getComponent($idx)
{
return isset($this->_components[$idx])
? $this->_components[$idx]
: false;
}
/**
* Locates the first child component of the specified class, and returns a
* reference to it.
*
* @param string $type The type of component to find.
*
* @return boolean|Horde_Icalendar_* False if no subcomponent of the
* specified class exists or the
* requested component.
*/
public function findComponent($childclass)
{
$childclass = __CLASS__ . '_' . Horde_String::lower($childclass);
foreach (array_keys($this->_components) as $key) {
if ($this->_components[$key] instanceof $childclass) {
return $this->_components[$key];
}
}
return false;
}
/**
* Locates the first matching child component of the specified class, and
* returns a reference to it.
*
* @param string $childclass The type of component to find.
* @param string $attribute This attribute must be set in the component
* for it to match.
* @param string $value Optional value that $attribute must match.
*
* @return boolean|Horde_Icalendar_* False if no matching subcomponent
* of the specified class exists, or
* the requested component.
*/
public function findComponentByAttribute($childclass, $attribute,
$value = null)
{
$childclass = __CLASS__ . '_' . Horde_String::lower($childclass);
foreach (array_keys($this->_components) as $key) {
if ($this->_components[$key] instanceof $childclass) {
try {
$attr = $this->_components[$key]->getAttribute($attribute);
} catch (Horde_Icalendar_Exception $e) {
continue;
}
if (is_null($value) || $value == $attr) {
return $this->_components[$key];
}
}
}
return false;
}
/**
* Clears the iCalendar object (resets the components and attributes
* arrays).
*/
public function clear()
{
$this->_attributes = $this->_components = array();
}
public function toString() { return $this->exportvCalendar(); }
/**
* Export as vCalendar format.
*
* @return TODO
*/
public function exportvCalendar()
{
// Default values.
// TODO: HORDE_VERSION does not exist.
$requiredAttributes['PRODID'] = '-//The Horde Project//Horde iCalendar Library' . (defined('HORDE_VERSION') ? ', Horde ' . constant('HORDE_VERSION') : '') . '//EN';
foreach ($requiredAttributes as $name => $default_value) {
try {
$this->getAttribute($name);
} catch (Horde_Icalendar_Exception $e) {
$this->setAttribute($name, $default_value);
}
}
return $this->_exportvData('VCALENDAR');
}
/**
* Export this entry as a hash array with tag names as keys.
*
* @param boolean $paramsInKeys If false, the operation can be quite
* lossy as the parameters are ignored when
* building the array keys.
* So if you export a vcard with
* LABEL;TYPE=WORK:foo
* LABEL;TYPE=HOME:bar
* the resulting hash contains only one
* label field!
* If set to true, array keys look like
* 'LABEL;TYPE=WORK'
*
* @return array A hash array with tag names as keys.
*/
public function toHash($paramsInKeys = false)
{
$hash = array();
foreach ($this->_attributes as $a) {
$k = $a['name'];
if ($paramsInKeys && is_array($a['params'])) {
foreach ($a['params'] as $p => $v) {
$k .= ";$p=$v";
}
}
$hash[$k] = $a['value'];
}
return $hash;
}
/**
* Parses a string containing vCalendar data.
*
* @todo This method doesn't work well at all, if $base is VCARD.
*
* @param string $text The data to parse.
* @param string $base The type of the base object.
* @param boolean $clear If true clears this object before parsing.
*
* @return boolean True on successful import, false otherwise.
* @throws Horde_Icalendar_Exception
*/
public function parsevCalendar($text, $base = 'VCALENDAR', $clear = true)
{
if ($clear) {
$this->clear();
}
$text = Horde_String::trimUtf8Bom($text);
if (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
$container = true;
$vCal = $matches[1];
} else {
// Text isn't enclosed in BEGIN:VCALENDAR
// .. END:VCALENDAR. We'll try to parse it anyway.
$container = false;
$vCal = $text;
}
$vCal = trim($vCal);
// Extract all subcomponents.
$matches = $components = null;
if (preg_match_all('/^BEGIN:(.*)\s*?(\r\n|\r|\n)(.*)^END:\1\s*?/Uims', $vCal, $components)) {
foreach ($components[0] as $key => $data) {
// Remove from the vCalendar data.
$vCal = str_replace($data, '', $vCal);
}
} elseif (!$container) {
return false;
}
// Unfold "quoted printable" folded lines like:
// BODY;ENCODING=QUOTED-PRINTABLE:=
// another=20line=
// last=20line
while (preg_match_all('/^([^:]+;\s*(ENCODING=)?QUOTED-PRINTABLE(.*=\r?\n)+(.*[^=])?(\r?\n|$))/mU', $vCal, $matches)) {
foreach ($matches[1] as $s) {
$r = preg_replace('/=\r?\n/', '', $s);
$vCal = str_replace($s, $r, $vCal);
}
}
// Unfold any folded lines.
$vCal = preg_replace('/[\r\n]+[ \t]/', '', $vCal);
// Parse the remaining attributes.
if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches)) {
foreach ($matches[0] as $attribute) {
preg_match('/([^;^:]*)((;(?:[^":]+|(?:"[^"]*")+)*)?):([^\r\n]*)[\r\n]*/', $attribute, $parts);
$tag = trim(preg_replace('/^.*\./', '', Horde_String::upper($parts[1])));
$value = $parts[4];
$params = array();
// Parse parameters.
if (!empty($parts[2])) {
preg_match_all('/;(([^;=]*)(=("[^"]*"|[^;]*))?)/', $parts[2], $param_parts);
foreach ($param_parts[2] as $key => $paramName) {
$paramName = Horde_String::upper($paramName);
$paramValue = $param_parts[4][$key];
if ($paramName == 'TYPE') {
$paramValue = preg_split('/(?<!\\\\),/', $paramValue);
if (count($paramValue) == 1) {
$paramValue = $paramValue[0];
}
}
if (is_string($paramValue)) {
if (preg_match('/"([^"]*)"/', $paramValue, $parts)) {
$paramValue = $parts[1];
}
} else {
foreach ($paramValue as $k => $tmp) {
if (preg_match('/"([^"]*)"/', $tmp, $parts)) {
$paramValue[$k] = $parts[1];
}
}
}
if (isset($params[$paramName])) {
if (is_array($params[$paramName])) {
$params[$paramName][] = $paramValue;
} else {
$params[$paramName] = array($params[$paramName], $paramValue);
}
} else {
$params[$paramName] = $paramValue;
}
}
}
// Charset and encoding handling.
if ((isset($params['ENCODING']) &&
Horde_String::upper($params['ENCODING']) == 'QUOTED-PRINTABLE') ||
isset($params['QUOTED-PRINTABLE'])) {
$value = quoted_printable_decode($value);
if (isset($params['CHARSET'])) {
$value = Horde_String::convertCharset($value, $params['CHARSET'], 'UTF-8');
}
} elseif (isset($params['CHARSET'])) {
$value = Horde_String::convertCharset($value, $params['CHARSET'], 'UTF-8');
}
// Get timezone info for date fields from $params.
$tzid = isset($params['TZID']) ? trim($params['TZID'], '\"') : false;
switch ($tag) {
// Date fields.
case 'COMPLETED':
case 'CREATED':
case 'LAST-MODIFIED':
case 'X-MOZ-LASTACK':
case 'X-MOZ-SNOOZE-TIME':
$this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
break;
case 'BDAY':
case 'X-ANNIVERSARY':
$this->setAttribute($tag, $this->_parseDate($value), $params);
break;
case 'DTEND':
case 'DTSTART':
case 'DTSTAMP':
case 'DUE':
case 'AALARM':
case 'RECURRENCE-ID':
// types like AALARM may contain additional data after a ;
// ignore these.
$ts = explode(';', $value);
if (isset($params['VALUE']) && $params['VALUE'] == 'DATE') {
$this->setAttribute($tag, $this->_parseDate($ts[0]), $params);
} else {
$this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params);
}
break;
case 'TRIGGER':
if (isset($params['VALUE']) &&
$params['VALUE'] == 'DATE-TIME') {
$this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
} else {
$this->setAttribute($tag, $this->_parseDuration($value), $params);
}
break;
// Comma seperated dates.
case 'EXDATE':
case 'RDATE':
if (!strlen($value)) {
break;
}
$dates = array();
$separator = $this->_oldFormat ? ';' : ',';
preg_match_all('/' . $separator . '([^' . $separator . ']*)/', $separator . $value, $values);
foreach ($values[1] as $value) {
$stamp = $this->_parseDateTime($value);
if (!is_int($stamp)) {
continue;
}
$dates[] = array('year' => date('Y', $stamp),
'month' => date('m', $stamp),
'mday' => date('d', $stamp));
}
$this->setAttribute($tag, isset($dates[0]) ? $dates[0] : null, $params, true, $dates);
break;
// Duration fields.
case 'DURATION':
$this->setAttribute($tag, $this->_parseDuration($value), $params);
break;
// Period of time fields.
case 'FREEBUSY':
$periods = array();
preg_match_all('/,([^,]*)/', ',' . $value, $values);
foreach ($values[1] as $value) {
$periods[] = $this->_parsePeriod($value);
}
$this->setAttribute($tag, isset($periods[0]) ? $periods[0] : null, $params, true, $periods);
break;
// UTC offset fields.
case 'TZOFFSETFROM':
case 'TZOFFSETTO':
$this->setAttribute($tag, $this->_parseUtcOffset($value), $params);
break;
// Integer fields.
case 'PERCENT-COMPLETE':
case 'PRIORITY':
case 'REPEAT':
case 'SEQUENCE':
$this->setAttribute($tag, intval($value), $params);
break;
// Geo fields.
case 'GEO':
if ($value) {
if ($this->_oldFormat) {
$floats = explode(',', $value);
$value = array('latitude' => floatval($floats[1]),
'longitude' => floatval($floats[0]));
} else {
$floats = explode(';', $value);
$value = array('latitude' => floatval($floats[0]),
'longitude' => floatval($floats[1]));
}
}
$this->setAttribute($tag, $value, $params);
break;
// Recursion fields.
case 'EXRULE':
case 'RRULE':
$this->setAttribute($tag, trim($value), $params);
break;
// ADR, ORG and N are lists seperated by unescaped semicolons
// with a specific number of slots.
case 'ADR':
case 'N':
case 'ORG':
$value = trim($value);
// As of rfc 2426 2.4.2 semicolon, comma, and colon must
// be escaped (comma is unescaped after splitting below).
$value = str_replace(array('\\n', '\\N', '\\;', '\\:'),
array($this->_newline, $this->_newline, ';', ':'),
$value);
// Split by unescaped semicolons:
$values = preg_split('/(?<!\\\\);/', $value);
$value = str_replace('\\;', ';', $value);
$values = str_replace('\\;', ';', $values);
$this->setAttribute($tag, trim($value), $params, true, $values);
break;
// String fields.
default:
if ($this->_oldFormat) {
// vCalendar 1.0 and vCard 2.1 only escape semicolons
// and use unescaped semicolons to create lists.
$value = trim($value);
// Split by unescaped semicolons:
$values = preg_split('/(?<!\\\\);/', $value);
$value = str_replace('\\;', ';', $value);
$values = str_replace('\\;', ';', $values);
$this->setAttribute($tag, trim($value), $params, true, $values);
} else {
$value = trim($value);
// As of rfc 2426 2.4.2 semicolon, comma, and colon
// must be escaped (comma is unescaped after splitting
// below).
$value = str_replace(array('\\n', '\\N', '\\;', '\\:', '\\\\'),
array($this->_newline, $this->_newline, ';', ':', '\\'),
$value);
// Split by unescaped commas.
$values = preg_split('/(?<!\\\\),/', $value);
$value = str_replace('\\,', ',', $value);
$values = str_replace('\\,', ',', $values);
$this->setAttribute($tag, trim($value), $params, true, $values);
}
break;
}
}
}
// Process all components.
if ($components) {
// vTimezone components are processed first. They are
// needed to process vEvents that may use a TZID.
foreach ($components[0] as $key => $data) {
$type = trim($components[1][$key]);
if ($type != 'VTIMEZONE') {
continue;
}
$component = $this->newComponent($type, $this);
if ($component === false) {
throw new Horde_Icalendar_Exception('Unable to create object for type ' . $type);
}
$component->parsevCalendar($data, $type);
$this->addComponent($component);
// Remove from the vCalendar data.
$vCal = str_replace($data, '', $vCal);
}
// Now process the non-vTimezone components.
foreach ($components[0] as $key => $data) {
$type = trim($components[1][$key]);
if ($type == 'VTIMEZONE') {
continue;
}
$component = $this->newComponent($type, $this);
if ($component === false) {
throw new Horde_Icalendar_Exception('Unable to create object for type ' . $type);
}
$component->parsevCalendar($data, $type);
$this->addComponent($component);
}
}
return true;
}
/**
* Export this component in vCal format.
*
* @param string $base The type of the base object.
*
* @return string vCal format data.
*/
protected function _exportvData($base = 'VCALENDAR')
{
$result = 'BEGIN:' . Horde_String::upper($base) . $this->_newline;
// VERSION is not allowed for entries enclosed in VCALENDAR/ICALENDAR,
// as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
if ($base !== 'VEVENT' && $base !== 'VTODO' && $base !== 'VALARM' &&
$base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
$base != 'VTIMEZONE' && $base != 'STANDARD' && $base != 'DAYLIGHT') {
// Ensure that version is the first attribute.
$result .= 'VERSION:' . $this->_version . $this->_newline;
}
foreach ($this->_attributes as $attribute) {
$name = $attribute['name'];
if ($name == 'VERSION') {
// Already done.
continue;
}
$params_str = '';
$params = $attribute['params'];
if ($params) {
foreach ($params as $param_name => $param_value) {
/* Skip CHARSET for iCalendar 2.0 data, not allowed. */
if ($param_name == 'CHARSET' && !$this->_oldFormat) {
continue;
}
/* Skip VALUE=DATE for vCalendar 1.0 data, not allowed. */
if ($this->_oldFormat &&
$param_name == 'VALUE' && $param_value == 'DATE') {
continue;
}
if ($param_value === null) {
$params_str .= ";$param_name";
} else {
if (!is_array($param_value)) {
$param_value = array($param_value);
}
foreach ($param_value as &$one_param_value) {
$len = strlen($one_param_value);
$safe_value = '';
$quote = false;
for ($i = 0; $i < $len; ++$i) {
$ord = ord($one_param_value[$i]);
// Accept only valid characters.
if ($ord == 9 || $ord == 32 || $ord == 33 ||
($ord >= 35 && $ord <= 126) ||
$ord >= 128) {
$safe_value .= $one_param_value[$i];
// Characters above 128 do not need to be
// quoted as per RFC2445 but Outlook requires
// this.
if ($ord == 44 || $ord == 58 || $ord == 59 ||
$ord >= 128) {
$quote = true;
}
}
}
if ($quote) {
$safe_value = '"' . $safe_value . '"';
}
$one_param_value = $safe_value;
}
$params_str .= ";$param_name=" . implode(',', $param_value);
}
}
}
$value = $attribute['value'];
switch ($name) {
// Date fields.
case 'COMPLETED':
case 'CREATED':
case 'DCREATED':
case 'LAST-MODIFIED':
case 'X-MOZ-LASTACK':
case 'X-MOZ-SNOOZE-TIME':
$value = $this->_exportDateTime($value);
break;
case 'DTEND':
case 'DTSTART':
case 'DTSTAMP':
case 'DUE':
case 'AALARM':
case 'RECURRENCE-ID':
$floating = $base == 'STANDARD'
|| $base == 'DAYLIGHT'
|| isset($params['TZID']);
if (isset($params['VALUE'])) {
if ($params['VALUE'] == 'DATE') {
// VCALENDAR 1.0 uses T000000 - T235959 for all day events:
if ($this->_oldFormat && $name == 'DTEND') {
$d = new Horde_Date($value);
$value = new Horde_Date(array(
'year' => $d->year,
'month' => $d->month,
'mday' => $d->mday - 1));
$value = $this->_exportDate($value, '235959');
} else {
$value = $this->_exportDate($value, '000000');
}
} else {
$value = $this->_exportDateTime($value, $floating);
}
} else {
$value = $this->_exportDateTime($value, $floating);
}
break;