date_ical_plugin_style_ical_feed.inc 18.5 KB
Newer Older
Robert Rollins's avatar
Robert Rollins committed
1 2 3 4 5 6 7 8 9 10 11 12
<?php

/**
 * @file
 * Views style plugin for the Date iCal module.
 */

/**
 * Default style plugin to render an iCal feed.
 */
class date_ical_plugin_style_ical_feed extends views_plugin_style {
  
13
  protected function _get_option($option_name) {
Robert Rollins's avatar
Robert Rollins committed
14
    return isset($this->options[$option_name]) ? $this->options[$option_name] : '';
Robert Rollins's avatar
Robert Rollins committed
15 16 17 18 19 20 21 22 23 24 25
  }
  
  // Sets up the iCal feed icon on calendar pages.
  function attach_to($display_id, $path, $title) {
    $display = $this->view->display[$display_id]->handler;
    $url_options = array();
    $input = $this->view->get_exposed_input();
    if ($input) {
      $url_options['query'] = $input;
    }
    $url_options['absolute'] = TRUE;
Robert Rollins's avatar
Robert Rollins committed
26
    
Robert Rollins's avatar
Robert Rollins committed
27
    $url = url($this->view->get_url(NULL, $path), $url_options);
Robert Rollins's avatar
Robert Rollins committed
28 29 30
    // If the user didn't disable the option, change the scheme to webcal:// so
    // that calendar clients can automatically subscribe via the iCal link.
    if (!$this->_get_option('disable_webcal')) {
31
      $url = str_replace(array('http://', 'https://'), 'webcal://', $url);
Robert Rollins's avatar
Robert Rollins committed
32 33
    }
    
34
    // Render the feed icon and header tag (except during a View Preview).
Robert Rollins's avatar
Robert Rollins committed
35 36
    if (empty($this->view->live_preview)) {
      $tooltip = t('Add to My Calendar');
37 38 39 40
      if (!isset($this->view->feed_icon)) {
        // In PHP 5.5, you're no longer allowed to concatinate onto a not-yet-existent property.
        $this->view->feed_icon = '';
      }
41
      $this->view->feed_icon .= theme('date_ical_icon', array('url' => check_url($url), 'tooltip' => $tooltip, 'view' => $this->view));
Robert Rollins's avatar
Robert Rollins committed
42 43
      drupal_add_html_head_link(array(
        'rel' => 'alternate',
Robert Rollins's avatar
Robert Rollins committed
44 45
        'type' => 'text/calendar',
        'title' => $tooltip,
Robert Rollins's avatar
Robert Rollins committed
46 47 48 49 50
        'href' => $url
      ));
    }
  }
  
51 52 53
  function option_definition() {
    $options = parent::option_definition();
    $options['cal_name'] = array('default' => array());
54 55 56
    $options['no_calname'] = array('default' => FALSE, 'bool' => TRUE);
    $options['disable_webcal'] = array('default' => FALSE, 'bool' => TRUE);
    $options['exclude_dtstamp'] = array('default' => FALSE, 'bool' => TRUE);
57
    $options['unescape_punctuation'] = array('default' => FALSE, 'bool' => TRUE);
58 59 60
    return $options;
  }
  
Robert Rollins's avatar
Robert Rollins committed
61 62 63 64 65 66
  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    // Allow users to override the default Calendar name (X-WR-CALNAME).
    $form['cal_name'] = array(
      '#type' => 'textfield',
      '#title' => t('iCal Calendar Name'),
Robert Rollins's avatar
Robert Rollins committed
67
      '#default_value' => $this->_get_option('cal_name'),
68 69
      '#description' => t('This will appear as the title of the iCal feed. If left blank, the View Title will be used.
        If that is also blank, the site name will be inserted as the iCal feed title.'),
Robert Rollins's avatar
Robert Rollins committed
70
    );
Robert Rollins's avatar
Robert Rollins committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    $form['no_calname'] = array(
      '#type' => 'checkbox',
      '#title' => t('Exclude Calendar Name'),
      '#default_value' => $this->_get_option('no_calname'),
      '#description' => t("Excluding the X-WR-CALNAME value from the iCal Feed causes
        some calendar clients to add the events in the feed to an existing calendar, rather
        than creating a whole new calendar for them."),
    );
    $form['disable_webcal'] = array(
      '#type' => 'checkbox',
      '#title' => t('Disable webcal://'),
      '#default_value' => $this->_get_option('disable_webcal'),
      '#description' => t("By default, the feed URL will use the webcal:// scheme, which allows calendar
        clients to easily subscribe to the feed. If you want your users to instead download this iCal
        feed as a file, activate this option."),
    );
87 88 89 90 91 92 93 94 95
    $form['exclude_dtstamp'] = array(
      '#type' => 'checkbox',
      '#title' => t('Exclude DTSTAMP'),
      '#default_value' => $this->_get_option('exclude_dtstamp'),
      '#description' => t("By default, the feed will set each event's DTSTAMP property to the time at which the feed got downloaded.
        Some feed readers will (incorrectly) look at the DTSTAMP value when they compare different downloads of the same feed, and
        conclcude that the event has been updated (even though it hasn't actually changed). Enable this option to exclude the DTSTAMP
        field from your feeds, so that these buggy feed readers won't mark every event as updated every time they check."),
    );
96 97 98 99 100 101 102 103
    $form['unescape_punctuation'] = array(
      '#type' => 'checkbox',
      '#title' => t('Unescape Commas and Semicolons'),
      '#default_value' => $this->_get_option('unescape_punctuation'),
      '#description' => t('In order to comply with the iCal spec, Date iCal will "escape" commas and semicolons (prepend them with backslashes).
        However, many calendar clients are bugged to not unescape these characters, leaving the backslashes littered throughout your events\' text fields.
        Enable this option to have Date iCal unescape these characters before it exports the iCal feed.'),
    );
Robert Rollins's avatar
Robert Rollins committed
104 105 106
  }
  
  function render() {
107 108
    if (empty($this->row_plugin) || !in_array($this->row_plugin->plugin_name, array('date_ical', 'date_ical_fields'))) {
      debug('date_ical_plugin_style_ical_feed: This style plugin supports only the "iCal Entity" and "iCal Fields" row plugins.', NULL, TRUE);
109
      return t('To enable iCal output, this view\'s Format must be configured to Show: iCal Entity or iCal Fields.');
Robert Rollins's avatar
Robert Rollins committed
110
    }
111 112
    if ($this->row_plugin->plugin_name == 'date_ical_fields' && empty($this->row_plugin->options['date_field'])) {
      // Because the Date field is required by the form, this error state will rarely occur. But I ran across it during
113
      // testing, and the error that resulted was totally non-sensical, so I'm adding this in case it does ever happen.
114
      return t("When using the iCal Fields row plugin, the Date field is required. Please set it up using the Settings link under 'Format -> Show: iCal Fields'.");
115 116
    }
    $events = array();
Robert Rollins's avatar
Robert Rollins committed
117 118
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
119
      $row->index = $row_index;
120
      try {
121
        $events[] = $this->row_plugin->render($row);
122 123 124 125 126
      }
      catch (Exception $e) {
        debug($e->getMessage(), NULL, TRUE);
        return $e->getMessage();
      }
Robert Rollins's avatar
Robert Rollins committed
127 128
    }
    unset($this->view->row_index);
129
    
130
    // Try to load the iCalcreator library.
Robert Rollins's avatar
Robert Rollins committed
131
    $library = libraries_load('iCalcreator');
132 133 134 135 136
    if (empty($library['loaded'])) {
      // The iCalcreator library isn't available, so we can't output anything.
      $output = t('Please install the iCalcreator library to enable iCal output.');
    }
    else {
Robert Rollins's avatar
Robert Rollins committed
137
      // Create a vcalendar object using the iCalcreator library.
138
      $config = array('unique_id' => 'Date iCal v' . DATE_ICAL_VERSION);
Robert Rollins's avatar
Robert Rollins committed
139 140 141
      $vcalendar = new vcalendar($config);
      $vcalendar->setMethod('PUBLISH');
      
142 143 144 145 146 147 148 149 150
      // Only include the X-WR-CALNAME property if the user didn't enable
      // the "Exclude Calendar Name" option.
      if (!$this->_get_option('no_calname')) {
        $cal_name = $this->_get_option('cal_name');
        if (empty($cal_name)) {
          $cal_name = $this->view->get_title();
          if (empty($cal_name)) {
            $cal_name = variable_get('site_name', 'Drupal');
          }
151
        }
152 153
        if (!empty($cal_name)) {
          $vcalendar->setProperty('X-WR-CALNAME', $cal_name, array('VALUE' => 'TEXT'));
154
        }
Robert Rollins's avatar
Robert Rollins committed
155
      }
156
      
Robert Rollins's avatar
Robert Rollins committed
157
      // Now add the VEVENTs.
Robert Rollins's avatar
Robert Rollins committed
158
      $timezones = array();
159 160
      foreach ($events as $event) {
        if (empty($event)) {
161
          // The row plugin returned NULL for this row, which can happen due to
162 163
          // either various error conditions, or because an RRULE is involved.
          // When this happens, just skip it.
164 165 166
          continue;
        }
        
Robert Rollins's avatar
Robert Rollins committed
167
        $vevent = $vcalendar->newComponent('vevent');
168 169 170
        $vevent->setUid($event['uid']);
        $vevent->setSummary($event['summary']);
        
Robert Rollins's avatar
Robert Rollins committed
171
        // Get the start date as an array.
172
        $start = $event['start']->toArray();
173 174
        $start_timezone = $event['start']->getTimezone()->getName();
        $timezones[$start_timezone] = $start_timezone;
175
        
176
        if ($event['all_day']) {
177
          // All Day events need to be specified as DATE, rather than DATE-TIME, or they get interpretted wrong.
178 179 180 181 182 183 184 185 186 187 188
          $vevent->setDtstart($start['year'], $start['month'], $start['day'],
            FALSE, FALSE, FALSE, FALSE, array('VALUE' => 'DATE'));
        }
        else {
          $vevent->setDtstart(
            $start['year'],
            $start['month'],
            $start['day'],
            $start['hour'],
            $start['minute'],
            $start['second'],
189
            $start_timezone
190
          );
191
        }
192
        
193
        // Add the Timezone info to the start date, for use later.
194
        $start['tz'] = $event['start']->getTimezone();
195
        
Robert Rollins's avatar
Robert Rollins committed
196
        // Only add the end date if there is one.
197 198
        if (!empty($event['end'])) {
          $end = $event['end']->toArray();
199 200
          $end_timezone = $event['end']->getTimezone()->getName();
          $timezones[$end_timezone] = $end_timezone;
201
          
202
          if ($event['all_day']) {
203 204 205 206 207 208 209 210 211 212 213
            $vevent->setDtend($end['year'], $end['month'], $end['day'],
              FALSE, FALSE, FALSE, FALSE, array('VALUE' => 'DATE'));
          }
          else {
            $vevent->setDtend(
              $end['year'],
              $end['month'],
              $end['day'],
              $end['hour'],
              $end['minute'],
              $end['second'],
214
              $end_timezone
215
            );
216
          }
217
          $end['tz'] = $event['end']->getTimezone();
Robert Rollins's avatar
Robert Rollins committed
218
        }
219
        
Robert Rollins's avatar
Robert Rollins committed
220
        // Handle repeating dates from the date_repeat module.
221
        if (!empty($event['rrule']) && module_exists('date_repeat')) {
222
          // Split the rrule into an RRULE and any additions and exceptions.
223 224
          module_load_include('inc', 'date_api', 'date_api_ical');
          module_load_include('inc', 'date_repeat', 'date_repeat_calc');
225
          list($rrule, $exceptions, $additions) = date_repeat_split_rrule($event['rrule']);
226 227
          
          // Add the RRULE itself. We need to massage the data a bit, since
228 229
          // iCalcreator expects RRULEs to be in a different format than how
          // Date API gives them to us.
230 231 232
          $vevent->setRrule(self::convert_rrule_for_icalcreator($rrule));
          
          // Convert any exceptions to EXDATE properties.
Robert Rollins's avatar
Robert Rollins committed
233 234 235 236
          if (!empty($exceptions)) {
            $exdates = array();
            foreach ($exceptions as $exception) {
              $except = date_ical_date($exception, 'UTC');
237 238
              date_timezone_set($except, $start['tz']);
              $exception_array = $except->toArray();
Robert Rollins's avatar
Robert Rollins committed
239
              $exdates[] = array(
240 241 242
                'year' =>  $exception_array['year'],
                'month' => $exception_array['month'],
                'day' =>   $exception_array['day'],
243 244
                // Use the time information from the start date, since Date
                // doesn't store time info for EXDATEs.
245 246 247 248
                'hour' =>   $start['hour'],
                'min' =>    $start['minute'],
                'second' => $start['second'],
                'tz' =>     $start['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
249 250
              );
            }
251 252 253 254 255 256 257
            // Add each exclusion as a separate EXDATE property.
            // The spec supports putting multiple date values into one EXDATE,
            // but several popular calendar clients (*cough* Apple *cough*)
            // are bugged, and do not recognize multi-value EXDATEs.
            foreach ($exdates as $exdate) {
              $vevent->setExdate(array($exdate));
            }
Robert Rollins's avatar
Robert Rollins committed
258
          }
259 260
          
          // Convert any additions to RDATE properties.
Robert Rollins's avatar
Robert Rollins committed
261
          if (!empty($additions)) {
262
            $rdates = array();
Robert Rollins's avatar
Robert Rollins committed
263 264
            foreach ($additions as $addition) {
              $add = date_ical_date($addition, 'UTC');
265 266
              date_timezone_set($add, $start['tz']);
              $addition_array = $add->toArray();
267
              
268
              $rdate = array(
269 270 271
                'year' =>  $addition_array['year'],
                'month' => $addition_array['month'],
                'day' =>   $addition_array['day'],
272 273
                // Use the time information from the start date, since Date
                // doesn't store time info for RDATEs.
274 275 276 277
                'hour' =>   $start['hour'],
                'min' =>    $start['minute'],
                'second' => $start['second'],
                'tz' =>     $start['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
278
              );
279 280 281 282 283 284 285
              
              // If an end date was was calculated above, use that too.
              // iCalcreator expects RDATEs that have end dates to be
              // specified as array($start_rdate, $end_rdate).
              if (isset($end)) {
                $rdate_with_end = array($rdate);
                $rdate_with_end[] = array(
286 287 288
                  'year' =>  $addition_array['year'],
                  'month' => $addition_array['month'],
                  'day' =>   $addition_array['day'],
Robert Rollins's avatar
Robert Rollins committed
289
                  // Use the time information from the end date.
290 291 292 293
                  'hour' =>   $end['hour'],
                  'min' =>    $end['minute'],
                  'second' => $end['second'],
                  'tz' =>     $end['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
294
                );
295
                $rdate = $rdate_with_end;
Robert Rollins's avatar
Robert Rollins committed
296
              }
297
              
298 299 300 301 302 303 304 305
              $rdates[] = $rdate;
            }
            // Add each addition as a separate RDATE property.
            // The spec supports putting multiple date values into one RDATE,
            // but several popular calendar clients (*cough* Apple *cough*)
            // are bugged, and do not recognize multi-value RDATEs.
            foreach ($rdates as $rdate) {
              $vevent->setRdate(array($rdate));
Robert Rollins's avatar
Robert Rollins committed
306 307 308
            }
          }
        }
309 310
        if (!empty($event['url'])) {
          $vevent->setUrl($event['url'], array('type' => 'URI'));
Robert Rollins's avatar
Robert Rollins committed
311
        }
312
        if (!empty($event['location'])) {
313
          $vevent->setLocation($event['location']);
Robert Rollins's avatar
Robert Rollins committed
314
        }
315
        if (!empty($event['description'])) {
316
          $vevent->setDescription($event['description']);
Robert Rollins's avatar
Robert Rollins committed
317
        }
318 319
        if (!empty($event['last-modified'])) {
          $lm = $event['last-modified']->toArray();
Robert Rollins's avatar
Robert Rollins committed
320 321 322 323 324 325 326 327 328 329
          $vevent->setLastModified(
            $lm['year'],
            $lm['month'],
            $lm['day'],
            $lm['hour'],
            $lm['minute'],
            $lm['second'],
            $lm['timezone']
          );
        }
330 331 332 333 334 335 336 337 338 339 340 341
        if (!empty($event['created'])) {
          $created = $event['created']->toArray();
          $vevent->setCreated(
            $created['year'],
            $created['month'],
            $created['day'],
            $created['hour'],
            $created['minute'],
            $created['second'],
            $created['timezone']
          );
        }
Robert Rollins's avatar
Robert Rollins committed
342
        
343 344
        // Allow other modules to alter the vevent before it's exported.
        drupal_alter('date_ical_export_vevent', $vevent, $this->view, $event);
Robert Rollins's avatar
Robert Rollins committed
345
      }
346
      
347
      // Now add to the calendar all the timezones used by the events.
Robert Rollins's avatar
Robert Rollins committed
348
      foreach ($timezones as $timezone) {
349 350 351
        if (strtoupper($timezone) != 'UTC') {
          iCalUtilityFunctions::createTimezone($vcalendar, $timezone);
        }
Robert Rollins's avatar
Robert Rollins committed
352
      }
353
      
354 355
      // Allow other modules to alter the vcalendar before it's exported.
      drupal_alter('date_ical_export_vcalendar', $vcalendar, $this->view);
356
      
Robert Rollins's avatar
Robert Rollins committed
357
      $output = $vcalendar->createCalendar();
358 359 360 361
      // iCalcreator escapes all commas and semicolons in string values, as the
      // spec demands. However, some calendar clients are buggy and fail to
      // unescape these characters. Users may choose to unescape them here to
      // sidestep those clients' bugs.
362 363 364 365 366 367
      // NOTE: This results in a non-compliant iCal feed, but it seems like a
      // LOT of major clients are bugged this way.
      if ($this->_get_option('unescape_punctuation')) {
        $output = str_replace('\,', ',', $output);
        $output = str_replace('\;', ';', $output);
      }
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
      
      // In order to respect the Exclude DTSTAMP option, we unfortunately have
      // to parse out the DTSTAMP properties after they get rendered. Simply
      // using deleteProperty('DTSTAMP') doesn't work, because iCalcreator
      // considers the DTSTAMP to be essential, and will re-create it when
      // createCalendar() is called.
      if ($this->_get_option('exclude_dtstamp')) {
        $filtered_lines = array();
        foreach (explode("\r\n", $output) as $line) {
          if (strpos($line, 'DTSTAMP') === 0) {
            continue;
          }
          $filtered_lines[] = $line;
        }
        $output = implode("\r\n", $filtered_lines);
      }
Robert Rollins's avatar
Robert Rollins committed
384
    }
Robert Rollins's avatar
Robert Rollins committed
385 386 387
    
    // These steps shouldn't be run when doing a Preview on the View config page.
    if (empty($this->view->live_preview)) {
Robert Rollins's avatar
Robert Rollins committed
388 389
      // Prevent devel module from appending queries to ical export.
      $GLOBALS['devel_shutdown'] = FALSE;
Robert Rollins's avatar
Robert Rollins committed
390 391 392 393 394 395 396 397
      
      drupal_add_http_header('Content-Type', 'text/calendar; charset=utf-8');
      
      // For sites with Clean URLs disabled, the "path" value in the view Display
      // doesn't actually get applied to the URL of the calendar feed. So, we
      // need to manually instruct browsers to download a .ics file.
      if (!variable_get('clean_url', FALSE)) {
        $path_array = explode('/', $this->display->display_options['path']);
398
        $filename = end($path_array);
Robert Rollins's avatar
Robert Rollins committed
399 400
        drupal_add_http_header('Content-Disposition', "attachment; filename=\"$filename\"");
      }
401 402
    }
    
403 404
    // Allow other modules to alter the rendered calendar.
    drupal_alter('date_ical_export_post_render', $output, $this->view);
405
    
Robert Rollins's avatar
Robert Rollins committed
406 407
    return $output;
  }
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  
  /**
   * This function converts an rrule array to the iCalcreator format.
   *
   * iCalcreator expects the BYDAY element to be an array like this:
   * (array) ( [([plus] ordwk / minus ordwk)], "DAY" => weekday )
   *
   * But the way that the Date API gives it to us is like this:
   * (array) ( [([plus] ordwk / minus ordwk)]weekday )
   */
  public static function convert_rrule_for_icalcreator($rrule) {
    $new_rrule = array();
    foreach ($rrule as $key => $value) {
      if (strtoupper($key) == 'DATA') {
        // iCalcreator doesn't expect the 'DATA' key that the Date API gives us.
        continue;
      }
425 426 427 428
      if (strtoupper($key) == 'UNTIL') {
        // iCalcreator expects the 'timestamp' to be array key for UNTIL
        $value['timestamp'] = strtotime($value['datetime']);
      }
429 430 431
      if (strtoupper($key) == 'BYDAY') {
        $new_byday = array();
        foreach ($value as $day) {
432
          // Fortunately, the weekday values are always 2 characters.
433 434 435 436 437 438 439 440 441 442
          $weekday = substr($day, -2);
          $ordwk = substr($day, 0, -2);
          $new_byday[] = array($ordwk, 'DAY' => $weekday);
        }
        $value = $new_byday;
      }
      $new_rrule[$key] = $value;
    }
    return $new_rrule;
  }
Robert Rollins's avatar
Robert Rollins committed
443
}