date_ical_plugin_style_ical_feed.inc 17.6 KB
Newer Older
Robert Rollins's avatar
Robert Rollins committed
1 2 3 4 5 6 7
<?php
/**
 * @file
 * Views style plugin for the Date iCal module.
 */

/**
8
 * Defines a Views style plugin that renders iCal feeds.
Robert Rollins's avatar
Robert Rollins committed
9 10 11
 */
class date_ical_plugin_style_ical_feed extends views_plugin_style {
  
12 13 14
  /**
   * Internal helper function.
   */
15
  protected function _get_option($option_name) {
Robert Rollins's avatar
Robert Rollins committed
16
    return isset($this->options[$option_name]) ? $this->options[$option_name] : '';
Robert Rollins's avatar
Robert Rollins committed
17 18
  }
  
19 20 21 22
  /**
   * Sets up the iCal feed icon on calendar pages.
   */
  public function attach_to($display_id, $path, $title) {
Robert Rollins's avatar
Robert Rollins committed
23 24 25 26 27 28
    $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
29
    
Robert Rollins's avatar
Robert Rollins committed
30
    $url = url($this->view->get_url(NULL, $path), $url_options);
31 32
    // If the user didn't disable the option, change the scheme to webcal://
    // so calendar clients can automatically subscribe via the iCal link.
Robert Rollins's avatar
Robert Rollins committed
33
    if (!$this->_get_option('disable_webcal')) {
34
      $url = str_replace(array('http://', 'https://'), 'webcal://', $url);
Robert Rollins's avatar
Robert Rollins committed
35 36
    }
    
37
    // Render the feed icon and header tag (except during a View Preview).
Robert Rollins's avatar
Robert Rollins committed
38 39
    if (empty($this->view->live_preview)) {
      $tooltip = t('Add to My Calendar');
40
      if (!isset($this->view->feed_icon)) {
41 42 43
        // In PHP 5.5, you're not allowed to concatinate onto an unset
        // property. But we need to do a concat, because there may be
        // other attachments.
44 45
        $this->view->feed_icon = '';
      }
46 47 48 49 50 51
      $variables = array(
        'url' => check_url($url),
        'tooltip' => $tooltip,
        'view' => $this->view,
      );
      $this->view->feed_icon .= theme('date_ical_icon', $variables);
Robert Rollins's avatar
Robert Rollins committed
52 53
      drupal_add_html_head_link(array(
        'rel' => 'alternate',
Robert Rollins's avatar
Robert Rollins committed
54 55
        'type' => 'text/calendar',
        'title' => $tooltip,
Robert Rollins's avatar
Robert Rollins committed
56 57 58 59 60
        'href' => $url
      ));
    }
  }
  
61 62 63 64 65 66
  /**
   * Set up the options for the style plugin.
   */
  public function option_definition() {
    $false_bool = array('default' => FALSE, 'bool' => TRUE);
    
67 68
    $options = parent::option_definition();
    $options['cal_name'] = array('default' => array());
69 70 71 72
    $options['no_calname'] = $false_bool;
    $options['disable_webcal'] = $false_bool;
    $options['exclude_dtstamp'] = $false_bool;
    $options['unescape_punctuation'] = $false_bool;
73 74 75
    return $options;
  }
  
76 77 78 79
  /**
   * Build the form for setting the style plugin's options.
   */
  public function options_form(&$form, &$form_state) {
Robert Rollins's avatar
Robert Rollins committed
80 81 82 83 84
    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
85
      '#default_value' => $this->_get_option('cal_name'),
86 87
      '#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
88
    );
Robert Rollins's avatar
Robert Rollins committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    $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."),
    );
105 106 107 108 109 110 111 112 113
    $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."),
    );
114 115 116 117 118
    $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).
119
        However, many calendar clients are bugged to not unescape these characters, leaving the backslashes littered throughout your events.
120 121
        Enable this option to have Date iCal unescape these characters before it exports the iCal feed.'),
    );
Robert Rollins's avatar
Robert Rollins committed
122 123
  }
  
124 125 126 127
  /**
   * Render the event arrays returned by the row plugin into a VCALENDAR.
   */
  public function render() {
128 129
    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);
130
      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
131
    }
132
    if ($this->row_plugin->plugin_name == 'date_ical_fields' && empty($this->row_plugin->options['date_field'])) {
133 134 135
      // Because the Date field is required by the form, this error state will
      // rarely occur. But I ran across it during testing, and the error that
      // resulted was totally non-sensical, so I'm adding this just in case.
136
      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'.");
137 138
    }
    $events = array();
Robert Rollins's avatar
Robert Rollins committed
139 140
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
141
      $row->index = $row_index;
142
      try {
143
        $events[] = $this->row_plugin->render($row);
144 145 146 147 148
      }
      catch (Exception $e) {
        debug($e->getMessage(), NULL, TRUE);
        return $e->getMessage();
      }
Robert Rollins's avatar
Robert Rollins committed
149 150
    }
    unset($this->view->row_index);
151
    
152
    // Try to load the iCalcreator library.
Robert Rollins's avatar
Robert Rollins committed
153
    $library = libraries_load('iCalcreator');
154 155 156 157 158
    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
159
      // Create a vcalendar object using the iCalcreator library.
160
      $config = array('unique_id' => 'Date iCal v' . DATE_ICAL_VERSION);
Robert Rollins's avatar
Robert Rollins committed
161 162 163
      $vcalendar = new vcalendar($config);
      $vcalendar->setMethod('PUBLISH');
      
164 165 166 167 168 169 170 171 172
      // 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');
          }
173
        }
174 175
        if (!empty($cal_name)) {
          $vcalendar->setProperty('X-WR-CALNAME', $cal_name, array('VALUE' => 'TEXT'));
176
        }
Robert Rollins's avatar
Robert Rollins committed
177
      }
178
      
Robert Rollins's avatar
Robert Rollins committed
179
      // Now add the VEVENTs.
Robert Rollins's avatar
Robert Rollins committed
180
      $timezones = array();
181 182
      foreach ($events as $event) {
        if (empty($event)) {
183
          // The row plugin returned NULL for this row, which can happen due to
184 185
          // either various error conditions, or because an RRULE is involved.
          // When this happens, just skip it.
186 187 188
          continue;
        }
        
Robert Rollins's avatar
Robert Rollins committed
189
        $vevent = $vcalendar->newComponent('vevent');
190 191 192
        $vevent->setUid($event['uid']);
        $vevent->setSummary($event['summary']);
        
Robert Rollins's avatar
Robert Rollins committed
193
        // Get the start date as an array.
194
        $start = $event['start']->toArray();
195 196
        $start_timezone = $event['start']->getTimezone()->getName();
        $timezones[$start_timezone] = $start_timezone;
197
        
198
        if ($event['all_day']) {
199
          // All Day events need to be DATEs, rather than DATE-TIMEs.
200 201 202 203 204 205 206 207 208 209 210
          $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'],
211
            $start_timezone
212
          );
213
        }
214
        
215
        // Add the Timezone info to the start date, for use later.
216
        $start['tz'] = $event['start']->getTimezone();
217
        
Robert Rollins's avatar
Robert Rollins committed
218
        // Only add the end date if there is one.
219 220
        if (!empty($event['end'])) {
          $end = $event['end']->toArray();
221 222
          $end_timezone = $event['end']->getTimezone()->getName();
          $timezones[$end_timezone] = $end_timezone;
223
          
224
          if ($event['all_day']) {
225 226 227 228 229 230 231 232 233 234 235
            $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'],
236
              $end_timezone
237
            );
238
          }
239
          $end['tz'] = $event['end']->getTimezone();
Robert Rollins's avatar
Robert Rollins committed
240
        }
241
        
Robert Rollins's avatar
Robert Rollins committed
242
        // Handle repeating dates from the date_repeat module.
243
        if (!empty($event['rrule']) && module_exists('date_repeat')) {
244
          // Split the rrule into an RRULE and any additions and exceptions.
245 246
          module_load_include('inc', 'date_api', 'date_api_ical');
          module_load_include('inc', 'date_repeat', 'date_repeat_calc');
247
          list($rrule, $exceptions, $additions) = date_repeat_split_rrule($event['rrule']);
248 249
          
          // Add the RRULE itself. We need to massage the data a bit, since
250 251
          // iCalcreator expects RRULEs to be in a different format than how
          // Date API gives them to us.
252
          $vevent->setRrule(_date_ical_convert_rrule_for_icalcreator($rrule));
253 254
          
          // Convert any exceptions to EXDATE properties.
Robert Rollins's avatar
Robert Rollins committed
255 256 257 258
          if (!empty($exceptions)) {
            $exdates = array();
            foreach ($exceptions as $exception) {
              $except = date_ical_date($exception, 'UTC');
259 260
              date_timezone_set($except, $start['tz']);
              $exception_array = $except->toArray();
Robert Rollins's avatar
Robert Rollins committed
261
              $exdates[] = array(
262 263 264
                'year' =>  $exception_array['year'],
                'month' => $exception_array['month'],
                'day' =>   $exception_array['day'],
265 266
                // Use the time information from the start date, since Date
                // doesn't store time info for EXDATEs.
267 268 269 270
                'hour' =>   $start['hour'],
                'min' =>    $start['minute'],
                'second' => $start['second'],
                'tz' =>     $start['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
271 272
              );
            }
273 274 275 276 277 278 279
            // 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
280
          }
281 282
          
          // Convert any additions to RDATE properties.
Robert Rollins's avatar
Robert Rollins committed
283
          if (!empty($additions)) {
284
            $rdates = array();
Robert Rollins's avatar
Robert Rollins committed
285 286
            foreach ($additions as $addition) {
              $add = date_ical_date($addition, 'UTC');
287 288
              date_timezone_set($add, $start['tz']);
              $addition_array = $add->toArray();
289
              
290
              $rdate = array(
291 292 293
                'year' =>  $addition_array['year'],
                'month' => $addition_array['month'],
                'day' =>   $addition_array['day'],
294 295
                // Use the time information from the start date, since Date
                // doesn't store time info for RDATEs.
296 297 298 299
                'hour' =>   $start['hour'],
                'min' =>    $start['minute'],
                'second' => $start['second'],
                'tz' =>     $start['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
300
              );
301 302 303 304 305 306 307
              
              // 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(
308 309 310
                  'year' =>  $addition_array['year'],
                  'month' => $addition_array['month'],
                  'day' =>   $addition_array['day'],
Robert Rollins's avatar
Robert Rollins committed
311
                  // Use the time information from the end date.
312 313 314 315
                  'hour' =>   $end['hour'],
                  'min' =>    $end['minute'],
                  'second' => $end['second'],
                  'tz' =>     $end['tz']->getName(),
Robert Rollins's avatar
Robert Rollins committed
316
                );
317
                $rdate = $rdate_with_end;
Robert Rollins's avatar
Robert Rollins committed
318
              }
319
              
320 321 322 323 324 325 326 327
              $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
328 329 330
            }
          }
        }
331 332
        if (!empty($event['url'])) {
          $vevent->setUrl($event['url'], array('type' => 'URI'));
Robert Rollins's avatar
Robert Rollins committed
333
        }
334
        if (!empty($event['location'])) {
335
          $vevent->setLocation($event['location']);
Robert Rollins's avatar
Robert Rollins committed
336
        }
337
        if (!empty($event['description'])) {
338
          $vevent->setDescription($event['description']);
Robert Rollins's avatar
Robert Rollins committed
339
        }
340 341
        if (!empty($event['last-modified'])) {
          $lm = $event['last-modified']->toArray();
Robert Rollins's avatar
Robert Rollins committed
342 343 344 345 346 347 348 349 350 351
          $vevent->setLastModified(
            $lm['year'],
            $lm['month'],
            $lm['day'],
            $lm['hour'],
            $lm['minute'],
            $lm['second'],
            $lm['timezone']
          );
        }
352 353 354 355 356 357 358 359 360 361 362 363
        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
364
        
365 366
        // 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
367
      }
368
      
369
      // Now add to the calendar all the timezones used by the events.
Robert Rollins's avatar
Robert Rollins committed
370
      foreach ($timezones as $timezone) {
371 372 373
        if (strtoupper($timezone) != 'UTC') {
          iCalUtilityFunctions::createTimezone($vcalendar, $timezone);
        }
Robert Rollins's avatar
Robert Rollins committed
374
      }
375
      
376 377
      // Allow other modules to alter the vcalendar before it's exported.
      drupal_alter('date_ical_export_vcalendar', $vcalendar, $this->view);
378
      
Robert Rollins's avatar
Robert Rollins committed
379
      $output = $vcalendar->createCalendar();
380 381 382 383
      // 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.
384 385 386 387 388 389
      // 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);
      }
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
      
      // 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
406
    }
Robert Rollins's avatar
Robert Rollins committed
407
    
408
    // These steps shouldn't be run when during Preview on the View page.
Robert Rollins's avatar
Robert Rollins committed
409
    if (empty($this->view->live_preview)) {
Robert Rollins's avatar
Robert Rollins committed
410 411
      // Prevent devel module from appending queries to ical export.
      $GLOBALS['devel_shutdown'] = FALSE;
Robert Rollins's avatar
Robert Rollins committed
412 413 414
      
      drupal_add_http_header('Content-Type', 'text/calendar; charset=utf-8');
      
415 416 417 418
      // For sites with Clean URLs disabled, the Display's "path" value ends
      // up only in the query args, meaning the filename won't be set properly
      // when users download the feed. So we need to manually instruct browsers
      // to download a .ics file.
Robert Rollins's avatar
Robert Rollins committed
419 420
      if (!variable_get('clean_url', FALSE)) {
        $path_array = explode('/', $this->display->display_options['path']);
421
        $filename = end($path_array);
Robert Rollins's avatar
Robert Rollins committed
422 423
        drupal_add_http_header('Content-Disposition', "attachment; filename=\"$filename\"");
      }
424 425
    }
    
426 427
    // Allow other modules to alter the rendered calendar.
    drupal_alter('date_ical_export_post_render', $output, $this->view);
428
    
Robert Rollins's avatar
Robert Rollins committed
429 430 431
    return $output;
  }
}