ParserVcalendar.inc 14.4 KB
Newer Older
Robert Rollins's avatar
Robert Rollins committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
<?php

/**
 * @file
 * Defines a class that parses iCalcreator vcalendar objects into
 * Feeds-compatible data arrays.
 */

class ParserVcalendar {
  protected $calendar;
  protected $source;
  protected $fetcher_result;
  protected $config;
  protected $timezones = array();
  protected $xtimezone;

  public function __construct($calendar, $source, $fetcher_result, $config) {
    $this->calendar = $calendar;
    $this->source = $source;
    $this->fetcher_result = $fetcher_result;
    $this->config = $config;
  }

  /**
   * Parses the vcalendar object into an array of event data arrays.
   *
   * @return array
   *   An array keyed by the same property keys as returned by
   *   DateiCalFeedsParser::getiCalMappingSources().
   */
  public function parse() {
    // 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,
        'feeds_fetcher_result' => $this->fetcher_result,
      );
      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;
    }

    // Parse each calendar component it into a Feeds-compatible data array.
    $events = array();
    $component_types = array('VEVENT', 'VTODO', 'VJOURNAL', 'VFREEBUSY', 'VALARM');
    foreach ($component_types as $component_type) {
      while ($vcalendar_component = $this->calendar->getComponent($component_type)) {
        // Allow modules to alter the vcalendar component before we parse it
        // into a Feeds-compatible data array.
        $context = array(
          'calendar' => $this->calendar,
          'source' => $this->source,
          'fetcher_result' => $this->fetcher_result,
        );
        drupal_alter('date_ical_import_component', $vcalendar_component, $context);

        $parsed_component = array();
        foreach (DateiCalFeedsParser::getiCalMappingSources() as $property_key => $data) {
          $handler = $data['date_ical_parse_handler'];
          $parsed_component[$property_key] = $this->$handler($property_key, $vcalendar_component);
        }
        $events[] = $parsed_component;
      }
    }

    return $events;
  }

  /**
   * Parses text fields.
   *
   * @return string
   */
  public function parseTextProperty($property_key, $vcalendar_component) {
    $text = $vcalendar_component->getProperty($property_key);
    if ($text === FALSE) {
      if ($property_key == 'SUMMARY') {
        $uid = $vcalendar_component->getProperty('UID');
        throw new DateIcalParseException(t('The component with UID %uid is invalid because it has no SUMMARY (nodes require a title).', array('%uid' => $uid)));
      }
      // If the component doesn't have this property, return NULL.
      return NULL;
    }
    // Convert literal \n and \N into newline characters.
    $text = str_replace(array('\n', '\N'), "\n", $text);
    return $text;
  }

  /**
   * Parses field parameters.
   *
   * @return string
   */
  public function parsePropertyParameter($property_key, $vcalendar_component) {
    list($key, $attr) = explode(':', $property_key);
    $property = $vcalendar_component->getProperty($key, FALSE, TRUE);
    if ($property === FALSE) {
      // If the component doesn't have this property, return NULL.
      return NULL;
    }
    return isset($property['params'][$attr]) ? $property['params'][$attr]: '';
  }

  /**
   * Parses datetime fields.
   *
   * @return FeedsDateTime
   */
  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);
    $dtend = $vcalendar_component->getProperty('DTEND', FALSE, TRUE);
    $uid = $vcalendar_component->getProperty('UID');

    if ($property === FALSE) {
      if ($property_key == 'DTEND') {
        return NULL;
      }
      else if ($property_key == 'DTSTART') {
        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;
        }
      }
    }

    // It's frustrating that iCalcreator gives us date data in a different
    // format than what it expects us to give back.
    if (isset($property['params']['TZID'])) {
      $property['value']['tz'] = $property['params']['TZID'];
    }

    if (isset($property['params']['VALUE']) && $property['params']['VALUE'] == 'DATE') {
      // DATE-type values are treated as All Day events, with no time-of-day.
      // They can span over multiple days.
      // The Date module's All Day event handling was never finalized:
      // http://drupal.org/node/874322
      if ($property_key == 'DTEND') {
        if ($dtstart === FALSE) {
          // This will almost certainly never happen, but the error message
          // in this case should be comprehensible.
          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 the Date All Day module is installed, single-day All Day events
        // will be displayed wrong unless we ignore the DTEND value.
        if (module_exists('date_all_day')) {
          $prev_day = iCalUtilityFunctions::_duration2date($property['value'], array('day' => -1));
          if ($dtstart['value'] == $prev_day) {
            return NULL;
          }
          else {
            // If Date All Day is installed and this All Day event spans
            // multiple days, we need to rewind the DTEND by one day, because
            // of the problem with FeedsDateTime mentioned below.
            $property['value'] = $prev_day;
          }
        }
      }
      else if ($property_key == 'DTSTART') {
        // NOTE TO MAINTAINERS: This is why DTSTART *must* be parsed first!
        // If DTEND is parsed first, this block will have no effect.
        if ($dtend === FALSE && $duration === FALSE) {
          // If the All Day event has no DTEND and no DURATION, assume the
          // event is a single day: set DTEND = DTSTART + 1 day.
          $end = $property['value'];
          $end['day'] += 1;
          $vcalendar_component->setDtend($end['year'], $end['month'], $end['day'], FALSE, FALSE, FALSE, FALSE, array('VALUE' => 'DATE'));
        }
      }

      // FeedsDateTime->setTimezone() ignores timezone changes made to dates
      // with no time element, which means we can't compensate for the Date
      // module's automatic conversion to UTC when it writes to the DB. To get
      // around that, we must add 00:00:00 explicitly.
      $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.
      // This will ensure that the date value doesn't get messed up when Date
      // converts it back from UTC when it's read from the database.
      $datetimezone = new DateTimeZone(date_default_timezone_get());
    }
    else {
      // This is a DATE-TIME property.
      $date_string = iCalUtilityFunctions::_format_date_time($property['value']);

      if (isset($property['value']['tz'])) {
        // Z == Zulu == UTC. DateTimeZone won't acept Z, so change it to UTC.
        if (strtoupper($property['value']['tz']) == 'Z') {
          $property['value']['tz'] = 'UTC';
        }
        // Allow modules to alter the timezone string before it gets converted
        // into a DateTimeZone.
        $context = array(
          'property_key' => $property_key,
          'calendar_component' => $vcalendar_component,
          'calendar' => $this->calendar,
          'feeeds_source' => $this->source,
          'feeds_fetcher_result' => $this->fetcher_result,
        );
        drupal_alter('date_ical_import_timezone', $property['value']['tz'], $context);

        $datetimezone = $this->_tzid_to_datetimezone($property['value']['tz']);
      }
      else if (isset($this->xtimezone)) {
        // 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 if (count($this->timezones) == 1) {
        // There is exactly one VTIMEZONE in this feed, this date field doesn't
        // specify a timezone, and there's no X-WR-TIMEZONE. The best we can do
        // is assume this field should use the sole available TZID.
        $datetimezone = $this->_tzid_to_datetimezone($this->timezones[0]->getProperty('TZID'));
      }
      else {
        drupal_set_message(t('No timezone detected for the @key property of the event with UID %uid. Falling back to UTC.',
        array('%uid' => $uid, '@key' => $property_key)), 'warning');
        $datetimezone = new DateTimeZone('UTC');
      }
    }

    // NOTE TO MAINTAINERS: This is why DTSTART *must* be parsed first!
    // If DTEND is parsed first, this block will have no effect.
    if ($property_key == 'DTSTART' && $dtend === FALSE && $duration !== FALSE) {
      // In order to call $vcalendar_component->setDtend() correctly for both
      // DATE and DATE-TIME values, we need to build this dummy array first.
      $new_dtend = array(
        'year'  => NULL,
        'month' => NULL,
        'day'   => NULL,
        'hour'  => NULL,
        'min'   => NULL,
        'sec'   => NULL,
        'tz'    => NULL,
        'params' => $property['params'],
      );
      // If this component has no DTEND, but it does have a DURATION, set
      // DTEND = DTSTART + DURATION.
      $new_dtend = array_merge($new_dtend, iCalUtilityFunctions::_duration2date($property['value'], $duration['value']));
      call_user_func_array(array($vcalendar_component, 'setDtend'), $new_dtend);
    }

    return new FeedsDateTime($date_string, $datetimezone);
  }

  /**
   * Parses multi-value fields, like the CATEGORIES component.
   *
   * @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;
  }

  /**
   * Format RRULEs, which specify when and how often the event is repeated.
   *
   * @return string
   *   An RRULE string, with EXDATE and RDATE values separated by \n.
   *   This is to make the RRULE compatible with date_repeat_split_rrule().
   */
  public function parseRepeatProperty($property_key, $vcalendar_component) {
    if ($vcalendar_component->getProperty($property_key) === FALSE) {
      return NULL;
    }

    // Due to a few bugs and limitations with Date Repeat, we need to massage
    // the RRULE a bit.
    if (count($vcalendar_component->rrule) > 1) {
      drupal_set_message(t('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.<br>
          If your events need to have a complex repeat pattern, using RDATEs should help.',
          array('%uid' => $vcalendar_component->getProperty('UID'))), 'warning'
              );
              // 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]);
    }
    foreach ($vcalendar_component->rrule as $ndx => &$rrule_data) {
      // RRULEs must have an INTERVAL, or Date Repeat will throw errors.
      if (!isset($rrule_data['value']['INTERVAL'])) {
        $rrule_data['value']['INTERVAL'] = '1';
      }

      if (!isset($rrule_data['value']['COUNT']) && !isset($rrule_data['value']['UNTIL'])) {
        drupal_set_message(t('The event with UID %uid 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('%uid' => $vcalendar_component->getProperty('UID'), '@count' => $this->config['indefinite_count'])), 'warning'
        );
        $rrule_data['value']['COUNT'] = $this->config['indefinite_count'];
      }
    }

    $rrule = trim($vcalendar_component->createRrule());
    $exdate = trim($vcalendar_component->createExdate());
    $rdate = trim($vcalendar_component->createRdate());
    return "$rrule\n$exdate\n$rdate";
  }

  protected function _tzid_to_datetimezone($tzid) {
    try {
      $datetimezone = new DateTimeZone($tzid);
    }
    catch (Exception $e) {
      $link = l('here', 'http://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List', array('absolute' => TRUE));
      $msg = t(
          '"@tz" is not a valid timezone (see the TZ column !here), so Date iCal used UTC (which is probably wrong!).<br>
          Try implementing hook_date_ical_import_timezone_alter() in a custom module to fix this problem.',
          array('@tz' => $tzid, '!here' => $link)
      );
      $this->source->log('parse', $msg, array(), WATCHDOG_WARNING);
      drupal_set_message($msg, 'warning', FALSE);
      $datetimezone = new DateTimeZone("UTC");
    }
    return $datetimezone;
  }
}