Projet

Général

Profil

Paste
Télécharger (27,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date_api / date_api_ical.inc @ 599a39cd

1
<?php
2

    
3
/**
4
 * @file
5
 * Parse iCal data.
6
 *
7
 * This file must be included when these functions are needed.
8
 */
9

    
10
/**
11
 * Return an array of iCalendar information from an iCalendar file.
12
 *
13
 * No timezone adjustment is performed in the import since the timezone
14
 * conversion needed will vary depending on whether the value is being
15
 * imported into the database (when it needs to be converted to UTC), is being
16
 * viewed on a site that has user-configurable timezones (when it needs to be
17
 * converted to the user's timezone), if it needs to be converted to the site
18
 * timezone, or if it is a date without a timezone which should not have any
19
 * timezone conversion applied.
20
 *
21
 * Properties that have dates and times are converted to sub-arrays like:
22
 * 'datetime' => Date in YYYY-MM-DD HH:MM format, not timezone adjusted.
23
 * 'all_day'  => Whether this is an all-day event.
24
 * 'tz'       => The timezone of the date, could be blank for absolute times
25
 *               that should get no timezone conversion.
26
 *
27
 * Exception dates can have muliple values and are returned as arrayslike the
28
 * above for each exception date.
29
 *
30
 * Most other properties are returned as PROPERTY => VALUE.
31
 *
32
 * Each item in the VCALENDAR will return an array like:
33
 * [0] => Array (
34
 *   [TYPE] => VEVENT
35
 *   [UID] => 104
36
 *   [SUMMARY] => An example event
37
 *   [URL] => http://example.com/node/1
38
 *   [DTSTART] => Array (
39
 *     [datetime] => 1997-09-07 09:00:00
40
 *     [all_day] => 0
41
 *     [tz] => US/Eastern
42
 *   )
43
 *   [DTEND] => Array (
44
 *     [datetime] => 1997-09-07 11:00:00
45
 *     [all_day] => 0
46
 *     [tz] => US/Eastern
47
 *   )
48
 *   [RRULE] => Array (
49
 *     [FREQ] => Array (
50
 *       [0] => MONTHLY
51
 *     )
52
 *     [BYDAY] => Array (
53
 *       [0] => 1SU
54
 *       [1] => -1SU
55
 *     )
56
 *   )
57
 *   [EXDATE] => Array (
58
 *     [0] = Array (
59
 *       [datetime] => 1997-09-21 09:00:00
60
 *       [all_day] => 0
61
 *       [tz] => US/Eastern
62
 *     )
63
 *     [1] = Array (
64
 *       [datetime] => 1997-10-05 09:00:00
65
 *       [all_day] => 0
66
 *       [tz] => US/Eastern
67
 *     )
68
 *   )
69
 *   [RDATE] => Array (
70
 *     [0] = Array (
71
 *       [datetime] => 1997-09-21 09:00:00
72
 *       [all_day] => 0
73
 *       [tz] => US/Eastern
74
 *     )
75
 *     [1] = Array (
76
 *       [datetime] => 1997-10-05 09:00:00
77
 *       [all_day] => 0
78
 *       [tz] => US/Eastern
79
 *     )
80
 *   )
81
 * )
82
 *
83
 * @todo
84
 *   figure out how to handle this if subgroups are nested,
85
 *   like a VALARM nested inside a VEVENT.
86
 *
87
 * @param string $filename
88
 *   Location (local or remote) of a valid iCalendar file.
89
 *
90
 * @return array
91
 *   An array with all the elements from the ical.
92
 */
93
function date_ical_import($filename) {
94
  // Fetch the iCal data. If file is a URL, use drupal_http_request. fopen
95
  // isn't always configured to allow network connections.
96
  if (substr($filename, 0, 4) == 'http') {
97
    // Fetch the ical data from the specified network location.
98
    $icaldatafetch = drupal_http_request($filename);
99
    // Check the return result.
100
    if ($icaldatafetch->error) {
101
      watchdog('date ical', 'HTTP Request Error importing %filename: @error', array('%filename' => $filename, '@error' => $icaldatafetch->error));
102
      return FALSE;
103
    }
104
    // Break the return result into one array entry per lines.
105
    $icaldatafolded = explode("\n", $icaldatafetch->data);
106
  }
107
  else {
108
    $icaldatafolded = @file($filename, FILE_IGNORE_NEW_LINES);
109
    if ($icaldatafolded === FALSE) {
110
      watchdog('date ical', 'Failed to open file: %filename', array('%filename' => $filename));
111
      return FALSE;
112
    }
113
  }
114
  // Verify this is iCal data.
115
  if (trim($icaldatafolded[0]) != 'BEGIN:VCALENDAR') {
116
    watchdog('date ical', 'Invalid calendar file: %filename', array('%filename' => $filename));
117
    return FALSE;
118
  }
119
  return date_ical_parse($icaldatafolded);
120
}
121

    
122
/**
123
 * Returns an array of iCalendar information from an iCalendar file.
124
 *
125
 * As date_ical_import() but different param.
126
 *
127
 * @param array $icaldatafolded
128
 *   An array of lines from an ical feed.
129
 *
130
 * @return array
131
 *   An array with all the elements from the ical.
132
 */
133
function date_ical_parse(array $icaldatafolded = array()) {
134
  $items = array();
135

    
136
  // Verify this is iCal data.
137
  if (trim($icaldatafolded[0]) != 'BEGIN:VCALENDAR') {
138
    watchdog('date ical', 'Invalid calendar file.');
139
    return FALSE;
140
  }
141

    
142
  // "Unfold" wrapped lines.
143
  $icaldata = array();
144
  foreach ($icaldatafolded as $line) {
145
    $out = array();
146
    // See if this looks like the beginning of a new property or value. If not,
147
    // it is a continuation of the previous line. The regex is to ensure that
148
    // wrapped QUOTED-PRINTABLE data is kept intact.
149
    if (!preg_match('/([A-Z]+)[:;](.*)/', $line, $out)) {
150
      // Trim up to 1 leading space from wrapped line per iCalendar standard.
151
      $line = array_pop($icaldata) . (ltrim(substr($line, 0, 1)) . substr($line, 1));
152
    }
153
    $icaldata[] = $line;
154
  }
155
  unset($icaldatafolded);
156

    
157
  // Parse the iCal information.
158
  $parents = array();
159
  $subgroups = array();
160
  $vcal = '';
161
  foreach ($icaldata as $line) {
162
    $line = trim($line);
163
    $vcal .= $line . "\n";
164
    // Deal with begin/end tags separately.
165
    if (preg_match('/(BEGIN|END):V(\S+)/', $line, $matches)) {
166
      $closure = $matches[1];
167
      $type = 'V' . $matches[2];
168
      if ($closure == 'BEGIN') {
169
        array_push($parents, $type);
170
        array_push($subgroups, array());
171
      }
172
      elseif ($closure == 'END') {
173
        end($subgroups);
174
        $subgroup = &$subgroups[key($subgroups)];
175
        switch ($type) {
176
          case 'VCALENDAR':
177
            if (prev($subgroups) == FALSE) {
178
              $items[] = array_pop($subgroups);
179
            }
180
            else {
181
              $parent[array_pop($parents)][] = array_pop($subgroups);
182
            }
183
            break;
184

    
185
          // Add the timezones in with their index their TZID.
186
          case 'VTIMEZONE':
187
            $subgroup = end($subgroups);
188
            $id = $subgroup['TZID'];
189
            unset($subgroup['TZID']);
190

    
191
            // Append this subgroup onto the one above it.
192
            prev($subgroups);
193
            $parent = &$subgroups[key($subgroups)];
194

    
195
            $parent[$type][$id] = $subgroup;
196

    
197
            array_pop($subgroups);
198
            array_pop($parents);
199
            break;
200

    
201
          // Do some fun stuff with durations and all_day events and then append
202
          // to parent.
203
          case 'VEVENT':
204
          case 'VALARM':
205
          case 'VTODO':
206
          case 'VJOURNAL':
207
          case 'VVENUE':
208
          case 'VFREEBUSY':
209
          default:
210
            // Can't be sure whether DTSTART is before or after DURATION, so
211
            // parse DURATION at the end.
212
            if (isset($subgroup['DURATION'])) {
213
              date_ical_parse_duration($subgroup, 'DURATION');
214
            }
215
            // Add a top-level indication for the 'All day' condition. Leave it
216
            // in the individual date components, too, so it is always available
217
            // even when you are working with only a portion of the VEVENT
218
            // array, like in Feed API parsers.
219
            $subgroup['all_day'] = FALSE;
220

    
221
            // iCal spec states 'The "DTEND" property for a "VEVENT" calendar
222
            // component specifies the non-inclusive end of the event'. Adjust
223
            // multi-day events to remove the extra day because the Date code
224
            // assumes the end date is inclusive.
225
            if (!empty($subgroup['DTEND']) && (!empty($subgroup['DTEND']['all_day']))) {
226
              // Make the end date one day earlier.
227
              $date = new DateObject($subgroup['DTEND']['datetime'] . ' 00:00:00', $subgroup['DTEND']['tz']);
228
              date_modify($date, '-1 day');
229
              $subgroup['DTEND']['datetime'] = date_format($date, 'Y-m-d');
230
            }
231
            // If a start datetime is defined AND there is no definition for
232
            // the end datetime THEN make the end datetime equal the start
233
            // datetime and if it is an all day event define the entire event
234
            // as a single all day event.
235
            if (!empty($subgroup['DTSTART']) &&
236
               (empty($subgroup['DTEND']) && empty($subgroup['RRULE']) && empty($subgroup['RRULE']['COUNT']))) {
237
              $subgroup['DTEND'] = $subgroup['DTSTART'];
238
            }
239
            // Add this element to the parent as an array under the component
240
            // name.
241
            if (!empty($subgroup['DTSTART']['all_day'])) {
242
              $subgroup['all_day'] = TRUE;
243
            }
244
            // Add this element to the parent as an array under the.
245
            prev($subgroups);
246
            $parent = &$subgroups[key($subgroups)];
247

    
248
            $parent[$type][] = $subgroup;
249

    
250
            array_pop($subgroups);
251
            array_pop($parents);
252
        }
253
      }
254
    }
255
    // Handle all other possibilities.
256
    else {
257
      // Grab current subgroup.
258
      end($subgroups);
259
      $subgroup = &$subgroups[key($subgroups)];
260

    
261
      // Split up the line into nice pieces for PROPERTYNAME,
262
      // PROPERTYATTRIBUTES, and PROPERTYVALUE.
263
      preg_match('/([^;:]+)(?:;([^:]*))?:(.+)/', $line, $matches);
264
      $name = !empty($matches[1]) ? strtoupper(trim($matches[1])) : '';
265
      $field = !empty($matches[2]) ? $matches[2] : '';
266
      $data = !empty($matches[3]) ? $matches[3] : '';
267
      $parse_result = '';
268

    
269
      switch ($name) {
270
        // Keep blank lines out of the results.
271
        case '':
272
          break;
273

    
274
        // Lots of properties have date values that must be parsed out.
275
        case 'CREATED':
276
        case 'LAST-MODIFIED':
277
        case 'DTSTART':
278
        case 'DTEND':
279
        case 'DTSTAMP':
280
        case 'FREEBUSY':
281
        case 'DUE':
282
        case 'COMPLETED':
283
          $parse_result = date_ical_parse_date($field, $data);
284
          break;
285

    
286
        case 'EXDATE':
287
        case 'RDATE':
288
          $parse_result = date_ical_parse_exceptions($field, $data);
289
          break;
290

    
291
        case 'TRIGGER':
292
          // A TRIGGER can either be a date or in the form -PT1H.
293
          if (!empty($field)) {
294
            $parse_result = date_ical_parse_date($field, $data);
295
          }
296
          else {
297
            $parse_result = array('DATA' => $data);
298
          }
299
          break;
300

    
301
        case 'DURATION':
302
          // Can't be sure whether DTSTART is before or after DURATION in
303
          // the VEVENT, so store the data and parse it at the end.
304
          $parse_result = array('DATA' => $data);
305
          break;
306

    
307
        case 'RRULE':
308
        case 'EXRULE':
309
          $parse_result = date_ical_parse_rrule($field, $data);
310
          break;
311

    
312
        case 'STATUS':
313
        case 'SUMMARY':
314
        case 'DESCRIPTION':
315
          $parse_result = date_ical_parse_text($field, $data);
316
          break;
317

    
318
        case 'LOCATION':
319
          $parse_result = date_ical_parse_location($field, $data);
320
          break;
321

    
322
        // For all other properties, just store the property and the value.
323
        // This can be expanded on in the future if other properties should
324
        // be given special treatment.
325
        default:
326
          $parse_result = $data;
327
      }
328

    
329
      // Store the result of our parsing.
330
      $subgroup[$name] = $parse_result;
331
    }
332
  }
333
  return $items;
334
}
335

    
336
/**
337
 * Parses a ical date element.
338
 *
339
 * Possible formats to parse include:
340
 * - PROPERTY:YYYYMMDD[T][HH][MM][SS][Z]
341
 * - PROPERTY;VALUE=DATE:YYYYMMDD[T][HH][MM][SS][Z]
342
 * - PROPERTY;VALUE=DATE-TIME:YYYYMMDD[T][HH][MM][SS][Z]
343
 * - PROPERTY;TZID=XXXXXXXX;VALUE=DATE:YYYYMMDD[T][HH][MM][SS]
344
 * - PROPERTY;TZID=XXXXXXXX:YYYYMMDD[T][HH][MM][SS]
345
 *
346
 * The property and the colon before the date are removed in the import
347
 * process above and we are left with $field and $data.
348
 *
349
 * @param string $field
350
 *   The text before the colon and the date, i.e.
351
 *   ';VALUE=DATE:', ';VALUE=DATE-TIME:', ';TZID='
352
 * @param string $data
353
 *   The date itself, after the colon, in the format YYYYMMDD[T][HH][MM][SS][Z]
354
 *   'Z', if supplied, means the date is in UTC.
355
 *
356
 * @return array
357
 *   Consisting of:
358
 *   'datetime' => Date in YYYY-MM-DD HH:MM format, not timezone adjusted.
359
 *   'all_day'  => Whether this is an all-day event with no time.
360
 *   'tz'       => The timezone of the date, could be blank if the iCal has no
361
 *                 timezone; the ical specs say no timezone conversion should be
362
 *                 done if no timezone info is supplied.
363
 *
364
 * @todo Another option for dates is the format PROPERTY;VALUE=PERIOD:XXXX. The
365
 *   period may include a duration, or a date and a duration, or two dates, so
366
 *   would have to be split into parts and run through date_ical_parse_date()
367
 *   and date_ical_parse_duration(). This is not commonly used, so ignored for
368
 *   now. It will take more work to figure how to support that.
369
 */
370
function date_ical_parse_date($field, $data) {
371
  $items = array('datetime' => '', 'all_day' => '', 'tz' => '');
372
  if (empty($data)) {
373
    return $items;
374
  }
375
  // Make this a little more whitespace independent.
376
  $data = trim($data);
377

    
378
  // Turn the properties into a nice indexed array of
379
  // array(PROPERTYNAME => PROPERTYVALUE);
380
  $field_parts = preg_split('/[;:]/', $field);
381
  $properties = array();
382
  foreach ($field_parts as $part) {
383
    if (strpos($part, '=') !== FALSE) {
384
      $tmp = explode('=', $part);
385
      $properties[$tmp[0]] = $tmp[1];
386
    }
387
  }
388

    
389
  // Make this a little more whitespace independent.
390
  $data = trim($data);
391

    
392
  // Record if a time has been found.
393
  $has_time = FALSE;
394

    
395
  // If a format is specified, parse it according to that format.
396
  if (isset($properties['VALUE'])) {
397
    switch ($properties['VALUE']) {
398
      case 'DATE':
399
        preg_match(DATE_REGEX_ICAL_DATE, $data, $regs);
400
        // Date.
401
        $datetime = date_pad($regs[1]) . '-' . date_pad($regs[2]) . '-' . date_pad($regs[3]);
402
        break;
403

    
404
      case 'DATE-TIME':
405
        preg_match(DATE_REGEX_ICAL_DATETIME, $data, $regs);
406
        // Date.
407
        $datetime = date_pad($regs[1]) . '-' . date_pad($regs[2]) . '-' . date_pad($regs[3]);
408
        // Time.
409
        $datetime .= ' ' . date_pad($regs[4]) . ':' . date_pad($regs[5]) . ':' . date_pad($regs[6]);
410
        $has_time = TRUE;
411
        break;
412
    }
413
  }
414

    
415
  // If no format is specified, attempt a loose match.
416
  else {
417
    preg_match(DATE_REGEX_LOOSE, $data, $regs);
418
    if (!empty($regs) && count($regs) > 2) {
419
      // Date.
420
      $datetime = date_pad($regs[1]) . '-' . date_pad($regs[2]) . '-' . date_pad($regs[3]);
421
      if (isset($regs[4])) {
422
        $has_time = TRUE;
423
        // Time.
424
        $datetime .= ' ' . (!empty($regs[5]) ? date_pad($regs[5]) : '00') .
425
         ':' . (!empty($regs[6]) ? date_pad($regs[6]) : '00') .
426
         ':' . (!empty($regs[7]) ? date_pad($regs[7]) : '00');
427
      }
428
    }
429
  }
430

    
431
  // Use timezone if explicitly declared.
432
  if (isset($properties['TZID'])) {
433
    $tz = $properties['TZID'];
434
    // Fix alternatives like US-Eastern which should be US/Eastern.
435
    $tz = str_replace('-', '/', $tz);
436
    // Unset invalid timezone names.
437
    module_load_include('inc', 'date_api', 'date_api.admin');
438
    $tz = _date_timezone_replacement($tz);
439
    if (!date_timezone_is_valid($tz)) {
440
      $tz = '';
441
    }
442
  }
443
  // If declared as UTC with terminating 'Z', use that timezone.
444
  elseif (strpos($data, 'Z') !== FALSE) {
445
    $tz = 'UTC';
446
  }
447
  // Otherwise this date is floating.
448
  else {
449
    $tz = '';
450
  }
451

    
452
  $items['datetime'] = $datetime;
453
  $items['all_day'] = $has_time ? FALSE : TRUE;
454
  $items['tz'] = $tz;
455
  return $items;
456
}
457

    
458
/**
459
 * Parse an ical repeat rule.
460
 *
461
 * @return array
462
 *   A nested array in the form of 'PROPERTY' => array(VALUES) where
463
 *   'PROPERTIES' includes 'FREQ', 'INTERVAL', 'COUNT', 'BYDAY', 'BYMONTH',
464
 *   'BYYEAR', 'UNTIL'.
465
 */
466
function date_ical_parse_rrule($field, $data) {
467
  $data = preg_replace("/RRULE.*:/", '', $data);
468
  $items = array('DATA' => $data);
469
  $rrule = explode(';', $data);
470
  foreach ($rrule as $key => $value) {
471
    $param = explode('=', $value);
472
    // Must be some kind of invalid data.
473
    if (count($param) != 2) {
474
      continue;
475
    }
476
    if ($param[0] == 'UNTIL') {
477
      $values = date_ical_parse_date('', $param[1]);
478
    }
479
    else {
480
      $values = explode(',', $param[1]);
481
    }
482
    // Treat items differently if they have multiple or single values.
483
    if (in_array($param[0], array('FREQ', 'INTERVAL', 'COUNT', 'WKST'))) {
484
      $items[$param[0]] = $param[1];
485
    }
486
    else {
487
      $items[$param[0]] = $values;
488
    }
489
  }
490
  return $items;
491
}
492

    
493
/**
494
 * Parse exception dates (can be multiple values).
495
 *
496
 * @return array
497
 *   An array of date value arrays.
498
 */
499
function date_ical_parse_exceptions($field, $data) {
500
  $data = str_replace($field . ':', '', $data);
501
  $items = array('DATA' => $data);
502
  $ex_dates = explode(',', $data);
503
  foreach ($ex_dates as $ex_date) {
504
    $items[] = date_ical_parse_date('', $ex_date);
505
  }
506
  return $items;
507
}
508

    
509
/**
510
 * Parses the duration of the event.
511
 *
512
 * Example:
513
 * DURATION:PT1H30M
514
 * DURATION:P1Y2M.
515
 *
516
 * @param array $subgroup
517
 *   Array of other values in the vevent so we can check for DTSTART.
518
 * @param string $value_name
519
 *   The name of the value to process; defaults to 'DURATION'.
520
 */
521
function date_ical_parse_duration(array &$subgroup, $value_name = 'DURATION') {
522
  $items = $subgroup[$value_name];
523
  $data = $items['DATA'];
524
  preg_match('/^P(\d{1,4}[Y])?(\d{1,2}[M])?(\d{1,2}[W])?(\d{1,2}[D])?([T]{0,1})?(\d{1,2}[H])?(\d{1,2}[M])?(\d{1,2}[S])?/', $data, $duration);
525
  $items['year'] = isset($duration[1]) ? str_replace('Y', '', $duration[1]) : '';
526
  $items['month'] = isset($duration[2]) ? str_replace('M', '', $duration[2]) : '';
527
  $items['week'] = isset($duration[3]) ? str_replace('W', '', $duration[3]) : '';
528
  $items['day'] = isset($duration[4]) ? str_replace('D', '', $duration[4]) : '';
529
  $items['hour'] = isset($duration[6]) ? str_replace('H', '', $duration[6]) : '';
530
  $items['minute'] = isset($duration[7]) ? str_replace('M', '', $duration[7]) : '';
531
  $items['second'] = isset($duration[8]) ? str_replace('S', '', $duration[8]) : '';
532
  $start_date = array_key_exists('DTSTART', $subgroup) ? $subgroup['DTSTART']['datetime'] : date_format(date_now(), DATE_FORMAT_ISO);
533
  $timezone = array_key_exists('DTSTART', $subgroup) ? $subgroup['DTSTART']['tz'] : variable_get('date_default_timezone');
534
  if (empty($timezone)) {
535
    $timezone = 'UTC';
536
  }
537
  $date = new DateObject($start_date, $timezone);
538
  $date2 = clone $date;
539
  foreach ($items as $item => $count) {
540
    if ($count > 0) {
541
      date_modify($date2, '+' . $count . ' ' . $item);
542
    }
543
  }
544
  $format = isset($subgroup['DTSTART']['type']) && $subgroup['DTSTART']['type'] == 'DATE' ? 'Y-m-d' : 'Y-m-d H:i:s';
545
  $subgroup['DTEND'] = array(
546
    'datetime' => date_format($date2, DATE_FORMAT_DATETIME),
547
    'all_day' => isset($subgroup['DTSTART']['all_day']) ? $subgroup['DTSTART']['all_day'] : 0,
548
    'tz' => $timezone,
549
  );
550
  $duration = date_format($date2, 'U') - date_format($date, 'U');
551
  $subgroup['DURATION'] = array('DATA' => $data, 'DURATION' => $duration);
552
}
553

    
554
/**
555
 * Parse and clean up ical text elements.
556
 */
557
function date_ical_parse_text($field, $data) {
558
  if (strstr($field, 'QUOTED-PRINTABLE')) {
559
    $data = quoted_printable_decode($data);
560
  }
561
  // Strip line breaks within element.
562
  $data = str_replace(array("\r\n ", "\n ", "\r "), '', $data);
563
  // Put in line breaks where encoded.
564
  $data = str_replace(array("\\n", "\\N"), "\n", $data);
565
  // Remove other escaping.
566
  $data = stripslashes($data);
567
  return $data;
568
}
569

    
570
/**
571
 * Parse location elements.
572
 *
573
 * Catch situations like the upcoming.org feed that uses
574
 * LOCATION;VENUE-UID="http://upcoming.yahoo.com/venue/104/":111 First Street...
575
 * or more normal LOCATION;UID=123:111 First Street...
576
 * Upcoming feed would have been improperly broken on the ':' in http:// so we
577
 * paste the $field and $data back together first.
578
 *
579
 * Use non-greedy check for ':' in case there are more of them in the address.
580
 */
581
function date_ical_parse_location($field, $data) {
582
  if (preg_match('/UID=[?"](.+)[?"][*?:](.+)/', $field . ':' . $data, $matches)) {
583
    $location = array();
584
    $location['UID'] = $matches[1];
585
    $location['DESCRIPTION'] = stripslashes($matches[2]);
586
    return $location;
587
  }
588
  else {
589
    // Remove other escaping.
590
    $location = stripslashes($data);
591
    return $location;
592
  }
593
}
594

    
595
/**
596
 * Return a date object for the ical date, adjusted to its local timezone.
597
 *
598
 * @param array $ical_date
599
 *   An array of ical date information created in the ical import.
600
 * @param string $to_tz
601
 *   The timezone to convert the date's value to.
602
 *
603
 * @return object
604
 *   A timezone-adjusted date object.
605
 */
606
function date_ical_date(array $ical_date, $to_tz = FALSE) {
607
  // If the ical date has no timezone, must assume it is stateless
608
  // so treat it as a local date.
609
  if (empty($ical_date['datetime'])) {
610
    return NULL;
611
  }
612
  elseif (empty($ical_date['tz'])) {
613
    $from_tz = date_default_timezone();
614
  }
615
  else {
616
    $from_tz = $ical_date['tz'];
617
  }
618
  if (strlen($ical_date['datetime']) < 11) {
619
    $ical_date['datetime'] .= ' 00:00:00';
620
  }
621
  $date = new DateObject($ical_date['datetime'], new DateTimeZone($from_tz));
622

    
623
  if ($to_tz && !empty($ical_date['tz']) && $to_tz != $ical_date['tz']) {
624
    date_timezone_set($date, timezone_open($to_tz));
625
  }
626
  return $date;
627
}
628

    
629
/**
630
 * Escape #text elements for safe iCal use.
631
 *
632
 * @param string $text
633
 *   Text to escape.
634
 *
635
 * @return string
636
 *   Escaped text
637
 */
638
function date_ical_escape_text($text) {
639
  $text = drupal_html_to_text($text);
640
  $text = trim($text);
641
  // @todo Per #38130 the iCal specs don't want : and " escaped but there was
642
  // some reason for adding this in. Need to watch this and see if anything
643
  // breaks.
644
  // $text = str_replace('"', '\"', $text);
645
  // $text = str_replace(":", "\:", $text);
646
  $text = preg_replace("/\\\b/", "\\\\", $text);
647
  $text = str_replace(",", "\,", $text);
648
  $text = str_replace(";", "\;", $text);
649
  $text = str_replace("\n", "\\n ", $text);
650
  return trim($text);
651
}
652

    
653
/**
654
 * Build an iCal RULE from $form_values.
655
 *
656
 * @param array $form_values
657
 *   An array constructed like the one created by date_ical_parse_rrule().
658
 *     [RRULE] => Array (
659
 *       [FREQ] => Array (
660
 *         [0] => MONTHLY
661
 *       )
662
 *       [BYDAY] => Array (
663
 *         [0] => 1SU
664
 *         [1] => -1SU
665
 *       )
666
 *       [UNTIL] => Array (
667
 *         [datetime] => 1997-21-31 09:00:00
668
 *         [all_day] => 0
669
 *         [tz] => US/Eastern
670
 *       )
671
 *     )
672
 *     [EXDATE] => Array (
673
 *       [0] = Array (
674
 *         [datetime] => 1997-09-21 09:00:00
675
 *         [all_day] => 0
676
 *         [tz] => US/Eastern
677
 *       )
678
 *       [1] = Array (
679
 *         [datetime] => 1997-10-05 09:00:00
680
 *         [all_day] => 0
681
 *         [tz] => US/Eastern
682
 *       )
683
 *     )
684
 *     [RDATE] => Array (
685
 *       [0] = Array (
686
 *         [datetime] => 1997-09-21 09:00:00
687
 *         [all_day] => 0
688
 *         [tz] => US/Eastern
689
 *       )
690
 *       [1] = Array (
691
 *         [datetime] => 1997-10-05 09:00:00
692
 *         [all_day] => 0
693
 *         [tz] => US/Eastern
694
 *       )
695
 *     )
696
 */
697
function date_api_ical_build_rrule(array $form_values) {
698
  $rrule = '';
699
  if (empty($form_values) || !is_array($form_values)) {
700
    return $rrule;
701
  }
702

    
703
  // Grab the RRULE data and put them into iCal RRULE format.
704
  $rrule .= 'RRULE:FREQ=' . (!array_key_exists('FREQ', $form_values) ? 'DAILY' : $form_values['FREQ']);
705
  $rrule .= ';INTERVAL=' . (!array_key_exists('INTERVAL', $form_values) ? 1 : $form_values['INTERVAL']);
706

    
707
  // Unset the empty 'All' values.
708
  if (array_key_exists('BYDAY', $form_values) && is_array($form_values['BYDAY'])) {
709
    unset($form_values['BYDAY']['']);
710
  }
711
  if (array_key_exists('BYMONTH', $form_values) && is_array($form_values['BYMONTH'])) {
712
    unset($form_values['BYMONTH']['']);
713
  }
714
  if (array_key_exists('BYMONTHDAY', $form_values) && is_array($form_values['BYMONTHDAY'])) {
715
    unset($form_values['BYMONTHDAY']['']);
716
  }
717

    
718
  if (array_key_exists('BYDAY', $form_values) && is_array($form_values['BYDAY']) && $byday = implode(",", $form_values['BYDAY'])) {
719
    $rrule .= ';BYDAY=' . $byday;
720
  }
721
  if (array_key_exists('BYMONTH', $form_values) && is_array($form_values['BYMONTH']) && $bymonth = implode(",", $form_values['BYMONTH'])) {
722
    $rrule .= ';BYMONTH=' . $bymonth;
723
  }
724
  if (array_key_exists('BYMONTHDAY', $form_values) && is_array($form_values['BYMONTHDAY']) && $bymonthday = implode(",", $form_values['BYMONTHDAY'])) {
725
    $rrule .= ';BYMONTHDAY=' . $bymonthday;
726
  }
727
  // The UNTIL date is supposed to always be expressed in UTC. The input date
728
  // values may already have been converted to a date object on a previous
729
  // pass, so check for that.
730
  if (array_key_exists('UNTIL', $form_values) && array_key_exists('datetime', $form_values['UNTIL']) && !empty($form_values['UNTIL']['datetime'])) {
731
    // We only collect a date for UNTIL, but we need it to be inclusive, so
732
    // force it to a full datetime element at the last second of the day.
733
    if (!is_object($form_values['UNTIL']['datetime'])) {
734
      // If this is a date without time, give it time.
735
      if (strlen($form_values['UNTIL']['datetime']) < 11) {
736
        $granularity_options = drupal_map_assoc(array(
737
          'year',
738
          'month',
739
          'day',
740
          'hour',
741
          'minute',
742
          'second',
743
        ));
744

    
745
        $form_values['UNTIL']['datetime'] .= ' 23:59:59';
746
        $form_values['UNTIL']['granularity'] = serialize($granularity_options);
747
        $form_values['UNTIL']['all_day'] = FALSE;
748
      }
749
      $until = date_ical_date($form_values['UNTIL'], 'UTC');
750
    }
751
    else {
752
      $until = $form_values['UNTIL']['datetime'];
753
    }
754
    $rrule .= ';UNTIL=' . date_format($until, DATE_FORMAT_ICAL) . 'Z';
755
  }
756
  // Our form doesn't allow a value for COUNT, but it may be needed by modules
757
  // using the API, so add it to the rule.
758
  if (array_key_exists('COUNT', $form_values)) {
759
    $rrule .= ';COUNT=' . $form_values['COUNT'];
760
  }
761

    
762
  // iCal rules presume the week starts on Monday unless otherwise specified,
763
  // so we'll specify it.
764
  if (array_key_exists('WKST', $form_values)) {
765
    $rrule .= ';WKST=' . $form_values['WKST'];
766
  }
767
  else {
768
    $rrule .= ';WKST=' . date_repeat_dow2day(variable_get('date_first_day', 0));
769
  }
770

    
771
  // Exceptions dates go last, on their own line. The input date values may
772
  // already have been converted to a date object on a previous pass, so check
773
  // for that.
774
  if (isset($form_values['EXDATE']) && is_array($form_values['EXDATE'])) {
775
    $ex_dates = array();
776
    foreach ($form_values['EXDATE'] as $value) {
777
      if (!empty($value['datetime'])) {
778
        $date = !is_object($value['datetime']) ? date_ical_date($value, 'UTC') : $value['datetime'];
779
        $ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z' : '';
780
        if (!empty($ex_date)) {
781
          $ex_dates[] = $ex_date;
782
        }
783
      }
784
    }
785
    if (!empty($ex_dates)) {
786
      sort($ex_dates);
787
      $rrule .= chr(13) . chr(10) . 'EXDATE:' . implode(',', $ex_dates);
788
    }
789
  }
790
  elseif (!empty($form_values['EXDATE'])) {
791
    $rrule .= chr(13) . chr(10) . 'EXDATE:' . $form_values['EXDATE'];
792
  }
793

    
794
  // Exceptions dates go last, on their own line.
795
  if (isset($form_values['RDATE']) && is_array($form_values['RDATE'])) {
796
    $ex_dates = array();
797
    foreach ($form_values['RDATE'] as $value) {
798
      $date = !is_object($value['datetime']) ? date_ical_date($value, 'UTC') : $value['datetime'];
799
      $ex_date = !empty($date) ? date_format($date, DATE_FORMAT_ICAL) . 'Z' : '';
800
      if (!empty($ex_date)) {
801
        $ex_dates[] = $ex_date;
802
      }
803
    }
804
    if (!empty($ex_dates)) {
805
      sort($ex_dates);
806
      $rrule .= chr(13) . chr(10) . 'RDATE:' . implode(',', $ex_dates);
807
    }
808
  }
809
  elseif (!empty($form_values['RDATE'])) {
810
    $rrule .= chr(13) . chr(10) . 'RDATE:' . $form_values['RDATE'];
811
  }
812

    
813
  return $rrule;
814
}