date_ical.module 13.2 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
/**
Robert Rollins's avatar
Robert Rollins committed
21
 * Exception for when the date field for a row in the ical_fields row plugin 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
}

/**
 * The theme for the ical icon.
80
81
82
83
84
 * 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
85
 */
86
function theme_date_ical_icon($variables) {
87
88
89
  if (empty($variables['tooltip'])) {
    $variables['tooltip'] = t('Add this event to my calendar');
  }
Robert Rollins's avatar
Robert Rollins committed
90
91
  $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
92
  if ($image = theme('image', $variables)) {
Robert Rollins's avatar
Robert Rollins committed
93
94
95
96
    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
97
98
99
100
  }
}

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

/**
 * Implements hook_entity_info_alter().
 *
Robert Rollins's avatar
Robert Rollins committed
133
 * Add an 'iCal' view mode for entities, which will be used by the Views style 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/**
 * Implements hook_feeds_processor_targets_alter().
 *
 * Adds the "Field Name: Repeat Rule" target to Date Repeat Fields.
 *
 * @see FeedsNodeProcessor::getMappingTargets().
 */
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
 * 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.
207
208
 *
 * @param $text
209
 *   The text to be sanitized.
210
 */
211
function date_ical_sanitize_text($text = '') {
212
  // Use Drupal's built-in HTML to Text converter, which does a mostly adequate
213
  // job of making the text iCal-compliant.
214
  $text = trim(drupal_html_to_text($text));
215
216
  // Replace instances of more than one space with exactly one space. This
  // cleans up the whitespace mess that gets left behind by drupal_html_to_text().
217
  $text = preg_replace("/  +/", " ", $text);
218
  // The call to drupal_html_to_text() above converted <p> to \n\n, and also
219
220
221
222
223
  // 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);
224
225
226
  return $text;
}

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

258
259
260
261
262
263
/**
 *  Identify all potential fields that could populate the optional LOCATION component of iCal output.
 */
function date_ical_get_location_fields($base = 'node', $reset = FALSE) {
  static $fields = array();
  $empty = array('name' => array(), 'alias' => array());
264
  
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  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;
}

/**
 *  Identify all potential LOCATION fields.
Robert Rollins's avatar
Robert Rollins committed
280
281
 *  This is a cut down version of _date_views_fields() from date_views_fields.inc
 *  in date_views module.
282
283
284
285
 *
 *  @return
 *    array with fieldname, type, and table.
 *  @see
Robert Rollins's avatar
Robert Rollins committed
286
287
 *    date_views_date_views_fields(), which implements hook_date_views_fields()
 *    for the core date fields.
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
 */
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);
310
    if (!$info || !in_array($info['type'], array('text', 'text_long', 'text_with_summary', 'node_reference', 'addressfield'))) {
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
      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;
}
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386


/**
 *  Identify all potential fields that could populate the custom SUMMARY field
 */
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;
}

/**
 *  Identify all potential 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.
 *  @see
 *    date_views_date_views_fields(), which implements hook_date_views_fields()
 *    for the core date fields.
 */
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);
387
    if (!$info || !in_array($info['type'], array('text', 'text_long', 'text_with_summary', 'node_reference', 'taxonomy_term_reference'))) {
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
      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;
}