~ubuntu-branches/ubuntu/vivid/php-horde-icalendar/vivid-proposed

« back to all changes in this revision

Viewing changes to Horde_Icalendar-2.0.8/lib/Horde/Icalendar.php

  • Committer: Package Import Robot
  • Author(s): Mathieu Parent
  • Date: 2014-06-05 20:31:26 UTC
  • mfrom: (1.1.8)
  • Revision ID: package-import@ubuntu.com-20140605203126-geamf8wv7cvfrruh
Tags: 2.0.9-1
New upstream version 2.0.9

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
<?php
2
 
/**
3
 
 * @category Horde
4
 
 * @package  Icalendar
5
 
 */
6
 
 
7
 
/**
8
 
 * Class representing iCalendar files.
9
 
 *
10
 
 * Copyright 2003-2014 Horde LLC (http://www.horde.org/)
11
 
 *
12
 
 * See the enclosed file COPYING for license information (LGPL). If you
13
 
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
14
 
 *
15
 
 * @author   Mike Cochrane <mike@graftonhall.co.nz>
16
 
 * @category Horde
17
 
 * @license  http://www.horde.org/licenses/lgpl21 LGPL 2.1
18
 
 * @package  Icalendar
19
 
 */
20
 
class Horde_Icalendar
21
 
{
22
 
    /**
23
 
     * The component type of this class.
24
 
     *
25
 
     * @var string
26
 
     */
27
 
    public $type = 'vcalendar';
28
 
 
29
 
    /**
30
 
     * The parent (containing) iCalendar object.
31
 
     *
32
 
     * @var Horde_Icalendar
33
 
     */
34
 
    protected $_container = false;
35
 
 
36
 
    /**
37
 
     * The name/value pairs of attributes for this object (UID,
38
 
     * DTSTART, etc.). Which are present depends on the object and on
39
 
     * what kind of component it is.
40
 
     *
41
 
     * @var array
42
 
     */
43
 
    protected $_attributes = array();
44
 
 
45
 
    /**
46
 
     * Any children (contained) iCalendar components of this object.
47
 
     *
48
 
     * @var array
49
 
     */
50
 
    protected $_components = array();
51
 
 
52
 
    /**
53
 
     * According to RFC 2425, we should always use CRLF-terminated lines.
54
 
     *
55
 
     * @var string
56
 
     */
57
 
    protected $_newline = "\r\n";
58
 
 
59
 
    /**
60
 
     * iCalendar format version (different behavior for 1.0 and 2.0 especially
61
 
     * with recurring events).
62
 
     *
63
 
     * @var string
64
 
     */
65
 
    protected $_version;
66
 
 
67
 
    /**
68
 
     * Whether entry is vcalendar 1.0, vcard 2.1 or vnote 1.1.
69
 
     *
70
 
     * These 'old' formats are defined by www.imc.org. The 'new' (non-old)
71
 
     * formats icalendar 2.0 and vcard 3.0 are defined in rfc2426 and rfc2445
72
 
     * respectively.
73
 
     */
74
 
    protected $_oldFormat = true;
75
 
 
76
 
    /**
77
 
     * Constructor.
78
 
     *
79
 
     * @var string $version  Version.
80
 
     */
81
 
    public function __construct($version = '2.0')
82
 
    {
83
 
        $this->setAttribute('VERSION', $version);
84
 
    }
85
 
 
86
 
    /**
87
 
     * Return a reference to a new component.
88
 
     *
89
 
     * @param string $type                The type of component to return
90
 
     * @param Horde_Icalendar $container  A container that this component
91
 
     *                                    will be associated with.
92
 
     *
93
 
     * @return object  Reference to a Horde_Icalendar_* object as specified.
94
 
     */
95
 
    static public function newComponent($type, $container)
96
 
    {
97
 
        $type = Horde_String::lower($type);
98
 
        $class = __CLASS__ . '_' . Horde_String::ucfirst($type);
99
 
 
100
 
        if (class_exists($class)) {
101
 
            $component = new $class();
102
 
            if ($container !== false) {
103
 
                $component->_container = $container;
104
 
                // Use version of container, not default set by component
105
 
                // constructor.
106
 
                $component->setVersion($container->getAttribute('VERSION'));
107
 
            }
108
 
        } else {
109
 
            // Should return an dummy x-unknown type class here.
110
 
            $component = false;
111
 
        }
112
 
 
113
 
        return $component;
114
 
    }
115
 
 
116
 
    /**
117
 
     * Sets the version of this component.
118
 
     *
119
 
     * @see $version
120
 
     * @see $oldFormat
121
 
     *
122
 
     * @param string $version  A float-like version string.
123
 
     */
124
 
    public function setVersion($version)
125
 
    {
126
 
        $this->_oldFormat = $version < 2;
127
 
        $this->_version = $version;
128
 
    }
129
 
 
130
 
    /**
131
 
     * Sets the value of an attribute.
132
 
     *
133
 
     * @param string $name     The name of the attribute.
134
 
     * @param string $value    The value of the attribute.
135
 
     * @param array $params    Array containing any addition parameters for
136
 
     *                         this attribute.
137
 
     * @param boolean $append  True to append the attribute, False to replace
138
 
     *                         the first matching attribute found.
139
 
     * @param array $values    Array representation of $value.  For
140
 
     *                         comma/semicolon seperated lists of values.  If
141
 
     *                         not set use $value as single array element.
142
 
     */
143
 
    public function setAttribute($name, $value, $params = array(),
144
 
                                 $append = true, $values = false)
145
 
    {
146
 
        // Make sure we update the internal format version if
147
 
        // setAttribute('VERSION', ...) is called.
148
 
        if ($name == 'VERSION') {
149
 
            $this->setVersion($value);
150
 
            if ($this->_container !== false) {
151
 
                $this->_container->setVersion($value);
152
 
            }
153
 
        }
154
 
 
155
 
        if (!$values) {
156
 
            $values = array($value);
157
 
        }
158
 
        $found = false;
159
 
 
160
 
        if (!$append) {
161
 
            foreach (array_keys($this->_attributes) as $key) {
162
 
                if ($this->_attributes[$key]['name'] == Horde_String::upper($name)) {
163
 
                    $this->_attributes[$key]['params'] = $params;
164
 
                    $this->_attributes[$key]['value'] = $value;
165
 
                    $this->_attributes[$key]['values'] = $values;
166
 
                    $found = true;
167
 
                    break;
168
 
                }
169
 
            }
170
 
        }
171
 
 
172
 
        if ($append || !$found) {
173
 
            $this->_attributes[] = array(
174
 
                'name'      => Horde_String::upper($name),
175
 
                'params'    => $params,
176
 
                'value'     => $value,
177
 
                'values'    => $values
178
 
            );
179
 
        }
180
 
    }
181
 
 
182
 
    /**
183
 
     * Sets parameter(s) for an (already existing) attribute.  The
184
 
     * parameter set is merged into the existing set.
185
 
     *
186
 
     * @param string $name   The name of the attribute.
187
 
     * @param array $params  Array containing any additional parameters for
188
 
     *                       this attribute.
189
 
     *
190
 
     * @return boolean  True on success, false if no attribute $name exists.
191
 
     */
192
 
    public function setParameter($name, $params = array())
193
 
    {
194
 
        $keys = array_keys($this->_attributes);
195
 
        foreach ($keys as $key) {
196
 
            if ($this->_attributes[$key]['name'] == $name) {
197
 
                $this->_attributes[$key]['params'] = array_merge($this->_attributes[$key]['params'], $params);
198
 
                return true;
199
 
            }
200
 
        }
201
 
 
202
 
        return false;
203
 
    }
204
 
 
205
 
    /**
206
 
     * Get the value of an attribute.
207
 
     *
208
 
     * @param string $name     The name of the attribute.
209
 
     * @param boolean $params  Return the parameters for this attribute instead
210
 
     *                         of its value.
211
 
     *
212
 
     * @return mixed (string)  The value of the attribute.
213
 
     *               (array)   The parameters for the attribute or
214
 
     *                         multiple values for an attribute.
215
 
     * @throws Horde_Icalendar_Exception
216
 
     */
217
 
    public function getAttribute($name, $params = false)
218
 
    {
219
 
        if ($name == 'VERSION') {
220
 
            return $this->_version;
221
 
        }
222
 
 
223
 
        $result = array();
224
 
        foreach ($this->_attributes as $attribute) {
225
 
            if ($attribute['name'] == $name) {
226
 
                $result[] = $params
227
 
                    ? $attribute['params']
228
 
                    : $attribute['value'];
229
 
            }
230
 
        }
231
 
 
232
 
        if (!count($result)) {
233
 
            throw new Horde_Icalendar_Exception('Attribute "' . $name . '" Not Found');
234
 
        } elseif (count($result) == 1 && !$params) {
235
 
            return $result[0];
236
 
        }
237
 
 
238
 
        return $result;
239
 
    }
240
 
 
241
 
    /**
242
 
     * Gets the values of an attribute as an array.  Multiple values
243
 
     * are possible due to:
244
 
     *
245
 
     *  a) multiple occurences of 'name'
246
 
     *  b) (unsecapd) comma seperated lists.
247
 
     *
248
 
     * So for a vcard like "KEY:a,b\nKEY:c" getAttributesValues('KEY')
249
 
     * will return array('a', 'b', 'c').
250
 
     *
251
 
     * @param string $name  The name of the attribute.
252
 
     *
253
 
     * @return array  Multiple values for an attribute.
254
 
     * @throws Horde_Icalendar_Exception
255
 
     */
256
 
    public function getAttributeValues($name)
257
 
    {
258
 
        $result = array();
259
 
        foreach ($this->_attributes as $attribute) {
260
 
            if ($attribute['name'] == $name) {
261
 
                $result = array_merge($attribute['values'], $result);
262
 
            }
263
 
        }
264
 
 
265
 
        if (!count($result)) {
266
 
            throw new Horde_Icalendar_Exception('Attribute "' . $name . '" Not Found');
267
 
        }
268
 
 
269
 
        return $result;
270
 
    }
271
 
 
272
 
    /**
273
 
     * Returns the value of an attribute, or a specified default value
274
 
     * if the attribute does not exist.
275
 
     *
276
 
     * @param string $name    The name of the attribute.
277
 
     * @param mixed $default  What to return if the attribute specified by
278
 
     *                        $name does not exist.
279
 
     *
280
 
     * @return mixed (string) The value of $name.
281
 
     *               (mixed)  $default if $name does not exist.
282
 
     */
283
 
    public function getAttributeDefault($name, $default = '')
284
 
    {
285
 
        try {
286
 
            return $this->getAttribute($name);
287
 
        } catch (Horde_Icalendar_Exception $e) {
288
 
            return $default;
289
 
        }
290
 
    }
291
 
 
292
 
    /**
293
 
     * Remove all occurences of an attribute.
294
 
     *
295
 
     * @param string $name  The name of the attribute.
296
 
     */
297
 
    public function removeAttribute($name)
298
 
    {
299
 
        foreach (array_keys($this->_attributes) as $key) {
300
 
            if ($this->_attributes[$key]['name'] == $name) {
301
 
                unset($this->_attributes[$key]);
302
 
            }
303
 
        }
304
 
    }
305
 
 
306
 
    /**
307
 
     * Get attributes for all tags or for a given tag.
308
 
     *
309
 
     * @param string $tag  Return attributes for this tag, or all attributes
310
 
     *                     if not given.
311
 
     *
312
 
     * @return array  An array containing all the attributes and their types.
313
 
     */
314
 
    public function getAllAttributes($tag = false)
315
 
    {
316
 
        if ($tag === false) {
317
 
            return $this->_attributes;
318
 
        }
319
 
 
320
 
        $result = array();
321
 
        foreach ($this->_attributes as $attribute) {
322
 
            if ($attribute['name'] == $tag) {
323
 
                $result[] = $attribute;
324
 
            }
325
 
        }
326
 
 
327
 
        return $result;
328
 
    }
329
 
 
330
 
    /**
331
 
     * Add a vCalendar component (eg vEvent, vTimezone, etc.).
332
 
     *
333
 
     * @param mixed  Either a Horde_Icalendar component (subclass) or an array
334
 
     *               of them.
335
 
     */
336
 
    public function addComponent($components)
337
 
    {
338
 
        if (!is_array($components)) {
339
 
            $components = array($components);
340
 
        }
341
 
 
342
 
        foreach ($components as $component) {
343
 
            if ($component instanceof Horde_Icalendar) {
344
 
                $component->_container = $this;
345
 
                $this->_components[] = $component;
346
 
            }
347
 
        }
348
 
    }
349
 
 
350
 
    /**
351
 
     * Retrieve all the components.
352
 
     *
353
 
     * @return array  Array of Horde_Icalendar objects.
354
 
     */
355
 
    public function getComponents()
356
 
    {
357
 
        return $this->_components;
358
 
    }
359
 
 
360
 
    /**
361
 
     * TODO
362
 
     *
363
 
     * @return TODO
364
 
     */
365
 
    public function getType()
366
 
    {
367
 
        return $this->type;
368
 
    }
369
 
 
370
 
    /**
371
 
     * Return the classes (entry types) we have.
372
 
     *
373
 
     * @return array  Hash with class names Horde_Icalendar_xxx as keys
374
 
     *                and number of components of this class as value.
375
 
     */
376
 
    public function getComponentClasses()
377
 
    {
378
 
        $r = array();
379
 
 
380
 
        foreach ($this->_components as $c) {
381
 
            $cn = strtolower(get_class($c));
382
 
            if (empty($r[$cn])) {
383
 
                $r[$cn] = 1;
384
 
            } else {
385
 
                ++$r[$cn];
386
 
            }
387
 
        }
388
 
 
389
 
        return $r;
390
 
    }
391
 
 
392
 
    /**
393
 
     * Number of components in this container.
394
 
     *
395
 
     * @return integer  Number of components in this container.
396
 
     */
397
 
    public function getComponentCount()
398
 
    {
399
 
        return count($this->_components);
400
 
    }
401
 
 
402
 
    /**
403
 
     * Retrieve a specific component.
404
 
     *
405
 
     * @param integer $idx  The index of the object to retrieve.
406
 
     *
407
 
     * @return mixed  (boolean) False if the index does not exist.
408
 
     *                (Horde_Icalendar_*) The requested component.
409
 
     */
410
 
    public function getComponent($idx)
411
 
    {
412
 
        return isset($this->_components[$idx])
413
 
            ? $this->_components[$idx]
414
 
            : false;
415
 
    }
416
 
 
417
 
    /**
418
 
     * Locates the first child component of the specified class, and returns a
419
 
     * reference to it.
420
 
     *
421
 
     * @param string $type  The type of component to find.
422
 
     *
423
 
     * @return boolean|Horde_Icalendar_*  False if no subcomponent of the
424
 
     *                                    specified class exists or the
425
 
     *                                    requested component.
426
 
     */
427
 
    public function findComponent($childclass)
428
 
    {
429
 
        $childclass = __CLASS__ . '_' . Horde_String::lower($childclass);
430
 
 
431
 
        foreach (array_keys($this->_components) as $key) {
432
 
            if ($this->_components[$key] instanceof $childclass) {
433
 
                return $this->_components[$key];
434
 
            }
435
 
        }
436
 
 
437
 
        return false;
438
 
    }
439
 
 
440
 
    /**
441
 
     * Locates the first matching child component of the specified class, and
442
 
     * returns a reference to it.
443
 
     *
444
 
     * @param string $childclass  The type of component to find.
445
 
     * @param string $attribute   This attribute must be set in the component
446
 
     *                            for it to match.
447
 
     * @param string $value       Optional value that $attribute must match.
448
 
     *
449
 
     * @return boolean|Horde_Icalendar_*  False if no matching subcomponent
450
 
     *                                    of the specified class exists, or
451
 
     *                                    the requested component.
452
 
     */
453
 
    public function findComponentByAttribute($childclass, $attribute,
454
 
                                             $value = null)
455
 
    {
456
 
        $childclass = __CLASS__ . '_' . Horde_String::lower($childclass);
457
 
 
458
 
        foreach (array_keys($this->_components) as $key) {
459
 
            if ($this->_components[$key] instanceof $childclass) {
460
 
                try {
461
 
                    $attr = $this->_components[$key]->getAttribute($attribute);
462
 
                } catch (Horde_Icalendar_Exception $e) {
463
 
                    continue;
464
 
                }
465
 
 
466
 
                if (is_null($value) || $value == $attr) {
467
 
                    return $this->_components[$key];
468
 
                }
469
 
            }
470
 
        }
471
 
 
472
 
        return false;
473
 
    }
474
 
 
475
 
    /**
476
 
     * Clears the iCalendar object (resets the components and attributes
477
 
     * arrays).
478
 
     */
479
 
    public function clear()
480
 
    {
481
 
        $this->_attributes = $this->_components = array();
482
 
    }
483
 
 
484
 
    public function toString() { return $this->exportvCalendar(); }
485
 
    /**
486
 
     * Export as vCalendar format.
487
 
     *
488
 
     * @return TODO
489
 
     */
490
 
    public function exportvCalendar()
491
 
    {
492
 
        // Default values.
493
 
        // TODO: HORDE_VERSION does not exist.
494
 
        $requiredAttributes['PRODID'] = '-//The Horde Project//Horde iCalendar Library' . (defined('HORDE_VERSION') ? ', Horde ' . constant('HORDE_VERSION') : '') . '//EN';
495
 
 
496
 
        foreach ($requiredAttributes as $name => $default_value) {
497
 
            try {
498
 
                $this->getAttribute($name);
499
 
            } catch (Horde_Icalendar_Exception $e) {
500
 
                $this->setAttribute($name, $default_value);
501
 
            }
502
 
        }
503
 
 
504
 
        return $this->_exportvData('VCALENDAR');
505
 
    }
506
 
 
507
 
    /**
508
 
     * Export this entry as a hash array with tag names as keys.
509
 
     *
510
 
     * @param boolean $paramsInKeys  If false, the operation can be quite
511
 
     *                               lossy as the parameters are ignored when
512
 
     *                               building the array keys.
513
 
     *                               So if you export a vcard with
514
 
     *                               LABEL;TYPE=WORK:foo
515
 
     *                               LABEL;TYPE=HOME:bar
516
 
     *                               the resulting hash contains only one
517
 
     *                               label field!
518
 
     *                               If set to true, array keys look like
519
 
     *                               'LABEL;TYPE=WORK'
520
 
     *
521
 
     * @return array  A hash array with tag names as keys.
522
 
     */
523
 
    public function toHash($paramsInKeys = false)
524
 
    {
525
 
        $hash = array();
526
 
 
527
 
        foreach ($this->_attributes as $a)  {
528
 
            $k = $a['name'];
529
 
            if ($paramsInKeys && is_array($a['params'])) {
530
 
                foreach ($a['params'] as $p => $v) {
531
 
                    $k .= ";$p=$v";
532
 
                }
533
 
            }
534
 
            $hash[$k] = $a['value'];
535
 
        }
536
 
 
537
 
        return $hash;
538
 
    }
539
 
 
540
 
    /**
541
 
     * Parses a string containing vCalendar data.
542
 
     *
543
 
     * @todo This method doesn't work well at all, if $base is VCARD.
544
 
     *
545
 
     * @param string $text     The data to parse.
546
 
     * @param string $base     The type of the base object.
547
 
     * @param boolean $clear   If true clears this object before parsing.
548
 
     *
549
 
     * @return boolean  True on successful import, false otherwise.
550
 
     * @throws Horde_Icalendar_Exception
551
 
     */
552
 
    public function parsevCalendar($text, $base = 'VCALENDAR', $clear = true)
553
 
    {
554
 
        if ($clear) {
555
 
            $this->clear();
556
 
        }
557
 
 
558
 
        $text = Horde_String::trimUtf8Bom($text);
559
 
 
560
 
        if (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
561
 
            $container = true;
562
 
            $vCal = $matches[1];
563
 
        } else {
564
 
            // Text isn't enclosed in BEGIN:VCALENDAR
565
 
            // .. END:VCALENDAR. We'll try to parse it anyway.
566
 
            $container = false;
567
 
            $vCal = $text;
568
 
        }
569
 
        $vCal = trim($vCal);
570
 
 
571
 
        // Extract all subcomponents.
572
 
        $matches = $components = null;
573
 
        if (preg_match_all('/^BEGIN:(.*)\s*?(\r\n|\r|\n)(.*)^END:\1\s*?/Uims', $vCal, $components)) {
574
 
            foreach ($components[0] as $key => $data) {
575
 
                // Remove from the vCalendar data.
576
 
                $vCal = str_replace($data, '', $vCal);
577
 
            }
578
 
        } elseif (!$container) {
579
 
            return false;
580
 
        }
581
 
 
582
 
        // Unfold "quoted printable" folded lines like:
583
 
        //  BODY;ENCODING=QUOTED-PRINTABLE:=
584
 
        //  another=20line=
585
 
        //  last=20line
586
 
        while (preg_match_all('/^([^:]+;\s*(ENCODING=)?QUOTED-PRINTABLE(.*=\r?\n)+(.*[^=])?(\r?\n|$))/mU', $vCal, $matches)) {
587
 
            foreach ($matches[1] as $s) {
588
 
                $r = preg_replace('/=\r?\n/', '', $s);
589
 
                $vCal = str_replace($s, $r, $vCal);
590
 
            }
591
 
        }
592
 
 
593
 
        // Unfold any folded lines.
594
 
        $vCal = preg_replace('/[\r\n]+[ \t]/', '', $vCal);
595
 
 
596
 
        // Parse the remaining attributes.
597
 
        if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches)) {
598
 
            foreach ($matches[0] as $attribute) {
599
 
                preg_match('/([^;^:]*)((;(?:[^":]+|(?:"[^"]*")+)*)?):([^\r\n]*)[\r\n]*/', $attribute, $parts);
600
 
                $tag = trim(preg_replace('/^.*\./', '', Horde_String::upper($parts[1])));
601
 
                $value = $parts[4];
602
 
                $params = array();
603
 
 
604
 
                // Parse parameters.
605
 
                if (!empty($parts[2])) {
606
 
                    preg_match_all('/;(([^;=]*)(=("[^"]*"|[^;]*))?)/', $parts[2], $param_parts);
607
 
                    foreach ($param_parts[2] as $key => $paramName) {
608
 
                        $paramName = Horde_String::upper($paramName);
609
 
                        $paramValue = $param_parts[4][$key];
610
 
                        if ($paramName == 'TYPE') {
611
 
                            $paramValue = preg_split('/(?<!\\\\),/', $paramValue);
612
 
                            if (count($paramValue) == 1) {
613
 
                                $paramValue = $paramValue[0];
614
 
                            }
615
 
                        }
616
 
                        if (is_string($paramValue)) {
617
 
                            if (preg_match('/"([^"]*)"/', $paramValue, $parts)) {
618
 
                                $paramValue = $parts[1];
619
 
                            }
620
 
                        } else {
621
 
                            foreach ($paramValue as $k => $tmp) {
622
 
                                if (preg_match('/"([^"]*)"/', $tmp, $parts)) {
623
 
                                    $paramValue[$k] = $parts[1];
624
 
                                }
625
 
                            }
626
 
                        }
627
 
                        if (isset($params[$paramName])) {
628
 
                            if (is_array($params[$paramName])) {
629
 
                                $params[$paramName][] = $paramValue;
630
 
                            } else {
631
 
                                $params[$paramName] = array($params[$paramName], $paramValue);
632
 
                            }
633
 
                        } else {
634
 
                            $params[$paramName] = $paramValue;
635
 
                        }
636
 
                    }
637
 
                }
638
 
 
639
 
                // Charset and encoding handling.
640
 
                if ((isset($params['ENCODING']) &&
641
 
                     Horde_String::upper($params['ENCODING']) == 'QUOTED-PRINTABLE') ||
642
 
                    isset($params['QUOTED-PRINTABLE'])) {
643
 
 
644
 
                    $value = quoted_printable_decode($value);
645
 
                    if (isset($params['CHARSET'])) {
646
 
                        $value = Horde_String::convertCharset($value, $params['CHARSET'], 'UTF-8');
647
 
                     }
648
 
                } elseif (isset($params['CHARSET'])) {
649
 
                    $value = Horde_String::convertCharset($value, $params['CHARSET'], 'UTF-8');
650
 
                }
651
 
 
652
 
                // Get timezone info for date fields from $params.
653
 
                $tzid = isset($params['TZID']) ? trim($params['TZID'], '\"') : false;
654
 
 
655
 
                switch ($tag) {
656
 
                // Date fields.
657
 
                case 'COMPLETED':
658
 
                case 'CREATED':
659
 
                case 'LAST-MODIFIED':
660
 
                case 'X-MOZ-LASTACK':
661
 
                case 'X-MOZ-SNOOZE-TIME':
662
 
                    $this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
663
 
                    break;
664
 
 
665
 
                case 'BDAY':
666
 
                case 'X-ANNIVERSARY':
667
 
                    $this->setAttribute($tag, $this->_parseDate($value), $params);
668
 
                    break;
669
 
 
670
 
                case 'DTEND':
671
 
                case 'DTSTART':
672
 
                case 'DTSTAMP':
673
 
                case 'DUE':
674
 
                case 'AALARM':
675
 
                case 'RECURRENCE-ID':
676
 
                    // types like AALARM may contain additional data after a ;
677
 
                    // ignore these.
678
 
                    $ts = explode(';', $value);
679
 
                    if (isset($params['VALUE']) && $params['VALUE'] == 'DATE') {
680
 
                        $this->setAttribute($tag, $this->_parseDate($ts[0]), $params);
681
 
                    } else {
682
 
                        $this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params);
683
 
                    }
684
 
                    break;
685
 
 
686
 
                case 'TRIGGER':
687
 
                    if (isset($params['VALUE']) &&
688
 
                        $params['VALUE'] == 'DATE-TIME') {
689
 
                            $this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
690
 
                    } else {
691
 
                        $this->setAttribute($tag, $this->_parseDuration($value), $params);
692
 
                    }
693
 
                    break;
694
 
 
695
 
                // Comma seperated dates.
696
 
                case 'EXDATE':
697
 
                case 'RDATE':
698
 
                    if (!strlen($value)) {
699
 
                        break;
700
 
                    }
701
 
                    $dates = array();
702
 
                    $separator = $this->_oldFormat ? ';' : ',';
703
 
                    preg_match_all('/' . $separator . '([^' . $separator . ']*)/', $separator . $value, $values);
704
 
 
705
 
                    foreach ($values[1] as $value) {
706
 
                        $stamp = $this->_parseDateTime($value);
707
 
                        if (!is_int($stamp)) {
708
 
                            continue;
709
 
                        }
710
 
                        $dates[] = array('year' => date('Y', $stamp),
711
 
                                         'month' => date('m', $stamp),
712
 
                                         'mday' => date('d', $stamp));
713
 
                    }
714
 
                    $this->setAttribute($tag, isset($dates[0]) ? $dates[0] : null, $params, true, $dates);
715
 
                    break;
716
 
 
717
 
                // Duration fields.
718
 
                case 'DURATION':
719
 
                    $this->setAttribute($tag, $this->_parseDuration($value), $params);
720
 
                    break;
721
 
 
722
 
                // Period of time fields.
723
 
                case 'FREEBUSY':
724
 
                    $periods = array();
725
 
                    preg_match_all('/,([^,]*)/', ',' . $value, $values);
726
 
                    foreach ($values[1] as $value) {
727
 
                        $periods[] = $this->_parsePeriod($value);
728
 
                    }
729
 
 
730
 
                    $this->setAttribute($tag, isset($periods[0]) ? $periods[0] : null, $params, true, $periods);
731
 
                    break;
732
 
 
733
 
                // UTC offset fields.
734
 
                case 'TZOFFSETFROM':
735
 
                case 'TZOFFSETTO':
736
 
                    $this->setAttribute($tag, $this->_parseUtcOffset($value), $params);
737
 
                    break;
738
 
 
739
 
                // Integer fields.
740
 
                case 'PERCENT-COMPLETE':
741
 
                case 'PRIORITY':
742
 
                case 'REPEAT':
743
 
                case 'SEQUENCE':
744
 
                    $this->setAttribute($tag, intval($value), $params);
745
 
                    break;
746
 
 
747
 
                // Geo fields.
748
 
                case 'GEO':
749
 
                    if ($value) {
750
 
                        if ($this->_oldFormat) {
751
 
                            $floats = explode(',', $value);
752
 
                            $value = array('latitude' => floatval($floats[1]),
753
 
                                           'longitude' => floatval($floats[0]));
754
 
                        } else {
755
 
                            $floats = explode(';', $value);
756
 
                            $value = array('latitude' => floatval($floats[0]),
757
 
                                           'longitude' => floatval($floats[1]));
758
 
                        }
759
 
                    }
760
 
                    $this->setAttribute($tag, $value, $params);
761
 
                    break;
762
 
 
763
 
                // Recursion fields.
764
 
                case 'EXRULE':
765
 
                case 'RRULE':
766
 
                    $this->setAttribute($tag, trim($value), $params);
767
 
                    break;
768
 
 
769
 
                // ADR, ORG and N are lists seperated by unescaped semicolons
770
 
                // with a specific number of slots.
771
 
                case 'ADR':
772
 
                case 'N':
773
 
                case 'ORG':
774
 
                    $value = trim($value);
775
 
                    // As of rfc 2426 2.4.2 semicolon, comma, and colon must
776
 
                    // be escaped (comma is unescaped after splitting below).
777
 
                    $value = str_replace(array('\\n', '\\N', '\\;', '\\:'),
778
 
                                         array($this->_newline, $this->_newline, ';', ':'),
779
 
                                         $value);
780
 
 
781
 
                    // Split by unescaped semicolons:
782
 
                    $values = preg_split('/(?<!\\\\);/', $value);
783
 
                    $value = str_replace('\\;', ';', $value);
784
 
                    $values = str_replace('\\;', ';', $values);
785
 
                    $this->setAttribute($tag, trim($value), $params, true, $values);
786
 
                    break;
787
 
 
788
 
                // String fields.
789
 
                default:
790
 
                    if ($this->_oldFormat) {
791
 
                        // vCalendar 1.0 and vCard 2.1 only escape semicolons
792
 
                        // and use unescaped semicolons to create lists.
793
 
                        $value = trim($value);
794
 
                        // Split by unescaped semicolons:
795
 
                        $values = preg_split('/(?<!\\\\);/', $value);
796
 
                        $value = str_replace('\\;', ';', $value);
797
 
                        $values = str_replace('\\;', ';', $values);
798
 
                        $this->setAttribute($tag, trim($value), $params, true, $values);
799
 
                    } else {
800
 
                        $value = trim($value);
801
 
                        // As of rfc 2426 2.4.2 semicolon, comma, and colon
802
 
                        // must be escaped (comma is unescaped after splitting
803
 
                        // below).
804
 
                        $value = str_replace(array('\\n', '\\N', '\\;', '\\:', '\\\\'),
805
 
                                             array($this->_newline, $this->_newline, ';', ':', '\\'),
806
 
                                             $value);
807
 
 
808
 
                        // Split by unescaped commas.
809
 
                        $values = preg_split('/(?<!\\\\),/', $value);
810
 
                        $value = str_replace('\\,', ',', $value);
811
 
                        $values = str_replace('\\,', ',', $values);
812
 
 
813
 
                        $this->setAttribute($tag, trim($value), $params, true, $values);
814
 
                    }
815
 
                    break;
816
 
                }
817
 
            }
818
 
        }
819
 
 
820
 
        // Process all components.
821
 
        if ($components) {
822
 
            // vTimezone components are processed first. They are
823
 
            // needed to process vEvents that may use a TZID.
824
 
            foreach ($components[0] as $key => $data) {
825
 
                $type = trim($components[1][$key]);
826
 
                if ($type != 'VTIMEZONE') {
827
 
                    continue;
828
 
                }
829
 
                $component = $this->newComponent($type, $this);
830
 
                if ($component === false) {
831
 
                    throw new Horde_Icalendar_Exception('Unable to create object for type ' . $type);
832
 
                }
833
 
                $component->parsevCalendar($data, $type);
834
 
 
835
 
                $this->addComponent($component);
836
 
 
837
 
                // Remove from the vCalendar data.
838
 
                $vCal = str_replace($data, '', $vCal);
839
 
            }
840
 
 
841
 
            // Now process the non-vTimezone components.
842
 
            foreach ($components[0] as $key => $data) {
843
 
                $type = trim($components[1][$key]);
844
 
                if ($type == 'VTIMEZONE') {
845
 
                    continue;
846
 
                }
847
 
                $component = $this->newComponent($type, $this);
848
 
                if ($component === false) {
849
 
                    throw new Horde_Icalendar_Exception('Unable to create object for type ' . $type);
850
 
                }
851
 
                $component->parsevCalendar($data, $type);
852
 
 
853
 
                $this->addComponent($component);
854
 
            }
855
 
        }
856
 
 
857
 
        return true;
858
 
    }
859
 
 
860
 
    /**
861
 
     * Export this component in vCal format.
862
 
     *
863
 
     * @param string $base  The type of the base object.
864
 
     *
865
 
     * @return string  vCal format data.
866
 
     */
867
 
    protected function _exportvData($base = 'VCALENDAR')
868
 
    {
869
 
        $result = 'BEGIN:' . Horde_String::upper($base) . $this->_newline;
870
 
 
871
 
        // VERSION is not allowed for entries enclosed in VCALENDAR/ICALENDAR,
872
 
        // as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
873
 
        if ($base !== 'VEVENT' && $base !== 'VTODO' && $base !== 'VALARM' &&
874
 
            $base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
875
 
            $base != 'VTIMEZONE' && $base != 'STANDARD' && $base != 'DAYLIGHT') {
876
 
            // Ensure that version is the first attribute.
877
 
            $result .= 'VERSION:' . $this->_version . $this->_newline;
878
 
        }
879
 
        foreach ($this->_attributes as $attribute) {
880
 
            $name = $attribute['name'];
881
 
            if ($name == 'VERSION') {
882
 
                // Already done.
883
 
                continue;
884
 
            }
885
 
 
886
 
            $params_str = '';
887
 
            $params = $attribute['params'];
888
 
            if ($params) {
889
 
                foreach ($params as $param_name => $param_value) {
890
 
                    /* Skip CHARSET for iCalendar 2.0 data, not allowed. */
891
 
                    if ($param_name == 'CHARSET' && !$this->_oldFormat) {
892
 
                        continue;
893
 
                    }
894
 
                    /* Skip VALUE=DATE for vCalendar 1.0 data, not allowed. */
895
 
                    if ($this->_oldFormat &&
896
 
                        $param_name == 'VALUE' && $param_value == 'DATE') {
897
 
                        continue;
898
 
                    }
899
 
 
900
 
                    if ($param_value === null) {
901
 
                        $params_str .= ";$param_name";
902
 
                    } else {
903
 
                        if (!is_array($param_value)) {
904
 
                            $param_value = array($param_value);
905
 
                        }
906
 
                        foreach ($param_value as &$one_param_value) {
907
 
                            $len = strlen($one_param_value);
908
 
                            $safe_value = '';
909
 
                            $quote = false;
910
 
                            for ($i = 0; $i < $len; ++$i) {
911
 
                                $ord = ord($one_param_value[$i]);
912
 
                                // Accept only valid characters.
913
 
                                if ($ord == 9 || $ord == 32 || $ord == 33 ||
914
 
                                    ($ord >= 35 && $ord <= 126) ||
915
 
                                    $ord >= 128) {
916
 
                                    $safe_value .= $one_param_value[$i];
917
 
                                    // Characters above 128 do not need to be
918
 
                                    // quoted as per RFC2445 but Outlook requires
919
 
                                    // this.
920
 
                                    if ($ord == 44 || $ord == 58 || $ord == 59 ||
921
 
                                        $ord >= 128) {
922
 
                                        $quote = true;
923
 
                                    }
924
 
                                }
925
 
                            }
926
 
                            if ($quote) {
927
 
                                $safe_value = '"' . $safe_value . '"';
928
 
                            }
929
 
                            $one_param_value = $safe_value;
930
 
                        }
931
 
                        $params_str .= ";$param_name=" . implode(',', $param_value);
932
 
                    }
933
 
                }
934
 
            }
935
 
 
936
 
            $value = $attribute['value'];
937
 
            switch ($name) {
938
 
            // Date fields.
939
 
            case 'COMPLETED':
940
 
            case 'CREATED':
941
 
            case 'DCREATED':
942
 
            case 'LAST-MODIFIED':
943
 
            case 'X-MOZ-LASTACK':
944
 
            case 'X-MOZ-SNOOZE-TIME':
945
 
                $value = $this->_exportDateTime($value);
946
 
                break;
947
 
 
948
 
            case 'DTEND':
949
 
            case 'DTSTART':
950
 
            case 'DTSTAMP':
951
 
            case 'DUE':
952
 
            case 'AALARM':
953
 
            case 'RECURRENCE-ID':
954
 
                $floating = $base == 'STANDARD'
955
 
                    || $base == 'DAYLIGHT'
956
 
                    || isset($params['TZID']);
957
 
                if (isset($params['VALUE'])) {
958
 
                    if ($params['VALUE'] == 'DATE') {
959
 
                        // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
960
 
                        if ($this->_oldFormat && $name == 'DTEND') {
961
 
                            $d = new Horde_Date($value);
962
 
                            $value = new Horde_Date(array(
963
 
                                'year' => $d->year,
964
 
                                'month' => $d->month,
965
 
                                'mday' => $d->mday - 1));
966
 
                            $value = $this->_exportDate($value, '235959');
967
 
                        } else {
968
 
                            $value = $this->_exportDate($value, '000000');
969
 
                        }
970
 
                    } else {
971
 
                        $value = $this->_exportDateTime($value, $floating);
972
 
                    }
973
 
                } else {
974
 
                    $value = $this->_exportDateTime($value, $floating);
975
 
                }
976
 
                break;
977
 
 
978
 
            // Comma seperated dates.
979
 
            case 'EXDATE':
980
 
            case 'RDATE':
981
 
                $floating = $base == 'STANDARD' || $base == 'DAYLIGHT';
982
 
                $dates = array();
983
 
                foreach ($value as $date) {
984
 
                    if (isset($params['VALUE'])) {
985
 
                        if ($params['VALUE'] == 'DATE') {
986
 
                            $dates[] = $this->_exportDate($date, '000000');
987
 
                        } elseif ($params['VALUE'] == 'PERIOD') {
988
 
                            $dates[] = $this->_exportPeriod($date);
989
 
                        } else {
990
 
                            $dates[] = $this->_exportDateTime($date, $floating);
991
 
                        }
992
 
                    } else {
993
 
                        $dates[] = $this->_exportDateTime($date, $floating);
994
 
                    }
995
 
                }
996
 
                $value = implode($this->_oldFormat ? ';' : ',', $dates);
997
 
                break;
998
 
 
999
 
            case 'TRIGGER':
1000
 
                if (isset($params['VALUE'])) {
1001
 
                    if ($params['VALUE'] == 'DATE-TIME') {
1002
 
                        $value = $this->_exportDateTime($value);
1003
 
                    } elseif ($params['VALUE'] == 'DURATION') {
1004
 
                        $value = $this->_exportDuration($value);
1005
 
                    }
1006
 
                } else {
1007
 
                    $value = $this->_exportDuration($value);
1008
 
                }
1009
 
                break;
1010
 
 
1011
 
            // Duration fields.
1012
 
            case 'DURATION':
1013
 
                $value = $this->_exportDuration($value);
1014
 
                break;
1015
 
 
1016
 
            // Period of time fields.
1017
 
            case 'FREEBUSY':
1018
 
                $value_str = '';
1019
 
                foreach ($value as $period) {
1020
 
                    $value_str .= empty($value_str) ? '' : ',';
1021
 
                    $value_str .= $this->_exportPeriod($period);
1022
 
                }
1023
 
                $value = $value_str;
1024
 
                break;
1025
 
 
1026
 
            // UTC offset fields.
1027
 
            case 'TZOFFSETFROM':
1028
 
            case 'TZOFFSETTO':
1029
 
                $value = $this->_exportUtcOffset($value);
1030
 
                break;
1031
 
 
1032
 
            // Integer fields.
1033
 
            case 'PERCENT-COMPLETE':
1034
 
            case 'PRIORITY':
1035
 
            case 'REPEAT':
1036
 
            case 'SEQUENCE':
1037
 
                $value = "$value";
1038
 
                break;
1039
 
 
1040
 
            // Geo fields.
1041
 
            case 'GEO':
1042
 
                if ($this->_oldFormat) {
1043
 
                    $value = $value['longitude'] . ',' . $value['latitude'];
1044
 
                } else {
1045
 
                    $value = $value['latitude'] . ';' . $value['longitude'];
1046
 
                }
1047
 
                break;
1048
 
 
1049
 
            // Recurrence fields.
1050
 
            case 'EXRULE':
1051
 
            case 'RRULE':
1052
 
                break;
1053
 
 
1054
 
            default:
1055
 
                if ($this->_oldFormat) {
1056
 
                    if (is_array($attribute['values']) &&
1057
 
                        count($attribute['values']) > 1) {
1058
 
                        $values = $attribute['values'];
1059
 
                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1060
 
                            $glue = ';';
1061
 
                        } else {
1062
 
                            $glue = ',';
1063
 
                        }
1064
 
                        $values = str_replace(';', '\\;', $values);
1065
 
                        $value = implode($glue, $values);
1066
 
                    } else {
1067
 
                        /* vcard 2.1 and vcalendar 1.0 escape only
1068
 
                         * semicolons */
1069
 
                        $value = str_replace(';', '\\;', $value);
1070
 
                    }
1071
 
                    // Text containing newlines or ASCII >= 127 must be BASE64
1072
 
                    // or QUOTED-PRINTABLE encoded. Currently we use
1073
 
                    // QUOTED-PRINTABLE as default.
1074
 
                    if (preg_match("/[^\x20-\x7F]/", $value) &&
1075
 
                        empty($params['ENCODING']))  {
1076
 
                        $params['ENCODING'] = 'QUOTED-PRINTABLE';
1077
 
                        $params_str .= ';ENCODING=QUOTED-PRINTABLE';
1078
 
                        // Add CHARSET as well. At least the synthesis client
1079
 
                        // gets confused otherwise
1080
 
                        if (empty($params['CHARSET'])) {
1081
 
                            $params['CHARSET'] = 'UTF-8';
1082
 
                            $params_str .= ';CHARSET=' . $params['CHARSET'];
1083
 
                        }
1084
 
                    }
1085
 
                } else {
1086
 
                    if (is_array($attribute['values']) &&
1087
 
                        count($attribute['values'])) {
1088
 
                        $values = $attribute['values'];
1089
 
                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1090
 
                            $glue = ';';
1091
 
                        } else {
1092
 
                            $glue = ',';
1093
 
                        }
1094
 
                        // As of rfc 2426 2.5 semicolon and comma must be
1095
 
                        // escaped.
1096
 
                        $values = str_replace(array('\\', ';', ','),
1097
 
                                              array('\\\\', '\\;', '\\,'),
1098
 
                                              $values);
1099
 
                        $value = implode($glue, $values);
1100
 
                    } else {
1101
 
                        // As of rfc 2426 2.5 semicolon and comma must be
1102
 
                        // escaped.
1103
 
                        $value = str_replace(array('\\', ';', ','),
1104
 
                                             array('\\\\', '\\;', '\\,'),
1105
 
                                             $value);
1106
 
                    }
1107
 
                    $value = preg_replace('/\r?\n/', '\n', $value);
1108
 
                }
1109
 
                break;
1110
 
            }
1111
 
 
1112
 
            $value = str_replace("\r", '', $value);
1113
 
            if (!empty($params['ENCODING']) &&
1114
 
                $params['ENCODING'] == 'QUOTED-PRINTABLE' &&
1115
 
                strlen(trim($value))) {
1116
 
                $result .= $name . $params_str . ':'
1117
 
                    . preg_replace(array('/(?<!\r)\n/', '/(?<!=)\r\n/'),
1118
 
                                   array("\r\n", "=0D=0A=\r\n "),
1119
 
                                   Horde_Mime::quotedPrintableEncode($value))
1120
 
                    . $this->_newline;
1121
 
            } else {
1122
 
                $attr_string = $name . $params_str . ':' . $value;
1123
 
                if (!$this->_oldFormat) {
1124
 
                    if (isset($params['ENCODING']) && $params['ENCODING'] == 'b') {
1125
 
                        $attr_string = trim(chunk_split($attr_string, 75, $this->_newline . ' '));
1126
 
                    } else {
1127
 
                        $attr_string = Horde_String::wordwrap($attr_string, 75, $this->_newline . ' ', true, true);
1128
 
                    }
1129
 
                }
1130
 
                $result .= $attr_string . $this->_newline;
1131
 
            }
1132
 
        }
1133
 
 
1134
 
        $tzs = array();
1135
 
        foreach ($this->_components as $component) {
1136
 
            if (!($component instanceof Horde_Icalendar_Vtimezone) ||
1137
 
                !isset($tzs[$component->getAttribute('TZID')])) {
1138
 
                $result .= $component->exportvCalendar();
1139
 
                if ($component instanceof Horde_Icalendar_Vtimezone) {
1140
 
                    $tzs[$component->getAttribute('TZID')] = true;
1141
 
                }
1142
 
            }
1143
 
        }
1144
 
 
1145
 
        return $result . 'END:' . $base . $this->_newline;
1146
 
    }
1147
 
 
1148
 
    /**
1149
 
     * Parse a UTC Offset field.
1150
 
     *
1151
 
     * @param $text TODO
1152
 
     *
1153
 
     * @return TODO
1154
 
     */
1155
 
    protected function _parseUtcOffset($text)
1156
 
    {
1157
 
        $offset = array();
1158
 
 
1159
 
        if (preg_match('/(\+|-)([0-9]{2})([0-9]{2})([0-9]{2})?/', $text, $timeParts)) {
1160
 
            $offset['ahead']  = (bool)($timeParts[1] == '+');
1161
 
            $offset['hour']   = intval($timeParts[2]);
1162
 
            $offset['minute'] = intval($timeParts[3]);
1163
 
            if (isset($timeParts[4])) {
1164
 
                $offset['second'] = intval($timeParts[4]);
1165
 
            }
1166
 
            return $offset;
1167
 
        }
1168
 
 
1169
 
        return false;
1170
 
    }
1171
 
 
1172
 
    /**
1173
 
     * Export a UTC Offset field.
1174
 
     *
1175
 
     * @param $value TODO
1176
 
     *
1177
 
     * @return TODO
1178
 
     */
1179
 
    function _exportUtcOffset($value)
1180
 
    {
1181
 
        $offset = ($value['ahead'] ? '+' : '-') .
1182
 
            sprintf('%02d%02d', $value['hour'], $value['minute']);
1183
 
 
1184
 
        if (isset($value['second'])) {
1185
 
            $offset .= sprintf('%02d', $value['second']);
1186
 
        }
1187
 
 
1188
 
        return $offset;
1189
 
    }
1190
 
 
1191
 
    /**
1192
 
     * Parse a Time Period field.
1193
 
     *
1194
 
     * @param $text TODO
1195
 
     *
1196
 
     * @return array  TODO
1197
 
     */
1198
 
    protected function _parsePeriod($text)
1199
 
    {
1200
 
        $periodParts = explode('/', $text);
1201
 
        $start = $this->_parseDateTime($periodParts[0]);
1202
 
 
1203
 
        if ($duration = $this->_parseDuration($periodParts[1])) {
1204
 
            return array('start' => $start, 'duration' => $duration);
1205
 
        } elseif ($end = $this->_parseDateTime($periodParts[1])) {
1206
 
            return array('start' => $start, 'end' => $end);
1207
 
        }
1208
 
    }
1209
 
 
1210
 
    /**
1211
 
     * Export a Time Period field.
1212
 
     *
1213
 
     * @param $value TODO
1214
 
     *
1215
 
     * @return TODO
1216
 
     */
1217
 
    protected function _exportPeriod($value)
1218
 
    {
1219
 
        $period = $this->_exportDateTime($value['start']) . '/';
1220
 
 
1221
 
        return isset($value['duration'])
1222
 
            ? $period . $this->_exportDuration($value['duration'])
1223
 
            : $period . $this->_exportDateTime($value['end']);
1224
 
    }
1225
 
 
1226
 
    /**
1227
 
     * Grok the TZID and return an offset in seconds from UTC for this
1228
 
     * date and time.
1229
 
     *
1230
 
     * @param $date TODO
1231
 
     * @param $time TODO
1232
 
     * @param $tzid TODO
1233
 
     *
1234
 
     * @return TODO
1235
 
     */
1236
 
    protected function _parseTZID($date, $time, $tzid)
1237
 
    {
1238
 
        $vtimezone = $this->_container->findComponentByAttribute('vtimezone', 'TZID', $tzid);
1239
 
        if (!$vtimezone) {
1240
 
            return false;
1241
 
        }
1242
 
 
1243
 
        $change_times = array();
1244
 
        foreach ($vtimezone->getComponents() as $o) {
1245
 
            $change_times = array_merge(
1246
 
                $change_times,
1247
 
                $vtimezone->parseChild($o, $date['year'])
1248
 
            );
1249
 
        }
1250
 
 
1251
 
        if (!$change_times) {
1252
 
            return false;
1253
 
        }
1254
 
 
1255
 
        sort($change_times);
1256
 
 
1257
 
        // Time is arbitrarily based on UTC for comparison.
1258
 
        $t = @gmmktime($time['hour'], $time['minute'], $time['second'],
1259
 
                       $date['month'], $date['mday'], $date['year']);
1260
 
 
1261
 
        if ($t < $change_times[0]['time']) {
1262
 
            return $change_times[0]['from'];
1263
 
        }
1264
 
 
1265
 
        for ($i = 0, $n = count($change_times); $i < $n - 1; $i++) {
1266
 
            if (($t >= $change_times[$i]['time']) &&
1267
 
                ($t < $change_times[$i + 1]['time'])) {
1268
 
                return $change_times[$i]['to'];
1269
 
            }
1270
 
        }
1271
 
 
1272
 
        if ($t >= $change_times[$n - 1]['time']) {
1273
 
            return $change_times[$n - 1]['to'];
1274
 
        }
1275
 
 
1276
 
        return false;
1277
 
    }
1278
 
 
1279
 
    /**
1280
 
     * Parses a DateTime field and returns a unix timestamp. If the
1281
 
     * field cannot be parsed then the original text is returned
1282
 
     * unmodified.
1283
 
     *
1284
 
     * @todo This function should be moved to Horde_Date and made public.
1285
 
     *
1286
 
     * @param $time TODO
1287
 
     * @param $tzid TODO
1288
 
     *
1289
 
     * @return TODO
1290
 
     */
1291
 
    public function _parseDateTime($text, $tzid = false)
1292
 
    {
1293
 
        $dateParts = explode('T', $text);
1294
 
        if (count($dateParts) != 2 && !empty($text)) {
1295
 
            // Not a datetime field but may be just a date field.
1296
 
            if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text)) {
1297
 
                // Or not
1298
 
                return $text;
1299
 
            }
1300
 
            $dateParts = array($text, '000000');
1301
 
        }
1302
 
 
1303
 
        if (!($date = $this->_parseDate($dateParts[0])) ||
1304
 
            !($time = $this->_parseTime($dateParts[1]))) {
1305
 
            return $text;
1306
 
        }
1307
 
 
1308
 
        // Get timezone info for date fields from $tzid and container.
1309
 
        $tzoffset = ($time['zone'] == 'Local' && $tzid &&
1310
 
                     ($this->_container instanceof Horde_Icalendar))
1311
 
                     ? $this->_parseTZID($date, $time, $tzid)
1312
 
                     : false;
1313
 
        if ($time['zone'] == 'UTC' || $tzoffset !== false) {
1314
 
            $result = @gmmktime($time['hour'], $time['minute'], $time['second'],
1315
 
                                $date['month'], $date['mday'], $date['year']);
1316
 
            if ($result !== false && $tzoffset) {
1317
 
                $result -= $tzoffset;
1318
 
            }
1319
 
        } else {
1320
 
            // We don't know the timezone so assume local timezone.
1321
 
            $result = @mktime($time['hour'], $time['minute'], $time['second'],
1322
 
                              $date['month'], $date['mday'], $date['year']);
1323
 
        }
1324
 
 
1325
 
        return ($result !== false) ? $result : $text;
1326
 
    }
1327
 
 
1328
 
    /**
1329
 
     * Export a DateTime field.
1330
 
     *
1331
 
     * @todo A bunch of code calls this function outside this class, so it
1332
 
     * needs to be marked public for now.
1333
 
     *
1334
 
     * @param integer|object|array $value  The time value to export (either a
1335
 
     *                                     Horde_Date, array, or timestamp).
1336
 
     * @param boolean $floating            Whether to return a floating
1337
 
     *                                     date-time (without time zone
1338
 
     *                                     information).
1339
 
     *
1340
 
     * @return string  The string representation of the datetime value.
1341
 
     */
1342
 
    public function _exportDateTime($value, $floating = false)
1343
 
    {
1344
 
        $date = new Horde_Date($value);
1345
 
        return $date->toICalendar($floating);
1346
 
    }
1347
 
 
1348
 
    /**
1349
 
     * Parses a Time field.
1350
 
     *
1351
 
     * @param $text  TODO
1352
 
     *
1353
 
     * @return TODO
1354
 
     */
1355
 
    protected function _parseTime($text)
1356
 
    {
1357
 
        if (!preg_match('/([0-9]{2})([0-9]{2})([0-9]{2})(Z)?/', $text, $timeParts)) {
1358
 
            return false;
1359
 
        }
1360
 
 
1361
 
        return array(
1362
 
            'hour' => $timeParts[1],
1363
 
            'minute' => $timeParts[2],
1364
 
            'second' => $timeParts[3],
1365
 
            'zone' => isset($timeParts[4]) ? 'UTC' : 'Local'
1366
 
        );
1367
 
    }
1368
 
 
1369
 
    /**
1370
 
     * Parses a Date field.
1371
 
     *
1372
 
     * @param $text TODO
1373
 
     *
1374
 
     * @return array TODO
1375
 
     */
1376
 
    public function _parseDate($text)
1377
 
    {
1378
 
        $parts = explode('T', $text);
1379
 
        if (count($parts) == 2) {
1380
 
            $text = $parts[0];
1381
 
        }
1382
 
 
1383
 
        if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1384
 
            return false;
1385
 
        }
1386
 
 
1387
 
        return array(
1388
 
            'year' => $match[1],
1389
 
            'month' => $match[2],
1390
 
            'mday' => $match[3]
1391
 
        );
1392
 
    }
1393
 
 
1394
 
    /**
1395
 
     * Exports a date field.
1396
 
     *
1397
 
     * @param object|array $value  Date object or hash.
1398
 
     * @param string $autoconvert  If set, use this as time part to export the
1399
 
     *                             date as datetime when exporting to Vcalendar
1400
 
     *                             1.0. Examples: '000000' or '235959'
1401
 
     *
1402
 
     * @return TODO
1403
 
     */
1404
 
    protected function _exportDate($value, $autoconvert = false)
1405
 
    {
1406
 
        if (is_object($value)) {
1407
 
            $value = array('year' => $value->year, 'month' => $value->month, 'mday' => $value->mday);
1408
 
        }
1409
 
 
1410
 
        return ($autoconvert !== false && $this->_oldFormat)
1411
 
            ? sprintf('%04d%02d%02dT%s', $value['year'], $value['month'], $value['mday'], $autoconvert)
1412
 
            : sprintf('%04d%02d%02d', $value['year'], $value['month'], $value['mday']);
1413
 
    }
1414
 
 
1415
 
    /**
1416
 
     * Parses a DURATION value field.
1417
 
     *
1418
 
     * @param string $text  A DURATION value.
1419
 
     *
1420
 
     * @return integer  The duration in seconds.
1421
 
     */
1422
 
    protected function _parseDuration($text)
1423
 
    {
1424
 
        if (!preg_match('/([+]?|[-])P(([0-9]+W)|([0-9]+D)|)(T(([0-9]+H)|([0-9]+M)|([0-9]+S))+)?/', trim($text), $durvalue)) {
1425
 
            return false;
1426
 
        }
1427
 
 
1428
 
        // Weeks.
1429
 
        $duration = 7 * 86400 * intval($durvalue[3]);
1430
 
 
1431
 
        if (count($durvalue) > 4) {
1432
 
            // Days.
1433
 
            $duration += 86400 * intval($durvalue[4]);
1434
 
        }
1435
 
 
1436
 
        if (count($durvalue) > 5) {
1437
 
            // Hours.
1438
 
            $duration += 3600 * intval($durvalue[7]);
1439
 
 
1440
 
            // Mins.
1441
 
            if (isset($durvalue[8])) {
1442
 
                $duration += 60 * intval($durvalue[8]);
1443
 
            }
1444
 
 
1445
 
            // Secs.
1446
 
            if (isset($durvalue[9])) {
1447
 
                $duration += intval($durvalue[9]);
1448
 
            }
1449
 
        }
1450
 
 
1451
 
        // Sign.
1452
 
        if ($durvalue[1] == "-") {
1453
 
            $duration *= -1;
1454
 
        }
1455
 
 
1456
 
        return $duration;
1457
 
    }
1458
 
 
1459
 
    /**
1460
 
     * Export a duration value.
1461
 
     *
1462
 
     * @param $value TODO
1463
 
     */
1464
 
    protected function _exportDuration($value)
1465
 
    {
1466
 
        $duration = '';
1467
 
        if ($value < 0) {
1468
 
            $value *= -1;
1469
 
            $duration .= '-';
1470
 
        }
1471
 
        $duration .= 'P';
1472
 
 
1473
 
        $weeks = floor($value / (7 * 86400));
1474
 
        $value = $value % (7 * 86400);
1475
 
        if ($weeks) {
1476
 
            $duration .= $weeks . 'W';
1477
 
        }
1478
 
 
1479
 
        $days = floor($value / (86400));
1480
 
        $value = $value % (86400);
1481
 
        if ($days) {
1482
 
            $duration .= $days . 'D';
1483
 
        }
1484
 
 
1485
 
        if ($value) {
1486
 
            $duration .= 'T';
1487
 
 
1488
 
            $hours = floor($value / 3600);
1489
 
            $value = $value % 3600;
1490
 
            if ($hours) {
1491
 
                $duration .= $hours . 'H';
1492
 
            }
1493
 
 
1494
 
            $mins = floor($value / 60);
1495
 
            $value = $value % 60;
1496
 
            if ($mins) {
1497
 
                $duration .= $mins . 'M';
1498
 
            }
1499
 
 
1500
 
            if ($value) {
1501
 
                $duration .= $value . 'S';
1502
 
            }
1503
 
        }
1504
 
 
1505
 
        return $duration;
1506
 
    }
1507
 
 
1508
 
}