ParserVcalendar.inc 24.7 KB
Newer Older
Robert Rollins's avatar
Robert Rollins committed
1 2 3 4 5 6 7 8
<?php
/**
 * @file
 * Defines a class that parses iCalcreator vcalendar objects into
 * Feeds-compatible data arrays.
 */

class ParserVcalendar {
9 10 11
  /**
   * Variables used for parsing.
   */
Robert Rollins's avatar
Robert Rollins committed
12 13
  protected $calendar;
  protected $source;
14
  protected $fetcherResult;
Robert Rollins's avatar
Robert Rollins committed
15 16 17
  protected $config;
  protected $timezones = array();
  protected $xtimezone;
18

19 20 21 22 23 24 25 26 27 28
  /**
   * The parsed data for the component that's currently being processed.
   *
   * ParserVcalendar parses one component at a time. This array is stored as a
   * property so that each handler can tell what work the previous handlers
   * have already completed on the current component.
   *
   * @var array
   */
  protected $parsed_data = array();
29

30 31 32 33 34
  /**
   * Variables used for batch processing.
   */
  protected $totalComponents = 0;
  protected $lastComponentParsed = 0;
35

36 37 38 39 40 41 42 43 44 45
  /**
   * This is the list of iCal properties which are allowed to have more than
   * one entry in a single VEVENT. If we ever support parsing more than just
   * the first one, this listing will be useful.
   */
  protected $multi_entry_properties = array(
    'ATTACH', 'ATTENDEE', 'CATEGORIES', 'COMMENT', 'CONTACT', 'DESCRIPTION',
    'EXDATE', 'EXRULE', 'FREEBUSY', 'RDATE', 'RELATED-TO', 'RESOURCES',
    'RRULE', 'REQUEST-STATUS', 'TZNAME', 'X-PROP'
  );
46

47 48 49
  /**
   * Constructor.
   */
Robert Rollins's avatar
Robert Rollins committed
50 51 52
  public function __construct($calendar, $source, $fetcher_result, $config) {
    $this->calendar = $calendar;
    $this->source = $source;
53
    $this->mapping_sources = feeds_importer($source->id)->parser->getMappingSources();
54
    $this->fetcherResult = $fetcher_result;
Robert Rollins's avatar
Robert Rollins committed
55 56
    $this->config = $config;
  }
57

Robert Rollins's avatar
Robert Rollins committed
58 59 60
  /**
   * Parses the vcalendar object into an array of event data arrays.
   *
61
   * @param int $offset
62
   *   Specifies which section of the feed to start parsing at.
63 64
   *
   * @param int $limit
65
   *   Specifies how many components to parse on this run.
66
   *
Robert Rollins's avatar
Robert Rollins committed
67
   * @return array
68
   *   An array of parsed event data keyed by our mapping source property keys.
Robert Rollins's avatar
Robert Rollins committed
69
   */
70
  public function parse($offset, $limit) {
Robert Rollins's avatar
Robert Rollins committed
71 72 73 74 75 76 77 78 79 80 81 82
    // Sometimes, the feed will set a timezone for every event in the calendar
    // using the non-standard X-WR-TIMEZONE property. Date iCal uses this
    // timezone only if the date property is not in UTC and has no TZID.
    $xtimezone = $this->calendar->getProperty('X-WR-TIMEZONE');
    if (!empty($xtimezone[1])) {
      // Allow modules to alter the timezone string before it gets converted
      // into a DateTimeZone.
      $context = array(
        'property_key' => NULL,
        'calendar_component' => NULL,
        'calendar' => $this->calendar,
        'feeeds_source' => $this->source,
83
        'feeds_fetcher_result' => $this->fetcherResult,
Robert Rollins's avatar
Robert Rollins committed
84 85 86 87 88 89 90 91 92
      );
      drupal_alter('date_ical_import_timezone', $xtimezone[1], $context);
      $this->xtimezone = $this->_tzid_to_datetimezone($xtimezone[1]);
    }

    // Collect the timezones into an array, for easier access.
    while ($component = $this->calendar->getComponent('VTIMEZONE')) {
      $this->timezones[] = $component;
    }
93

Robert Rollins's avatar
Robert Rollins committed
94
    // This context array is used by date_ical_import_component_alter() and
95 96 97 98 99 100
    // date_ical_import_parsed_data_alter().
    $context2 = array(
      'calendar' => $this->calendar,
      'source' => $this->source,
      'fetcher_result' => $this->fetcherResult,
    );
101

102 103
    // Collect each component, so we can batch them properly in the next loop.
    $raw_components = array();
104 105 106
    $types = array('VEVENT', 'VTODO', 'VJOURNAL', 'VFREEBUSY', 'VALARM');
    foreach ($types as $type) {
      while ($vcalendar_component = $this->calendar->getComponent($type)) {
Robert Rollins's avatar
Robert Rollins committed
107 108
        // Allow modules to alter the vcalendar component before we parse it
        // into a Feeds-compatible data array.
109
        drupal_alter('date_ical_import_component', $vcalendar_component, $context2);
110
        $raw_components[] = $vcalendar_component;
Robert Rollins's avatar
Robert Rollins committed
111 112
      }
    }
113

114 115
    // Store this for use by DateiCalFeedsParser's batch processing code.
    $this->totalComponents = count($raw_components);
116

117 118 119 120 121
    // Parse each raw component in the current batch into a Feeds-compatible
    // event data array.
    $events = array();
    $batch = array_slice($raw_components, $offset, $limit, TRUE);
    foreach ($batch as $ndx => $raw_component) {
122
      $this->parsed_data = array();
123 124 125 126 127 128 129 130 131 132 133 134 135 136
      foreach ($this->mapping_sources as $property_key => $data) {
        $handler = NULL;
        if (isset($data['date_ical_parse_handler'])) {
          $handler = $data['date_ical_parse_handler'];
        }
        else {
          // This is not one of our sources, so if we don't recognize and
          // support it, we'll have to pass a warning to the user.
          if ($property_key == 'geofield') {
            $handler = 'parseGeofield';
          }
          else {
            // We can safely ignore certain sources.
            $known_unknowns = array(
137 138 139
              'Blank source 1', // "Black Source 1" is from Feeds Tamper.
              'parent:nid', // Defined in FeedsParser
              'parent:uid', // Defined in FeedsParser
140 141 142 143 144 145 146 147 148 149 150 151 152
            );
            if (!in_array($property_key, $known_unknowns)) {
              // Only warn the user if this mapping source is in use.
              foreach ($this->source->importer->processor->config['mappings'] as $mapping) {
                if ($mapping['source'] == $property_key) {
                  drupal_set_message(t('Date iCal does not recognize the "@name" Mapping Source, and must skip it.', array('@name' => $data['name'])), 'warning', FALSE);
                  break;
                }
              }
            }
          }
        }
        if ($handler) {
153
          $this->parsed_data[$property_key] = $this->$handler($property_key, $raw_component);
154
        }
155

156
        if ($property_key == 'geofield' && !empty($this->parsed_data['geofield'])) {
157 158
          // To make our data readable by geofield_feeds_combined_source(), we
          // need to put it into the format output by Simplepie 1.3.
159 160
          $this->parsed_data['location_latitude'] = array($this->parsed_data['geofield']['lat']);
          $this->parsed_data['location_longitude'] = array($this->parsed_data['geofield']['lon']);
161
        }
162
      }
163

164 165
      // Allow modules to alter the final parsed data before we send it to the
      // Feeds processor.
166
      drupal_alter('date_ical_import_post_parse', $this->parsed_data, $context2);
167

168 169 170 171
      // Skip this event if it's earlier than the user's specified skip time.
      if (!$this->_skip_current_event()) {
        $events[] = $this->parsed_data;
      }
172 173
      // The indices of the original $raw_components array are preserved in
      // $batch, so using the $ndx value here lets us communicate our progress
174
      // through the full collection of components.
175 176
      $this->lastComponentParsed = $ndx;
    }
177

Robert Rollins's avatar
Robert Rollins committed
178 179
    return $events;
  }
180

181 182 183
  /**
   * Getter for the protected totalComponents property.
   */
184 185 186
  public function getTotalComponents() {
    return $this->totalComponents;
  }
187

188 189 190
  /**
   * Getter for the protected lastComponentParsed property.
   */
191 192 193
  public function getLastComponentParsed() {
    return $this->lastComponentParsed;
  }
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208
  /**
   * Handler that parses GEO fields.
   *
   * @return array
   *   The latitude and longitude values, keyed by 'lat' and 'lon'.
   */
  public function parseGeofield($property_key, $vcalendar_component) {
    $geo = array();
    if (!empty($vcalendar_component->geo['value'])) {
      $geo['lat'] = $vcalendar_component->geo['value']['latitude'];
      $geo['lon'] = $vcalendar_component->geo['value']['longitude'];
    }
    return $geo;
  }
209

Robert Rollins's avatar
Robert Rollins committed
210
  /**
211
   * Handler that parses text fields.
Robert Rollins's avatar
Robert Rollins committed
212 213
   *
   * @return string
214
   *   The parsed text property.
Robert Rollins's avatar
Robert Rollins committed
215 216 217
   */
  public function parseTextProperty($property_key, $vcalendar_component) {
    $text = $vcalendar_component->getProperty($property_key);
218 219 220 221 222 223 224 225
    // In case someone writes a hook that adds a source for a multi-entry
    // property and a parameter of that same property, we need to force
    // iCalcreator to assume it has not accessed that property, yet.
    // TODO: This is really just a hack. If/when multi-entry properties
    // become supported, this will need to be redesigned.
    if (in_array($property_key, $this->multi_entry_properties)) {
      unset($vcalendar_component->propix[$property_key]);
    }
226

227 228 229 230 231 232
    if (is_array($text) && isset($vcalendar_component->xprop[$property_key])) {
      # This is an X-PROPERTY, which iCalcreator returns as an array like array('X-PROP-NAME', value).
      # We only care about the value, though.
      $text = $text[1];
    }

Robert Rollins's avatar
Robert Rollins committed
233
    if ($text === FALSE) {
234 235 236 237
      if ($property_key != 'SUMMARY') {
        return NULL;
      }
      else {
Robert Rollins's avatar
Robert Rollins committed
238
        $uid = $vcalendar_component->getProperty('UID');
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        if ($vcalendar_component->objName == 'vfreebusy') {
          // FREEBUSY elements can't have SUMMARY, but they can have COMMENT.
          // So if the feed has been configured to ask for SUMMARY, use COMMENT
          // instead. If COMMENT is also missing, we can't import.
          $text = $vcalendar_component->getProperty('COMMENT');
          if ($text === FALSE) {
            throw new DateIcalParseException(t('The VFREEBUSY component with UID %uid is invalid because it has no COMMENT.
              Nodes require a title, and since VFREEBUSY components can\'t have SUMMARY, Date iCal pulls that title from the COMMENT.',
              array('%uid' => $uid))
            );
          }
        }
        else {
          // Non-VFREEBUSY components must have a SUMMARY.
          throw new DateIcalParseException(t('The component with UID %uid is invalid because it has no SUMMARY (nodes require a title).',
            array('%uid' => $uid))
          );
        }
Robert Rollins's avatar
Robert Rollins committed
257 258 259 260 261 262
      }
    }
    // Convert literal \n and \N into newline characters.
    $text = str_replace(array('\n', '\N'), "\n", $text);
    return $text;
  }
263

Robert Rollins's avatar
Robert Rollins committed
264
  /**
265
   * Handler that parses field parameters.
Robert Rollins's avatar
Robert Rollins committed
266 267
   *
   * @return string
268
   *   The parsed field parameter.
Robert Rollins's avatar
Robert Rollins committed
269 270 271 272
   */
  public function parsePropertyParameter($property_key, $vcalendar_component) {
    list($key, $attr) = explode(':', $property_key);
    $property = $vcalendar_component->getProperty($key, FALSE, TRUE);
273 274 275 276
    // See parseTextProperty() for why this is here.
    if (in_array($property_key, $this->multi_entry_properties)) {
      unset($vcalendar_component->propix[$property_key]);
    }
277

Robert Rollins's avatar
Robert Rollins committed
278 279 280 281
    if ($property === FALSE) {
      // If the component doesn't have this property, return NULL.
      return NULL;
    }
282 283
    $param = isset($property['params'][$attr]) ? $property['params'][$attr] : '';
    return $param;
Robert Rollins's avatar
Robert Rollins committed
284
  }
285

Robert Rollins's avatar
Robert Rollins committed
286
  /**
287
   * Handler that parses DATE-TIME and DATE fields.
Robert Rollins's avatar
Robert Rollins committed
288 289
   *
   * @return FeedsDateTime
290
   *   The parsed datetime object.
Robert Rollins's avatar
Robert Rollins committed
291 292 293 294 295 296 297
   */
  public function parseDateTimeProperty($property_key, $vcalendar_component) {
    $property = $vcalendar_component->getProperty($property_key, FALSE, TRUE);
    // Gather all the other date properties, so we can work with them later.
    $duration = $vcalendar_component->getProperty('DURATION', FALSE, TRUE);
    $dtstart = $vcalendar_component->getProperty('DTSTART', FALSE, TRUE);
    $uid = $vcalendar_component->getProperty('UID');
298

299
    // DATE-type properties are treated as All Day events which can span over
300 301 302 303 304
    // multiple days.
    // The Date module's All Day event handling was never finalized
    // (http://drupal.org/node/874322), which requires us to do some some
    // special coddling later.
    $is_all_day = (isset($property['params']['VALUE']) && $property['params']['VALUE'] == 'DATE');
305

306
    // Cover various conditions in which either DTSTART or DTEND are not set.
Robert Rollins's avatar
Robert Rollins committed
307
    if ($property === FALSE) {
308
      // When DTEND isn't defined, we may need to emulate it.
Robert Rollins's avatar
Robert Rollins committed
309
      if ($property_key == 'DTEND') {
310 311
        // Unset DTENDs need to emulate the DATE type from DTSTART.
        $is_all_day = (isset($dtstart['params']['VALUE']) && $dtstart['params']['VALUE'] == 'DATE');
312

313 314
        if ($duration !== FALSE) {
          // If a DURATION is defined, emulate DTEND as DTSTART + DURATION.
315
          $property = array(
316 317 318 319
            'value' => iCalUtilityFunctions::_duration2date($dtstart['value'], $duration['value']),
            'params' => $dtstart['params'],
          );
        }
320
        elseif ($is_all_day) {
321 322
          // If this is an all-day event with no end or duration, treat this
          // as a single-day event by emulating DTEND as 1 day after DTSTART.
323
          $property = $dtstart;
324
          $property['value'] = iCalUtilityFunctions::_duration2date($property['value'], array('day' => 1));
325 326 327 328 329
        }
        else {
          // This event has no end date.
          return NULL;
        }
Robert Rollins's avatar
Robert Rollins committed
330
      }
331
      elseif ($property_key == 'DTSTART') {
332
        // DTSTART can only be legally unset in non-VEVENT components.
Robert Rollins's avatar
Robert Rollins committed
333 334 335 336 337 338 339 340
        if ($vcalendar_component->objName == 'vevent') {
          throw new DateIcalParseException(t('Feed import failed! The VEVENT with UID %uid is invalid: it has no DTSTART.', array('%uid' => $uid)));
        }
        else {
          return NULL;
        }
      }
    }
341

342 343 344 345
    // When iCalcreator parses a UTC date (one that ends with Z) from an iCal
    // feed, it stores that 'Z' into the $property['value']['tz'] value.
    if (isset($property['value']['tz'])) {
      $property['params']['TZID'] = 'UTC';
Robert Rollins's avatar
Robert Rollins committed
346
    }
347

348
    if ($is_all_day) {
Robert Rollins's avatar
Robert Rollins committed
349 350
      if ($property_key == 'DTEND') {
        if ($dtstart === FALSE) {
351 352
          // This will almost certainly never happen, but the error message
          // would be incomprehensible without this check.
Robert Rollins's avatar
Robert Rollins committed
353 354 355 356
          throw new DateIcalParseException(t('Feed import failed! The event with UID %uid is invalid: it has a DTEND but no DTSTART!', array('%uid' => $uid)));
        }

        if (module_exists('date_all_day')) {
357 358 359
          // If the Date All Day module is installed, we need to rewind the
          // DTEND by one day, because of the problem with FeedsDateTime
          // mentioned below.
Robert Rollins's avatar
Robert Rollins committed
360
          $prev_day = iCalUtilityFunctions::_duration2date($property['value'], array('day' => -1));
361
          $property['value'] = $prev_day;
Robert Rollins's avatar
Robert Rollins committed
362 363
        }
      }
364

Robert Rollins's avatar
Robert Rollins committed
365 366
      // FeedsDateTime->setTimezone() ignores timezone changes made to dates
      // with no time element, which means we can't compensate for the Date
367 368 369
      // module's automatic timezone conversion when it writes to the DB. To
      // get around that, we must add 00:00:00 explicitly, even though this
      // causes other problems (see above and below).
Robert Rollins's avatar
Robert Rollins committed
370 371
      $date_string = sprintf('%d-%d-%d 00:00:00', $property['value']['year'], $property['value']['month'], $property['value']['day']);
      // Use the server's timezone rather than letting it default to UTC.
372
      // This will help ensure that the date value doesn't get messed up when
373
      // Date converts its timezone as the value is read from the database.
374 375 376 377 378 379
      // This is *essential* for All Day events, because Date stores them as
      // '2013-10-03 00:00:00' in the database, rather than doing the sensible
      // thing and storing them as '2013-10-03'.
      // NOTE TO MAINTAINERS:
      // This will not work properly if the site is configured to allow users
      // to set their own timezone. Unfortunately, there isn't anything that
Robert Rollins's avatar
Robert Rollins committed
380
      // Date iCal can do about that, as far as I can tell.
Robert Rollins's avatar
Robert Rollins committed
381 382 383 384 385
      $datetimezone = new DateTimeZone(date_default_timezone_get());
    }
    else {
      // This is a DATE-TIME property.
      $date_string = iCalUtilityFunctions::_format_date_time($property['value']);
386

387 388 389 390 391 392 393 394 395 396 397
      // Allow modules to alter the timezone string. This also allows for
      // setting a TZID when one was not originally set for this property.
      $tzid = isset($property['params']['TZID']) ? $property['params']['TZID'] : NULL;
      $context = array(
        'property_key' => $property_key,
        'calendar_component' => $vcalendar_component,
        'calendar' => $this->calendar,
        'feeeds_source' => $this->source,
        'feeds_fetcher_result' => $this->fetcherResult,
      );
      drupal_alter('date_ical_import_timezone', $tzid, $context);
398

399 400
      if (isset($tzid)) {
        $datetimezone = $this->_tzid_to_datetimezone($tzid);
Robert Rollins's avatar
Robert Rollins committed
401
      }
402
      elseif (isset($this->xtimezone)) {
Robert Rollins's avatar
Robert Rollins committed
403 404 405 406 407
        // No timezone was set on the parsed date property, so if a timezone
        // was detected for the entire iCal feed, use it.
        $datetimezone = $this->xtimezone;
      }
      else {
408 409
        $msg = t("No timezone was detected for one or more of the events in this feed, forcing Date iCal to use this server's timezone as a fallback.<br>
            To make timezone-less events use a different timezone, implement hook_date_ical_import_timezone_alter() in a custom module.");
410 411 412
        drupal_set_message($msg, 'status', FALSE);
        $this->source->log('parse', $msg, array(), WATCHDOG_NOTICE);
        $datetimezone = new DateTimeZone(date_default_timezone_get());
Robert Rollins's avatar
Robert Rollins committed
413 414
      }
    }
415

416 417
    $datetime = new FeedsDateTime($date_string, $datetimezone);
    return $datetime;
Robert Rollins's avatar
Robert Rollins committed
418
  }
419

Robert Rollins's avatar
Robert Rollins committed
420
  /**
421
   * Handler that parses multi-value fields, like the CATEGORIES component.
Robert Rollins's avatar
Robert Rollins committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
   *
   * @return array
   *   An array of strings contaning the individual values.
   */
  public function parseMultivalueProperty($property_key, $vcalendar_component) {
    // Since we're not telling it to give us the params data, $property will
    // be either FALSE, a string, or an array of strings.
    $property = $vcalendar_component->getProperty($property_key);
    if (empty($property)) {
      // If this multi-value property is being mapped to a Taxonomy field,
      // Feeds will interpret anything besides empty array as an array of
      // empty values (e.g. array('')). This will create a term for that
      // empty value, rather than leaving the field blank.
      return array();
    }
    if (!is_array($property)) {
      $property = array($property);
    }
    return $property;
  }
442

Robert Rollins's avatar
Robert Rollins committed
443
  /**
444
   * Handler that parses RRULE, RDATE, EXRULE, and EXDATE together.
Robert Rollins's avatar
Robert Rollins committed
445 446
   *
   * @return string
447
   *   The RRULE, RDATE, EXRULE, and EXDATE values concatinated with |.
Robert Rollins's avatar
Robert Rollins committed
448 449 450 451 452
   */
  public function parseRepeatProperty($property_key, $vcalendar_component) {
    if ($vcalendar_component->getProperty($property_key) === FALSE) {
      return NULL;
    }
453

454 455
    $uid = $vcalendar_component->getProperty('UID');
    $count = $this->config['indefinite_count'];
Robert Rollins's avatar
Robert Rollins committed
456 457 458
    // Due to a few bugs and limitations with Date Repeat, we need to massage
    // the RRULE a bit.
    if (count($vcalendar_component->rrule) > 1) {
459
      // TODO: Is Date Repeat still limited to 1 RRULE with Feeds 2.0-beta1?
460 461 462 463 464
      $msg = 'The event with UID %uid has multiple RRULEs, but the Date Repeat module only supports one. Only the first RRULE in the event will be used.
        If your events need to have a complex repeat pattern, using RDATEs should help.';
      watchdog('date_ical', $msg, array('%uid' => $uid), 'warning');
      drupal_set_message('At least one of the events in this iCal feed has multiple RRULEs, but the Date Repeat module only supports one.
        Only the first RRULE in an event will be used.', 'warning', FALSE);
465

466 467 468
      // Date Repeat will get extremely confused if it's sent multiple RRULE
      // values, so we need to manually pare it down to only the first one.
      $vcalendar_component->rrule = array($vcalendar_component->rrule[0]);
Robert Rollins's avatar
Robert Rollins committed
469
    }
Robert Rollins's avatar
Robert Rollins committed
470
    foreach ($vcalendar_component->rrule as &$rrule_data) {
Robert Rollins's avatar
Robert Rollins committed
471
      // RRULEs must have an INTERVAL, or Date Repeat will throw errors.
472
      // TODO: Is this still true with Feeds 2.0-beta1?
Robert Rollins's avatar
Robert Rollins committed
473 474 475
      if (!isset($rrule_data['value']['INTERVAL'])) {
        $rrule_data['value']['INTERVAL'] = '1';
      }
476

477
      if ((!isset($rrule_data['value']['COUNT']) && !isset($rrule_data['value']['UNTIL']))) {
478 479 480
        $msg = "The event with UID %uid has an indefinitely repeating RRULE, which the Date Repeat module doesn't support.
          As a workaround, Date iCal set the repeat count to @count. This value can be customized in the iCal parser settings.";
        watchdog('date_ical', $msg, array('%uid' => $uid, '@count' => $count), WATCHDOG_WARNING);
481
        if (!empty($this->config['indefinite_message_display'])) {
482 483 484 485 486 487 488 489
          drupal_set_message(
            t("At least one of the events in this iCal feed has an indefinitely repeating RRULE, which the Date Repeat module doesn't support.<br>
              As a workaround, Date iCal set the repeat count to @count. This value can be customized in the iCal parser settings.",
            array('@count' => $count)),
            'warning',
            FALSE
          );
        }
490 491 492 493 494 495 496 497
        if (isset($this->config['indefinite_count'])) {
          $rrule_data['value']['COUNT'] = $this->config['indefinite_count'];
        }
        else {
          // Somehow, it's possible for the config values to have no setting, even though we've given them a default.
          // So make really sure we set the COUNT to *something*.
          $rrule_data['value']['COUNT'] = 52;
        }
Robert Rollins's avatar
Robert Rollins committed
498 499
      }
    }
500

501 502 503 504 505 506
    # Due to a bug in iCalcreator 2.20.2, any repeat property that's too long to fit on one line will be returned
    # verbatim, including the endline and the single-space indentation that starts the second line. Thus, we need to
    # remove those things ourselves.
    $rrule = trim(preg_replace('/\s/', '', $vcalendar_component->createRrule()));
    $rdate = trim(preg_replace('/\s/', '', $vcalendar_component->createRdate()));
    $exrule = trim(preg_replace('/\s/', '', $vcalendar_component->createExrule()));
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

    // Modules such as Date Repeat, as well as our parsing functions, generally
    // expect a single EXDATE entry for optimal operation. If we have multiple
    // entries in the data, we should concatenate them here.
    $parsed_exdate = trim(preg_replace('/\s/', '', $vcalendar_component->createExdate()));

    // First, get the individual contents of any definitions. It's OK even if
    // there is only one.
    $exdate_parts = explode('EXDATE;', $parsed_exdate);
    array_shift($exdate_parts); // First element always blank.

    // Extended parameters such as VALUE and TZID are set in the first EXDATE
    // The other ones must not repeat them. We skip the first entry when
    // enforcing this, obviously.
    $skip = TRUE;
    foreach ($exdate_parts as &$exdate_part) {
      if ($skip) {
        $skip = FALSE;
        continue;
      }

      // This strips off the part before the colon, since we only want the value
      // from the first EXDATE entry. end() wants a real array, hence why two
      // lines.
      $exdate_part_parts = explode(':', $exdate_part);
      $exdate_part = end($exdate_part_parts);
    }

    // Combine the parts back together with an EXDATE; specifier in front.
    $exdate = 'EXDATE;' . implode(',', $exdate_parts);
537

538
    return "$rrule|$rdate|$exrule|$exdate";
Robert Rollins's avatar
Robert Rollins committed
539
  }
540

541 542 543
  /**
   * Internal helper function for creating DateTimeZone objects.
   */
Robert Rollins's avatar
Robert Rollins committed
544 545 546 547 548
  protected function _tzid_to_datetimezone($tzid) {
    try {
      $datetimezone = new DateTimeZone($tzid);
    }
    catch (Exception $e) {
549 550 551 552 553 554 555
      // In case this is a Windows TZID, read the mapping file to try and
      // convert it to a real TZID.
      $zones = file_get_contents(drupal_get_path('module', 'date_ical') . '/libraries/windowsZones.json');
      $zones_assoc = json_decode($zones, TRUE);
      $windows_to_olson_map = array();
      foreach ($zones_assoc['supplemental']['windowsZones']['mapTimezones'] as $mapTimezone) {
        if ($mapTimezone['mapZone']['_other'] == $tzid) {
556
          // Parse out the space-separated TZIDs from $mapTimezone['mapZone']['_type'].
557 558 559 560 561 562 563 564 565 566 567 568 569
          $tzids = preg_split('/\s/', $mapTimezone['mapZone']['_type']);
          try {
            // They all have the same UTC offset, so for our purposes we can
            // just take the first one.
            return new DateTimeZone($tzids[0]);
          }
          catch (Exception $e) {
            // If this one also fails, we're out of luck, so just fall through
            // to the regular error report code.
            break;
          }
        }
      }
570

571 572
      $tz_wiki = l(t('here'), 'http://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List');
      $help = l(t('README'), 'admin/help/date_ical', array('absolute' => TRUE));
Robert Rollins's avatar
Robert Rollins committed
573
      $msg = t(
574 575 576
          '"@tz" is not a valid timezone (see the TZ column !here), so Date iCal had to fall back to UTC (which is probably wrong!).<br>
          Please read the Date iCal !readme for instructions on how to fix this.',
          array('@tz' => $tzid, '!here' => $tz_wiki, '!readme' => $help)
Robert Rollins's avatar
Robert Rollins committed
577 578 579
      );
      $this->source->log('parse', $msg, array(), WATCHDOG_WARNING);
      drupal_set_message($msg, 'warning', FALSE);
580
      $datetimezone = new DateTimeZone('UTC');
Robert Rollins's avatar
Robert Rollins committed
581 582 583
    }
    return $datetimezone;
  }
584

585 586 587 588 589 590 591 592 593 594 595 596 597
  /**
   * Internal helper function for skipping old events.
   */
  protected function _skip_current_event() {
    // Must use !isset() here, because 0 and NULL mean different things.
    if (!isset($this->config['skip_days'])) {
      return FALSE;
    }
    $compare_date = isset($this->parsed_data['DTEND']) ? $this->parsed_data['DTEND'] : $this->parsed_data['DTSTART'];
    $skip_date = new FeedsDateTime("today -{$this->config['skip_days']} days", $compare_date->getTimezone());
    $skip = ($skip_date > $compare_date);
    return $skip;
  }
Robert Rollins's avatar
Robert Rollins committed
598
}