date_ical.module 14.4 KB
Newer Older
Karen Stevenson's avatar
Karen Stevenson committed
1
<?php
2

Karen Stevenson's avatar
Karen Stevenson committed
3
4
/**
 * @file
Robert Rollins's avatar
Robert Rollins committed
5
 * Adds ical functionality to Views, and an iCal parser to Feeds.
Karen Stevenson's avatar
Karen Stevenson committed
6
7
 */

8
9
/**
 * The version number of the current release. This is inserted into the PRODID
Robert Rollins's avatar
Robert Rollins committed
10
11
 * value of the iCal feeds created by Date iCal. It's primarily used for
 * debugging.
12
 */
13
define('DATE_ICAL_VERSION', '3.0-dev');
14

15
/**
Robert Rollins's avatar
Robert Rollins committed
16
 * Exception class for generic exceptions thrown by this module.
17
 */
Robert Rollins's avatar
Robert Rollins committed
18
class DateIcalException extends Exception {}
19

20
/**
21
 * Exception used by iCal Fields for when a date field is blank.
22
 */
Robert Rollins's avatar
Robert Rollins committed
23
class BlankDateFieldException extends DateIcalException {}
24
25

/**
Robert Rollins's avatar
Robert Rollins committed
26
 * Exception thrown when the Feeds parser plugin fails.
27
28
29
30
31
32
33
34
 */
class DateIcalParseException extends DateIcalException {}

/**
 * Implements hook_hook_info().
 */
function date_ical_hook_info() {
  // TODO: Finish this.
Robert Rollins's avatar
Robert Rollins committed
35
  // Use two "groups": date_ical_import and date_ical_export.
36
37
}

Karen Stevenson's avatar
Karen Stevenson committed
38
/**
39
 * Implements hook_views_api().
Karen Stevenson's avatar
Karen Stevenson committed
40
41
42
43
 */
function date_ical_views_api() {
  return array(
    'api' => 3,
Robert Rollins's avatar
Robert Rollins committed
44
    'path' => drupal_get_path('module', 'date_ical') . '/includes',
Karen Stevenson's avatar
Karen Stevenson committed
45
46
47
  );
}

Robert Rollins's avatar
Robert Rollins committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
 * Implements hook_feeds_plugins().
 */
function date_ical_feeds_plugins() {
  $path = drupal_get_path('module', 'date_ical') . '/includes';
  $info = array();
  $info['DateiCalFeedsParser'] = array(
    'name' => 'iCal parser',
    'description' => t('Parse iCal feeds.'),
    'handler' => array(
      'parent' => 'FeedsParser',
      'class' => 'DateiCalFeedsParser',
      'file' => 'DateiCalFeedsParser.inc',
      'path' => $path,
    ),
  );
  return $info;
}

Karen Stevenson's avatar
Karen Stevenson committed
67
68
69
/**
 * Implements hook_theme().
 */
70
function date_ical_theme($existing, $type, $theme, $path) {
Karen Stevenson's avatar
Karen Stevenson committed
71
72
  return array(
    'date_ical_icon' => array(
Robert Rollins's avatar
Robert Rollins committed
73
      'variables' => array('url' => NULL, 'tooltip' => NULL),
74
75
    ),
  );
Karen Stevenson's avatar
Karen Stevenson committed
76
77
78
}

/**
79
80
 * Theme function for the ical icon used by attached iCal feed.
 *
81
82
83
84
85
 * Available variables are:
 * $variables['tooltip'] - The tooltip to be used for the ican feed icon.
 * $variables['url'] - The url to the actual iCal feed.
 * $variables['view'] - The view object from which the iCal feed is being
 *   built (useful for contextual information).
Karen Stevenson's avatar
Karen Stevenson committed
86
 */
87
function theme_date_ical_icon($variables) {
88
89
90
  if (empty($variables['tooltip'])) {
    $variables['tooltip'] = t('Add this event to my calendar');
  }
Robert Rollins's avatar
Robert Rollins committed
91
92
  $variables['path'] = drupal_get_path('module', 'date_ical') . '/images/ical-feed-icon-34x14.png';
  $variables['alt'] = $variables['title'] = $variables['tooltip'];
Karen Stevenson's avatar
Karen Stevenson committed
93
  if ($image = theme('image', $variables)) {
Robert Rollins's avatar
Robert Rollins committed
94
95
96
97
    return "<a href='{$variables['url']}' class='ical-icon'>$image</a>";
  }
  else {
    return "<a href='{$variables['url']}' class='ical-icon'>{$variables['tooltip']}</a>";
Karen Stevenson's avatar
Karen Stevenson committed
98
99
100
101
  }
}

/**
102
 * Implements hook_preprocess_HOOK().
103
 *
104
105
106
 * Hides the page elements which don't belong in an iCal DESCRIPTION element.
 * The display of the body and other fields is controlled by the Manage
 * Display settings for the nodes' iCal view mode.
Karen Stevenson's avatar
Karen Stevenson committed
107
 */
108
109
function date_ical_preprocess_node(&$variables) {
  if (isset($variables['view_mode']) && $variables['view_mode'] == 'ical') {
110
111
    // Trick the default node template into not displaying the page title, by
    // telling it that this *is* a page.
112
    $variables['page'] = TRUE;
Karen Stevenson's avatar
Karen Stevenson committed
113
114
    $variables['title_prefix'] = '';
    $variables['title_suffix'] = '';
115
    
Robert Rollins's avatar
Robert Rollins committed
116
    // We don't want to see the author information in our feed.
Karen Stevenson's avatar
Karen Stevenson committed
117
    $variables['display_submitted'] = FALSE;
118
    
Robert Rollins's avatar
Robert Rollins committed
119
    // Comments and links don't belong in an iCal feed.
120
121
122
123
124
125
    if (isset($variables['content']['comments'])) {
      unset($variables['content']['comments']);
    }
    if (isset($variables['content']['links'])) {
      unset($variables['content']['links']);
    }
Karen Stevenson's avatar
Karen Stevenson committed
126
127
128
129
130
131
  }
}

/**
 * Implements hook_entity_info_alter().
 *
132
133
 * Adds an 'iCal' view mode for entities, which is used by the iCal Entity
 * View plugin.
Karen Stevenson's avatar
Karen Stevenson committed
134
 */
135
136
function date_ical_entity_info_alter(&$entity_info) {
  foreach ($entity_info as $entity_type => $info) {
Robert Rollins's avatar
Robert Rollins committed
137
138
139
    if (!isset($entity_info[$entity_type]['view modes'])) {
      $entity_info[$entity_type]['view modes'] = array();
    }
140
    $entity_info[$entity_type]['view modes'] += array(
Karen Stevenson's avatar
Karen Stevenson committed
141
142
      'ical' => array(
        'label' => t('iCal'),
143
144
        // Set the iCal view mode to default to same settings as the "default"
        // view mode, so it won't pollute Features.
145
        'custom settings' => FALSE,
Karen Stevenson's avatar
Karen Stevenson committed
146
147
148
149
150
      ),
    );
  }
}

Robert Rollins's avatar
Robert Rollins committed
151
152
153
154
155
156
/**
 * Implements hook_libraries_info().
 */
function date_ical_libraries_info() {
  $libraries['iCalcreator'] = array(
    'name' => 'iCalcreator',
157
158
    'vendor url' => 'http://github.com/iCalcreator/iCalcreator',
    'download url' => 'http://github.com/iCalcreator/iCalcreator',
Robert Rollins's avatar
Robert Rollins committed
159
160
161
162
163
164
165
166
167
    'version arguments' => array(
      'file' => 'iCalcreator.class.php',
      'pattern' => "/define\( 'ICALCREATOR_VERSION', 'iCalcreator ([\d\.]+)' \);/",
      'lines' => 100,
    ),
    'files' => array(
      'php' => array('iCalcreator.class.php'),
    ),
  );
168
  
Robert Rollins's avatar
Robert Rollins committed
169
170
171
172
  return $libraries;
}

/**
173
 * Implements hook_ctools_plugin_api().
Robert Rollins's avatar
Robert Rollins committed
174
175
176
177
178
179
180
 */
function date_ical_ctools_plugin_api($owner, $api) {
  if ($owner == 'feeds' && $api == 'plugins') {
    return array('version' => 2);
  }
}

181
182
183
/**
 * Implements hook_feeds_processor_targets_alter().
 *
184
 * Adds the "Field Name: Repeat Rule" target to Date Repeat fields.
185
 *
186
 * @see FeedsNodeProcessor::getMappingTargets()
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
 */
function date_ical_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
    $info = field_info_field($name);
    if (in_array($info['type'], array('date', 'datestamp', 'datetime')) && isset($info['settings']['repeat']) && $info['settings']['repeat']) {
      $targets[$name . ':rrule'] = array(
        'name' => t('@name: Repeat Rule', array('@name' => $instance['label'])),
        'callback' => 'date_ical_feeds_set_rrule',
        'description' => t('The repeat rule for the @name field.', array('@name' => $instance['label'])),
        'real_target' => $name,
      );
    }
  }
}

202
203
/**
 * Reformats the provided text to be compliant with the iCal spec.
204
 *
205
206
207
 * If the text contains HTML tags, those tags will be stripped (with <p> tags
 * converted to "\n\n" and link tags converted to footnotes), and uneeded
 * whitespace will be cleaned up.
208
209
 *
 * @param $text
210
 *   The text to be sanitized.
211
 */
212
function date_ical_sanitize_text($text = '') {
213
214
  // Use Drupal's built-in HTML to Text converter, which does a mostly
  // adequate job of making the text iCal-compliant.
215
  $text = trim(drupal_html_to_text($text));
216
  // Replace instances of more than one space with exactly one space. This
217
  // cleans up the whitespace mess that drupal_html_to_text() leaves behind.
218
  $text = preg_replace("/  +/", " ", $text);
219
  // The call to drupal_html_to_text() above converted <p> to \n\n, and also
220
221
222
223
224
  // shoved a \n into the string every 80 characters. We don't want those
  // single \n's lying around, because iCalcreator will properly "fold" long
  // text fields for us. So, we need to remove all instances of \n which
  // are neither immediately preceeded, nor followed, by another \n.
  $text = preg_replace("/(?<!\n)\n(?!\n)/", " ", $text);
225
226
227
  return $text;
}

228
229
230
/**
 * Callback specified in date_ical_feeds_processor_targets_alter() for RRULEs.
 *
231
 * @param object $source
232
 *   The FeedsSource object.
233
 * @param object $entity
234
 *   The node that's being built from the iCal element that's being parsed.
235
 * @param string $target
236
237
 *   The machine name of the field into which this RRULE shall be parsed,
 *   with ":rrule" appended to the end.
238
 * @param string $feed_element
239
240
241
 *   The RRULE string (with optional EXDATEs and RDATEs separated by \n).
 */
function date_ical_feeds_set_rrule($source, $entity, $target, $feed_element) {
242
243
244
245
  if (empty($feed_element)) {
    // Make sure that VEVENTs which have no RRULE aren't given repeating dates.
    return;
  }
246
247
248
249
250
  // Add the RRULE value to the field in $entity.
  list($field_name, $trash) = explode(':', $target, 2);
  module_load_include('inc', 'date_api', 'date_api_ical');
  $info = field_info_field($field_name);
  foreach ($entity->{$field_name} as $lang => $field_array) {
251
252
    // Add the multiple date values that Date Repeat Field uses to represent
    // recurring dates.
Robert Rollins's avatar
Robert Rollins committed
253
    $values = date_repeat_build_dates($feed_element, NULL, $info, $field_array[0]);
254
255
256
257
258
259
    foreach ($values as $key => $value) {
      $entity->{$field_name}[$lang][$key] = $value;
    }
  }
}

260
/**
261
 * Identify all potential fields which could be used as an iCal LOCATION.
262
263
264
265
 */
function date_ical_get_location_fields($base = 'node', $reset = FALSE) {
  static $fields = array();
  $empty = array('name' => array(), 'alias' => array());
266
  
267
268
269
270
271
272
273
274
275
276
277
278
279
280
  if (empty($fields[$base]) || $reset) {
    $cid = 'date_ical_location_fields_' . $base;
    if (!$reset && $cached = cache_get($cid, 'cache_views')) {
      $fields[$base] = $cached->data;
    }
    else {
      $fields[$base] = _date_ical_get_location_fields($base);
    }
  }
  // Make sure that empty values will be arrays in the expected format.
  return !empty($fields) && !empty($fields[$base]) ? $fields[$base] : $empty;
}

/**
281
282
283
284
285
286
287
 * Internal helper function for date_ical_get_location_fields().
 *
 * This is a cut down version of _date_views_fields() from
 * date_views_fields.inc in date_views module.
 *
 * @return
 *   array with fieldname, type, and table.
288
 *
289
 * @see date_views_date_views_fields()
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
 */
function _date_ical_get_location_fields($base = 'node') {
  // Make sure $base is never empty.
  if (empty($base)) {
    $base = 'node';
  }
  
  $cid = 'date_ical_location_fields_' . $base;
  cache_clear_all($cid, 'cache_views');
  
  // Iterate over all the fields that Views knows about.
  $all_fields = date_views_views_fetch_fields($base, 'field');
  $fields = array();
  foreach ($all_fields as $alias => $val) {
    $name = $alias;
    $tmp = explode('.', $name);
    $field_name = $tmp[1];
    $table_name = $tmp[0];
    
    // Skip unsupported field types and fields that weren't defined through
    // the Field module.
    $info = field_info_field($field_name);
312
313
314
315
316
317
318
319
    $supported_location_fields = array(
      'text',
      'text_long',
      'text_with_summary',
      'node_reference',
      'addressfield',
    );
    if (!$info || !in_array($info['type'], $supported_location_fields)) {
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
      continue;
    }
    
    // Build an array of the field info that we'll need.
    $alias = str_replace('.', '_', $alias);
    $fields['name'][$name] = array(
      'label' => "{$val['group']}: {$val['title']} ($field_name)",
      'table_name' => $table_name,
      'field_name' => $field_name,
      'type' => $info['type'],
    );
    
    // These are here only to make this $field array conform to the same format
    // as the one returned by _date_views_fields(). They're probably not needed,
    // but I thought that consistency would be a good idea.
    $fields['name'][$name]['real_field_name'] = $field_name;
    $fields['alias'][$alias] = $fields['name'][$name];
  }
  
  cache_set($cid, $fields, 'cache_views');
  return $fields;
}
342
343
344


/**
345
 * Identify all potential fields which could be used as an iCal SUMMARY.
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
 */
function date_ical_get_summary_fields($base = 'node', $reset = FALSE) {
  static $fields = array();
  $empty = array('name' => array(), 'alias' => array());

  if (empty($fields[$base]) || $reset) {
    $cid = 'date_ical_summary_fields_' . $base;
    if (!$reset && $cached = cache_get($cid, 'cache_views')) {
      $fields[$base] = $cached->data;
    }
    else {
      $fields[$base] = _date_ical_get_summary_fields($base);
    }
  }
  // Make sure that empty values will be arrays in the expected format.
  return !empty($fields) && !empty($fields[$base]) ? $fields[$base] : $empty;
}

/**
365
366
367
368
369
370
371
 * Internal helper function for date_ical_get_summary_fields().
 *
 * This is a cut down version of _date_views_fields() from
 * date_views_fields.inc in date_views module.
 *
 * @return
 *   Array with fieldname, type, and table.
372
 *
373
 *  @see date_views_date_views_fields()
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
 */
function _date_ical_get_summary_fields($base = 'node') {
  // Make sure $base is never empty.
  if (empty($base)) {
    $base = 'node';
  }

  $cid = 'date_ical_summary_fields_' . $base;
  cache_clear_all($cid, 'cache_views');

  // Iterate over all the fields that Views knows about.
  $all_fields = date_views_views_fetch_fields($base, 'field');
  $fields = array();
  foreach ($all_fields as $alias => $val) {
    $name = $alias;
    $tmp = explode('.', $name);
    $field_name = $tmp[1];
    $table_name = $tmp[0];

    // Skip unsupported field types and fields that weren't defined through
    // the Field module.
    $info = field_info_field($field_name);
396
397
398
399
400
401
402
403
    $supported_summary_fields = array(
      'text',
      'text_long',
      'text_with_summary',
      'node_reference',
      'taxonomy_term_reference',
    );
    if (!$info || !in_array($info['type'], $supported_summary_fields)) {
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
      continue;
    }

    // Build an array of the field info that we'll need.
    $alias = str_replace('.', '_', $alias);
    $fields['name'][$name] = array(
      'label' => "{$val['group']}: {$val['title']} ($field_name)",
      'table_name' => $table_name,
      'field_name' => $field_name,
      'type' => $info['type'],
    );

    // These are here only to make this $field array conform to the same format
    // as the one returned by _date_views_fields(). They're probably not needed,
    // but I thought that consistency would be a good idea.
    $fields['name'][$name]['real_field_name'] = $field_name;
    $fields['alias'][$alias] = $fields['name'][$name];
  }

  cache_set($cid, $fields, 'cache_views');
  return $fields;
}
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

/**
 * Convert 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 )
 */
function _date_ical_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;
    }
    if (strtoupper($key) == 'UNTIL') {
      // iCalcreator expects the 'timestamp' to be array key for UNTIL
      $value['timestamp'] = strtotime($value['datetime']);
    }
    if (strtoupper($key) == 'BYDAY') {
      $new_byday = array();
      foreach ($value as $day) {
        // Fortunately, the weekday values are always 2 characters.
        $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;
}