uw_ct_event.module 68.2 KB
Newer Older
ccarigna's avatar
ccarigna committed
1
<?php
Liam Morland's avatar
Liam Morland committed
2

ccarigna's avatar
ccarigna committed
3
4
5
6
7
/**
 * @file
 * Code for the Event feature.
 */

Liam Morland's avatar
Liam Morland committed
8
include_once 'uw_ct_event.features.inc';
9

10
11
12
13
14
/**
 * Implements hook_preprocess_node().
 */
function uw_ct_event_preprocess_node(&$vars) {

15
  // Load in the node.
16
17
  $node = node_load($vars['nid']);

18
19
  // Load the wrappers around the node so that
  // we don't have to worry about the language.
20
  $wrapper = entity_metadata_wrapper('node', $vars['nid']);
21
22

  // Ensure that we have a node type.
23
  if ($wrapper->type->value()) {
24

25
26
27
28
29
30
31
32
33
34
35
    // Ensure that we are on an event and using the teaser.
    if ($wrapper->type->value() == "uw_event" && $vars['view_mode'] == 'teaser') {

      // Ensure that we are going to use the teaser template.
      $vars['theme_hook_suggestions'][] = 'node__uw_event__teaser';

      // Get the body from the entity wrapper.
      $body = $wrapper->body->value();

      // If there is a summary remove the images from it and set variable.
      if ($body['summary'] !== '') {
Liam Morland's avatar
Liam Morland committed
36
        $vars['content']['body_to_display'] = _uw_ct_event_remove_images_from_text(isset($body['safe_summary']) ? $body['safe_summary'] : NULL);
37
      }
38
39
      // If there is a value in the body remove
      // the images from it and set variable.
Liam Morland's avatar
Liam Morland committed
40
      elseif ($body['value'] !== '') {
41
42
43
44
45
46
47
48
49
50
51
        // Get the body field from the node.
        $body_data = field_get_items('node', $node, 'body');

        // Get the teaser output from the body.
        $teaser = field_view_value('node', $node, 'body', $body_data[0], 'teaser');

        // Render the teaser.
        $teaser = render($teaser);

        // Set the teaser but first correct and html.
        $vars['content']['body_to_display'] = _filter_htmlcorrector(_uw_ct_event_remove_images_from_text($teaser));
52
53
54
55
56
      }
      // Ensure that we get something in the variable.
      else {
        $vars['content']['body_to_display'] = '';
      }
57
      // The field name that we many be changing.
Liam Morland's avatar
Liam Morland committed
58
      $field_name = 'field_event_date';
59
      // If the field_event_date is present, process it.
60
      if ($wrapper->field_event_date->value() !== NULL) {
61

62
63
        // If there is more than 1 or 0 dates,
        // substitute in the first value with the view results value
64
        // and set the output.
65
66
67
68
        // This has to be done for evetns that re-occuring
        // to ensure that the right date is displayed.  If there
        // is only 1 event date the field_event_date will be rendered,
        // otherwise this new output.
69
        if (count($wrapper->field_event_date->value()) > 1 || count($wrapper->field_event_date->value()) == 0) {
70
71

          // Display settings for the field_event_date.
72
          $display = array('settings' => array('format_type' => 'hours_change_format'), 'label' => 'hidden');
73

74
75
          // Get the entity wrapper for the individual event node.
          // This is required to get the timezone.
Liam Morland's avatar
Liam Morland committed
76
          $event_wrapper = isset($vars['view']) ? entity_metadata_wrapper('node', $vars['view']->result[$vars['id'] - 1]->nid) : NULL;
77

78
79
          // Replace the two date values from the view results
          // into the 0th element of field_event_date.
80
          // Also, add in the timezone.
81
          $event_date = array(
Liam Morland's avatar
Liam Morland committed
82
83
            'value' => isset($vars['view']) ? $vars['view']->result[$vars['id'] - 1]->field_data_field_event_date_field_event_date_value : NULL,
            'value2' => isset($vars['view']) ? $vars['view']->result[$vars['id'] - 1]->field_data_field_event_date_field_event_date_value2 : NULL,
84
85
            'timezone' => $event_wrapper->field_event_date->value()[0]['timezone'],
            'timezone_db' => $event_wrapper->field_event_date->value()[0]['timezone_db'],
86
          );
87
88
89
90
91

          // Get the field_event_date from the node.
          $field_event_date = field_get_items('node', $node, 'field_event_date');

          // Set the new output from the re-occured dates.
92
          $vars['content']['output'] = field_view_value('node', $node, $field_name, $event_date, $display);
93
94

          // Drop the re-occuring rule if it is present.
Liam Morland's avatar
Liam Morland committed
95
          $vars['content']['output']['#markup'] = preg_replace('/\<div class=\"date-repeat-rule\"\>(.*?)\<\/div\>/', '', isset($vars['view']) ? $vars['content']['output']['#markup'] : NULL);
96
97

          // Remove the second end date if over multiple dates.
Liam Morland's avatar
Liam Morland committed
98
          $vars['content']['output']['#markup'] = preg_replace('/ to <span.*?<\/span>/', '', isset($vars['view']) ? $vars['content']['output']['#markup'] : NULL);
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
/**
 * Helper function.
 *
 * Removes the image tag from a given text.
 */
function _uw_ct_event_remove_images_from_text($text) {

  // Two patters that we are going to be searching for.
  // Pattern 1 is for only image tags that include only a paragraph tag.
  // Pattern 2 will remove the rest of the images.
  $pattern1 = '/<p><img(.*?)\/><\/p>/';
  $pattern2 = '/<img(.*?)\/>/';

  // If we match pattern 1 remove all of them.
  if (preg_match($pattern1, $text)) {
    $text = preg_replace($pattern1, '', $text);
  }

  // If we match pattern 2, remove all of them.
  if (preg_match($pattern2, $text)) {
    $text = preg_replace($pattern2, '', $text);
  }

  return $text;
}

131
/**
l26yan's avatar
l26yan committed
132
 * Implements hook_form_alter().
133
134
 */
function uw_ct_event_form_alter(&$form, &$form_state, $form_id) {
Liam Morland's avatar
Liam Morland committed
135
  // Content creation.
136
  if ($form_id == 'uw_location_node_form') {
Liam Morland's avatar
Liam Morland committed
137
    // Remove the 'delete this location' checkbox on the edit form.
138
139
    $form['field_location_details']['und'][0]['#after_build'][] = 'uw_ct_event_remove_location_delete';
  }
l26yan's avatar
l26yan committed
140

Liam Morland's avatar
Liam Morland committed
141
  // Exposed filters sitewide.
142
  if ($form_id == 'views_exposed_form') {
Liam Morland's avatar
Liam Morland committed
143
    // Get information about the current path to use for events exposed filters.
144
145
    $path = current_path();
    $path = explode("/", $path);
l26yan's avatar
l26yan committed
146

147
148
149
    // If this is the form for the exposed filters at the top of events,
    // use the post method to pass on choices so they're not a query string
    // after the URL.
Liam Morland's avatar
Liam Morland committed
150
    if ($form['#id'] == 'views-exposed-form-events-page' || $form['#id'] == 'views-exposed-form-events-events-archive-page'
151
        || $form['#id'] == 'views-exposed-form-events-with-calendar-page-1' || $form['#id'] == 'views-exposed-form-events-with-calendar-page-3') {
152
153
154
155
      // Using POST method from
      // https://drupal.org/comment/6468662#comment-6468662
      // (requires this patch on views, or an
      // additional module that Lily couldn't get to work)
Liam Morland's avatar
Liam Morland committed
156
      // @code
Liam Morland's avatar
Liam Morland committed
157
      // $form['#attributes']['method'] = 'post';
Liam Morland's avatar
Liam Morland committed
158
      // @endcode
159
    }
160

Liam Morland's avatar
Liam Morland committed
161
    // Hide dates option '-All-'.
162
163
    if ($form['#id'] == 'views-exposed-form-events-page' || $form['#id'] == 'views-exposed-form-events-events-archive-page' || $form['#id'] == 'views-exposed-form-events-events-tag-page' ||
        $form['#id'] == 'views-exposed-form-events-responsive-page' || $form['#id'] == 'views-exposed-form-events-responsive-events-archive-page' || $form['#id'] == 'views-exposed-form-events-responsive-events-tag-page') {
164
165
166
      $date_options = $form['date']['#options'];
      if (isset($date_options['All'])) {
        unset($date_options['All']);
167
      }
168
      $form['date']['#options'] = $date_options;
169
170
    }

171
172
173
    // When using "audience" or "type" exposed filter:
    // display the selected option ("tid" from path),
    // then change action to events.
174
    if ($form['#id'] == 'views-exposed-form-events-page' || $form['#id'] == 'views-exposed-form-events-responsive-page') {
175
      if (isset($path[1]) && isset($path[2])) {
176
177
        switch ($path[1]) {
          case "audience":
178
179
            // Cause the audience term id ("tid")
            // to be selected in the dropdown.
180
            $form_state['input']['audience'] = $path[2];
181
            break;
Liam Morland's avatar
Liam Morland committed
182

183
          case "type":
Liam Morland's avatar
Liam Morland committed
184
            // Cause the event term id ("tid") to be selected in the dropdown.
185
            $form_state['input']['type'] = $path[2];
186
187
            break;
        }
188
189
190
        // Make the form submit to the base events path;
        // once they submit to the exposed filter form we can't be sure
        // the URL still makes sense.
191
        $form['#action'] = base_path() . 'events';
192
      }
l26yan's avatar
l26yan committed
193
194
    }

195
196
197
198
199
200
    // When on "events by date" pages (from archive links),
    // add the chosen date to the "dates" exposed filter
    // and select it from the dropdown
    // Dates filter: Click date link,
    // add option composite_views_filter = 0 (date=0),
    // then change action to events.
201
    if ($form['#id'] == 'views-exposed-form-events-events-archive-page' || $form['#id'] == 'views-exposed-form-events-responsive-events-archive-page') {
Liam Morland's avatar
Liam Morland committed
202
203
204
205
      // Add the selected date to the dropdown.
      $timestamp = strtotime($path[2]);
      if ($timestamp) {
        $full_month = date('F', $timestamp);
206
        $final_name = strlen($path[2]) > 4 ? t('@full_month', array('@full_month' => $full_month)) . date(' Y', $timestamp) : $path[2];
Liam Morland's avatar
Liam Morland committed
207
208
        $form['date']['#options'][$path[2]] = $final_name;
        // Make Drupal think we submitted this value
209
210
        // $form_state['input'] =
        // array('date' => $path[2]) + $form_state['input'];.
Liam Morland's avatar
Liam Morland committed
211
212
213
214
215
        $form_state['input']['date'] = $path[2];
        // If other dropdowns were selected, they are passed in a query string
        // set field_uw_event_type_tid (type) if "type" was selected.
        if (isset($_GET['type'])) {
          $form_state['input']['type'] = $_GET['type'];
216
        }
Liam Morland's avatar
Liam Morland committed
217
218
219
220
221
        // Set field_audience_tid (audience) if "audience" was selected.
        if (isset($_GET['audience'])) {
          $form_state['input']['audience'] = $_GET['audience'];
        }
      }
222
223
224
225
      // Make the form submit to the base events path,
      // since the exposed filter can't actually deal with this
      // if they select the date, we have code elsewhere
      // that redirects them to the right path.
Liam Morland's avatar
Liam Morland committed
226
      $form['#action'] = base_path() . 'events';
l26yan's avatar
l26yan committed
227
    }
l26yan's avatar
l26yan committed
228

Liam Morland's avatar
Liam Morland committed
229
230
    // When on an events page that is not the "date archive" page.
    if ($form['#id'] == 'views-exposed-form-events-page') {
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
      // When coming from a submission of the exposed filters
      // that contains a "date archive" value
      // (from the composite_views_filter (date) field) -
      // and this can only happen from a "date archive" page -
      // since the form destination is set to "events"
      // (in case they didn't pick the date),
      // redirect to the date-based URL.
      // We don't need to add anything to the dropdown
      // since redirecting here will take care of that.
      if (isset($form_state['input']['date'])
        && !in_array($form_state['input']['date'],
          array('Current', 'Past', 'Today'))
        /* && $form_state['input']['type'] == 'All' &&
        $form_state['input']['audience'] == 'All' */) {
        drupal_goto('events/archive/' . $form_state['input']['date'], array(
          'query' => array(
            'type' => $form_state['input']['type'],
            'audience' => $form_state['input']['audience'],
          ),
        ));
l26yan's avatar
l26yan committed
251
252
      }
    }
l26yan's avatar
l26yan committed
253
254
255
  }
}

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/**
 * Implements hook_views_pre_render().
 *
 * Add the date to the title of the page.
 */
function uw_ct_event_views_pre_render(&$view) {

  // If we are on a news archive page, change the title.
  if ($view->name == 'events_responsive' && $view->current_display == 'events_archive_page') {

    // Get the URL.
    $args = arg();

    // The date for the news archive will always be the last part of the URL.
    $date = end($args);

    // If we have the format YYYY-MM, change title.
    // If we dont have that format it is just YYYY.
    if (preg_match('/[0-9]{4}-[0-9]{1,2}/', $date)) {
      $display_date = date("F Y", strtotime($date));
Tyler Struyk's avatar
Tyler Struyk committed
276
      $view->build_info['title'] = t('Events - @display_date', array('@display_date' => $display_date));
277
278
    }
    else {
Tyler Struyk's avatar
Tyler Struyk committed
279
      $view->build_info['title'] = t('Events - @date', array('@date' => $date));
280
281
282
283
    }
  }
}

284
/**
Liam Morland's avatar
Liam Morland committed
285
 * Implements hook_views_pre_view().
286
287
 */
function uw_ct_event_views_pre_view(&$view, &$display_id, &$args) {
288
289
290
291
292
293
  // If we are rendering the mini calendar,
  // and are at a url that references a day within a month,
  // make the mini-calendar start at that month.
  // note that currently dates are NOT zero-padded,
  // but we might want this in the future;
  // if we change this, the preg_match must change,
294
  // e.g.:
l26yan's avatar
l26yan committed
295
  // events/archive/2013-10
296
  // events/calendar/2013-10
297
  // events/day/2013-10-31
298
299
  // ***WE WILL HAVE TO REVIEW
  // AND POSSIBLY CHANGE WHAT URLS AFFECT MINI-CALENDAR.
l26yan's avatar
l26yan committed
300
  if ($view->name == 'events_with_calendar' && $display_id == 'block_1') {
301
302
    $path = current_path();
    $path = explode("/", $path);
l26yan's avatar
l26yan committed
303
    if (isset($path[2]) && (preg_match('/^(\d{4})$/', $path[2], $match))) {
304
305
306
      if ($path[2] != date("Y")) {
        $view->args[0] = $match[1] . '-1';
      }
l26yan's avatar
l26yan committed
307
    }
308
    if (isset($path[2]) && (preg_match('/^(\d{4}-(?:[123456789]|1[012]))$/', $path[2], $match) || preg_match('/^(\d{4}-(?:0[123456789]|1[012]))$/', $path[2], $match))) {
309
310
      $view->args[0] = $match[1];
    }
311
    if (isset($path[2]) && preg_match('/^(\d{4}-(?:[123456789]|1[012]))-(?:[123456789]|[12]\d|3[01])$/', $path[2], $match)) {
312
313
314
315
316
      $view->args[0] = $match[1];
    }
  }
}

l26yan's avatar
l26yan committed
317
/**
Liam Morland's avatar
Liam Morland committed
318
 * Implements hook_views_query_alter().
l26yan's avatar
l26yan committed
319
320
 */
function uw_ct_event_views_query_alter(&$view, &$query) {
321
322
  $path = current_path();
  $path = explode("/", $path);
Liam Morland's avatar
Liam Morland committed
323

l26yan's avatar
l26yan committed
324
  $today = date("Y-m-d");
325
  $future_date = date("Y-m-d", strtotime('+365 day'));
326

327
  if ($view->name == 'events_responsive' && isset($view->exposed_raw_input['date'])) {
Liam Morland's avatar
Liam Morland committed
328
    // Modify query for 'Past' to sort by desc.
329
330
    if ($view->exposed_raw_input['date'] == 'Past') {
      foreach ($query->orderby as $key => $data) {
331
332
        // We search for these fields so that it doesn't matter where they are;
        // they moved once and broke this.
333
334
335
336
337
338
339
        if ($data['field'] == 'field_data_field_event_date_field_event_date_value' || $data['field'] == 'field_data_field_event_date_field_event_date_value2') {
          $query->orderby[$key]['direction'] = 'DESC';
        }
      }
    }
  }

340
  if (($view->name == 'events' || $view->name == 'events_responsive') && isset($view->exposed_raw_input['date'])) {
341

Liam Morland's avatar
Liam Morland committed
342
    // Unset query conditions for events/archive view.
343
344
345
    if (isset($path[0]) && $path[0] == 'events' && isset($path[1]) && $path[1] == 'archive' && isset($path[2])) {
      end($query->where[1]['conditions']);
      $key = key($query->where[1]['conditions']);
Liam Morland's avatar
Liam Morland committed
346
      if (strlen($path[2]) == 4) {
347
348
        if (preg_match('/^(\d{4})$/', $path[2], $match)) {
          $archive_year = $match[0];
349
          if (isset($archive_year) && $view->exposed_raw_input['date'] == $archive_year) {
Liam Morland's avatar
Liam Morland committed
350
            unset($query->where[1]['conditions'][$key]);
351
352
353
354
355
          }
        }
      }
      else {
        if (preg_match('/^(\d{4}-(?:[123456789]|1[012]))$/', $path[2], $match) || preg_match('/^(\d{4}-(?:0[123456789]|1[012]))$/', $path[2], $match)) {
Liam Morland's avatar
Liam Morland committed
356
          $archive_year_month = $match[0];
357
          if (isset($archive_year_month) && $view->exposed_raw_input['date'] == $archive_year_month) {
Liam Morland's avatar
Liam Morland committed
358
            unset($query->where[1]['conditions'][$key]);
359
360
361
362
363
          }
        }
      }
    }

364
    // Modify query for 'Current and upcoming' to include 'OR' section
365
366
367
    // Dates now (WCMS 1.10+ w/Date 7.x-2.9-beta2+2-dev-uw_wcms1)
    // seem to be stored in local time format,
    // so we removed offset correction from the SQL statement below.
368
    if ($view->exposed_raw_input['date'] == 'Current') {
369
370
      end($query->where[1]['conditions']);
      $key = key($query->where[1]['conditions']);
371
372
      $query->where[1]['conditions'][$key]['field'] = "((DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T') <= :field_data_field_event_date_field_event_date_value)
          AND (DATE_FORMAT(field_data_field_event_date.field_event_date_value2, '%Y-%m-%dT%T') >= :field_data_field_event_date_field_event_date_value2))
Liam Morland's avatar
Liam Morland committed
373
        OR
374
          (DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T') >= :field_data_field_event_date_field_event_date_value)";
375
376
377
      $query->where[1]['conditions'][$key]['value'] = array(':field_data_field_event_date_field_event_date_value' => $today, ':field_data_field_event_date_field_event_date_value2' => $today);
    }
    // Modify query for 'Today' to include 'OR' section
378
379
380
    // Dates now (WCMS 1.10+ w/Date 7.x-2.9-beta2+2-dev-uw_wcms1)
    // seem to be stored in local time format,
    // so we removed offset correction from the SQL statement below.
381
    if ($view->exposed_raw_input['date'] == 'Today') {
382
383
      end($query->where[1]['conditions']);
      $key = key($query->where[1]['conditions']);
384
      $query->where[1]['conditions'][$key]['field'] =
385
386
        "((DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%d') <= :field_data_field_event_date_field_event_date_value)
          AND (DATE_FORMAT(field_data_field_event_date.field_event_date_value2, '%Y-%m-%d') >= :field_data_field_event_date_field_event_date_value2))
387
        OR
388
          (DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T') = :field_data_field_event_date_field_event_date_value)";
389
390
      $query->where[1]['conditions'][$key]['value'] = array(':field_data_field_event_date_field_event_date_value' => $today, ':field_data_field_event_date_field_event_date_value2' => $today);
    }
Liam Morland's avatar
Liam Morland committed
391
    // Modify query for 'Past' to sort by desc.
392
    if ($view->exposed_raw_input['date'] == 'Past') {
393
      foreach ($query->orderby as $key => $data) {
394
395
        // We search for these fields so that it doesn't matter where they are;
        // they moved once and broke this.
396
397
398
        if ($data['field'] == 'field_data_field_event_date_field_event_date_value' || $data['field'] == 'field_data_field_event_date_field_event_date_value2') {
          $query->orderby[$key]['direction'] = 'DESC';
        }
399
400
      }
    }
l26yan's avatar
l26yan committed
401
  }
402
403
404
  if ($view->name == 'events_with_calendar' && $view->current_display == 'feed_1') {
    end($query->where[1]['conditions']);
    $key = key($query->where[1]['conditions']);
Liam Morland's avatar
Liam Morland committed
405
    $query->where[1]['conditions'][$key]['field'] =
406
      "((DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T')
407
            <= :field_data_field_event_date_field_event_date_value)
Liam Morland's avatar
Liam Morland committed
408
         AND
409
           (DATE_FORMAT(field_data_field_event_date.field_event_date_value2, '%Y-%m-%dT%T')
410
411
            >= :field_data_field_event_date_field_event_date_value2)
         AND
412
           (DATE_FORMAT(field_data_field_event_date.field_event_date_value2, '%Y-%m-%dT%T')
413
414
415
           <= :future_date)
       )
       OR
416
       ((DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T')
417
418
         >= :field_data_field_event_date_field_event_date_value)
         AND
419
           (DATE_FORMAT(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T')
420
          <= :future_date))";
421
422
423
424
425
    $query->where[1]['conditions'][$key]['value'] = array(
      ':field_data_field_event_date_field_event_date_value' => $today,
      ':field_data_field_event_date_field_event_date_value2' => $today,
      ':future_date' => $future_date,
    );
426
  }
427

428
429
430
431
  // Remove the timezone adjustment.
  // Dates are already stored in local time so
  // they appear on the wrong day
  // when timezone adjustment is applied. RT#591395.
432
433
  if ($view->name == 'events_with_calendar' && $view->current_display == 'page_3') {
    $query->where['date']['conditions'][0]['field'] =
Liam Morland's avatar
Liam Morland committed
434
435
436
437
      "DATE_FORMAT(STR_TO_DATE(field_data_field_event_date.field_event_date_value2, '%Y-%m-%dT%T'), '%Y-%m-%d')
        >= :node_date_argument
      AND
        DATE_FORMAT(STR_TO_DATE(field_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), '%Y-%m-%d')
438
439
        <= :node_date_argument1";
  }
440
441
442
}

/**
lkmorlan's avatar
lkmorlan committed
443
 * Implements hook_node_form_ID_alter().
Liam Morland's avatar
Liam Morland committed
444
 *
445
446
 * Adds location data (through javascript settings) to the form,
 * which allows for quickly filling in
Liam Morland's avatar
Liam Morland committed
447
 * common campus locations
448
449
450
451
452
 * There needs to be a central website to get location data from
 * (that has the uw_ct_location feature enabled, populated with content)
 * The location of that site is in a Drupal variable,
 * uw_location_data_json_url, and defaults to the current site
 * if it is not set.
453
454
 */
function uw_ct_event_form_uw_event_node_form_alter(&$form, &$form_state, $form_id) {
Liam Morland's avatar
Liam Morland committed
455
  // Check if we have the data in cache, if not, retrieve it.
456
457
458
459
460
  $cache = cache_get('uw_ct_event:locations', 'cache');
  if ($cache) {
    $locations = $cache->data;
  }
  else {
461
    $request = variable_get('uw_location_data_json_url', 'https://uwaterloo.ca/web-resources') . '/location/json/list';
462
463
    $response = drupal_http_request($request);
    $locations = json_decode($response->data);
mnshantz's avatar
mnshantz committed
464

465
    if (isset($locations) && !isset($locations->error)) {
Liam Morland's avatar
Liam Morland committed
466
      // Set the cache.
467
468
469
      cache_set('uw_ct_event:locations', $locations, 'cache', CACHE_TEMPORARY);
    }
  }
lkmorlan's avatar
lkmorlan committed
470

471
  if (isset($locations)) {
Liam Morland's avatar
Liam Morland committed
472
    // Add javascript for pre-filling in location data.
473
474
    $form['#attached']['js'][] = drupal_get_path('module', 'uw_ct_event') . '/js/location-autofill.js';
    $location_container_id = 'uw_event_location';
mnshantz's avatar
mnshantz committed
475

476
477
    // Add Div Wrapper around form so the javascript knows
    // where to add the location lookup dropdown.
478
479
480
    $form['field_event_location']['#prefix'] = '<div id="' . $location_container_id . '">';
    $form['field_event_location']['#suffix'] = '</div>';

Liam Morland's avatar
Liam Morland committed
481
    // Settings used in location-autofill.js.
482
483
484
485
486
487
488
489
    $settings = array(
      'label' => t('Location lookup'),
      'description' => t('Choose a location or enter location information below.'),
      'custom' => t('- Custom location -'),
      'data' => $locations,
      'selectId' => 'autofill-location-data',
      'containerId' => $location_container_id,
    );
mnshantz's avatar
mnshantz committed
490

491
492
493
494
495
    $form['#attached']['js'][] = array(
      'data' => array('uw_ct_event' => $settings),
      'type' => 'setting',
    );
  }
Liam Morland's avatar
Liam Morland committed
496
  // Remove the 'delete this location' checkbox on the edit form.
497
498
499
500
  $form['field_event_location']['und'][0]['#after_build'][] = 'uw_ct_event_remove_location_delete';
}

/**
501
 * Remove the delete checkbox from location element.
Liam Morland's avatar
Liam Morland committed
502
 *
503
504
 * Code snippet courtesy of Fabian -
 * ref: http://drupal.org/node/381458#comment-4627442.
505
 */
506
function uw_ct_event_remove_location_delete(&$form_element, &$form_state) {
507
508
509
  $form_element['name']['#description'] = t('e.g. a building or venue');
  $form_element['additional']['#description'] = t('e.g. room number or meeting point');
  $form_element['locpick']['instructions']['#markup'] = t('Latitude and longitude is used for generating map links. If you do not have latitude and longitude coordinates, you can add a specific map link below.');
510
511
  return $form_element;
}
512

513
514
515
516
/**
 * Implements hook_block_info().
 */
function uw_ct_event_block_info() {
517
518
  $blocks['front_page'] = array(
    'info' => t('Events: front page'),
519
    'cache' => DRUPAL_CACHE_GLOBAL,
520
  );
Liam Morland's avatar
Liam Morland committed
521
  $blocks['events_public_feed'] = array(
mnshantz's avatar
mnshantz committed
522
523
524
    'info' => t('Events: public feed'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
l26yan's avatar
l26yan committed
525
  $blocks['event-calendar-block-id'] = array(
lkmorlan's avatar
lkmorlan committed
526
    'info' => t('Event calendar block'),
527
    'cache' => DRUPAL_CACHE_GLOBAL,
l26yan's avatar
l26yan committed
528
  );
529
530
  $blocks['events_by_audience'] = array(
    'info' => t('Events by audience'),
531
    'cache' => DRUPAL_CACHE_GLOBAL,
532
  );
533
534
535
536
537
538
539
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function uw_ct_event_block_view($delta = '') {
540
  global $language;
541
  global $theme_key;
542
  $block = array();
543
544
545
546
547
548
549
550
551
552
553
554
  // If the user doesn't have permission to access content,
  // don't display this block.
  if (!user_access('access content')) {
    return NULL;
  }
  else {
    switch ($delta) {
      case 'front_page':
        $events = db_select('node', 'n');
        $events->leftJoin('field_data_field_event_date', 'events', 'events.entity_id = n.nid');
        $events->fields('events', [
          'field_event_date_value',
Liam Morland's avatar
Liam Morland committed
555
          'field_event_date_value2',
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        ]);
        $events->fields('n', ['nid', 'title', 'sticky']);
        $events->condition('n.type', 'uw_event', '=');
        $events->condition('n.status', 1, '=');
        $events->condition('n.promote', 1, '=');
        $events->havingCondition('field_event_date_value2', date('Y-m-d'), '>=');
        $events->orderBy('n.sticky', 'DESC');
        $events->orderBy('events.field_event_date_value', 'ASC');
        $events->orderBy('n.title');
        $events->range(0, 3);

        $result = $events->execute();
        $items = [];
        $count = 0;

        foreach ($result as $record) {
          $date_start = strtotime($record->field_event_date_value);
          $date_end = strtotime($record->field_event_date_value2);
          // Start and end on same date. "Nov. 24, 2005".
          if (date('Y-m-d', $date_start) === date('Y-m-d', $date_end)) {
576
            if ($language->language === 'en') {
577
578
579
580
581
582
583
584
585
586
              $date_formatted = uw_month_name_short(date('n', $date_start)) . '&nbsp;' . date('j, Y', $date_start);
            }
            else {
              $date_formatted = format_date($date_start, 'custom', t('M j, Y', [], ['context' => 'php date format']));
            }
          }
          elseif (date('Y', $date_start) === date('Y', $date_end)) {
            // Same month and year, different day. "Nov. 24-26, 2005".
            if (date('m', $date_start) === date('m', $date_end)) {
              if ($language->language === 'en') {
Tyler Struyk's avatar
Tyler Struyk committed
587
588
589
590
591
                $date_formatted = t('@month @date_start to @date_end', array(
                  '@month' => uw_month_name_short(date('n', $date_start)),
                  '@date_start' => date('j', $date_start),
                  '@date_end' => date('j, Y', $date_end),
                ));
592
593
594
595
596
              }
              else {
                $date_formatted = format_date($date_start, 'custom', t('M', [], ['context' => 'php date format']))
                  . '&nbsp;'
                  . format_date($date_start, 'custom', t('j', [], ['context' => 'php date format']))
Liam Morland's avatar
Liam Morland committed
597
                  . t('&nbsp;to&nbsp;')
598
599
                  . format_date($date_end, 'custom', t('j, Y', [], ['context' => 'php date format']));
              }
600
            }
601
            // Same year. "Nov. 24 to Dec. 2, 2005".
602
            else {
603
604
605
606
607
608
609
610
611
612
613
614
615
              if ($language->language === 'en') {
                $date_formatted = t('@start_month @start_day to @end_month @end_day',
                  [
                    '@start_month' => uw_month_name_short(date('n', $date_start)),
                    '@start_day' => date('j', $date_start),
                    '@end_month' => uw_month_name_short(date('n', $date_end)),
                    '@end_day' => date('j, Y', $date_end),
                  ]);
              }
              else {
                $date_formatted = format_date($date_start, 'custom', t('M', [], ['context' => 'php date format']))
                  . '&nbsp;'
                  . format_date($date_start, 'custom', t('j', [], ['context' => 'php date format']))
Liam Morland's avatar
Liam Morland committed
616
                  . t('&nbsp;to&nbsp;')
617
618
                  . format_date($date_end, 'custom', t('M j, Y', [], ['context' => 'php date format']));
              }
619
            }
lkmorlan's avatar
lkmorlan committed
620
          }
621
          // Fully different dates."Nov. 24, 2005 to Jan. 2, 2006".
lkmorlan's avatar
lkmorlan committed
622
          else {
623
            if ($language->language === 'en') {
Tyler Struyk's avatar
Tyler Struyk committed
624
625
626
627
628
629
              $date_formatted = t('@month_start @date_start to @month_end @date_end', array(
                '@month_start' => uw_month_name_short(date('n', $date_start)),
                '@date_start' => date('j, Y', $date_start),
                '@month_end' => uw_month_name_short(date('n', $date_end)),
                'date_end' => date('j, Y', $date_end),
              ));
630
631
            }
            else {
632
              $date_formatted = format_date($date_start, 'custom', t('M j, Y', [], ['context' => 'php date format']))
Liam Morland's avatar
Liam Morland committed
633
                . t('&nbsp;to&nbsp;')
634
                . format_date($date_end, 'custom', t('M j, Y', [], ['context' => 'php date format']));
635
            }
lkmorlan's avatar
lkmorlan committed
636
          }
637

638
639
640
          $items[$count] = "";
          $items[$count] .= '<span class="home-listing-block-date' . (($record->sticky) ? ' sticky' : '') . '">' . $date_formatted . '</span>';
          $items[$count] .= '<span class="home-listing-block-link">' . l($record->title, 'node/' . $record->nid) . '</span>';
641

642
643
          if ($theme_key == 'uw_fdsu_theme_resp') {
            $node = node_load($record->nid);
Liam Morland's avatar
Liam Morland committed
644

645
646
647
648
649
650
651
652
653
            if (!empty($node->body['en'][0]['summary'])) {
              $summary = $node->body['en'][0]['summary'];
            }
            elseif (!empty($node->body['en'][0]['value'])) {
              $summary = text_summary($node->body['en'][0]['value']);
            }
            else {
              $summary = '';
            }
654

655
656
657
658
659
660
661
662
663
664
            $summary = check_markup(preg_replace(',<(/?)h\d,', '<$1p', $summary), 'uw_tf_basic');
            $summary = _filter_htmlcorrector($summary);
            $summary = preg_replace("/<img[^>]+\>/i", "", $summary);
            $items[$count] .= '<span class="home-listing-block-summary">';
            if (!empty($node->field_event_image[LANGUAGE_NONE][0]['uri'])) {
              $listing_image = $node->field_event_image[LANGUAGE_NONE][0]['uri'];
              $themed_image = '<img alt="' . $node->field_event_image[LANGUAGE_NONE][0]['alt'] . '" src="' . file_create_url($listing_image) . '" typeof="foaf:Image">';
              $items[$count] .= $themed_image;
            }
            $items[$count] .= $summary . '</span>';
665
666
          }

667
668
          $count++;
        }
669

670
671
672
673
674
675
676
677
678
679
680
681
        if (!empty($items)) {
          $block['subject'] = t('Events');
          // Setup array to be used by theme_item_list.
          $content = [
            'items' => $items,
            'title' => '',
            'type' => 'ol',
            'attributes' => [],
          ];
          $block['content'] = theme('item_list', $content) . '<span class="home-listing-block-more-link">' . l(t("All upcoming events"), 'events') . '</span>';
        }
        break;
682

683
684
685
686
      // Create a link to the rss feed for news.
      case 'events_public_feed':
        $block['content'] = events_public_feed_link();
        break;
mnshantz's avatar
mnshantz committed
687

688
689
690
691
      // Create a link to expose event calendar.
      case 'event-calendar-block-id':
        $block['content'] = uw_ct_event_calendar_contents();
        break;
lkmorlan's avatar
lkmorlan committed
692

693
      case 'events_by_audience':
694

695
696
697
698
        $audience_tree = uw_ct_event_audience_taxonomy_tree(0);
        $html = '<div class="item-list">';
        $html .= $audience_tree;
        $html .= '</div>';
Liam Morland's avatar
Liam Morland committed
699

700
701
702
703
704
705
706
707
708
        if ($audience_tree) {
          $block['subject'] = '<button>' . t('Events by audience') . '</button>';
        }
        else {
          $block['subject'] = ' ';
        }
        $block['content'] = $html;
        break;
    }
709
710
711
712
713
714
  }
  return $block;
}

/**
 * Implements hook_block_view_alter().
Liam Morland's avatar
Liam Morland committed
715
716
 *
 * Add events by date under calendar block.
717
718
 */
function uw_ct_event_block_view_alter(&$data, $block) {
l26yan's avatar
l26yan committed
719
720
  $event_exist = db_query("SELECT count(nid) FROM {node} node WHERE type = 'uw_event'")->fetchField();

721
  if ($block->delta == 'events_with_calendar-block_1') {
722
723
724
    if (!user_access('access content')) {
      return NULL;
    };
l26yan's avatar
l26yan committed
725
726
    if ($event_exist) {
      $by_date = uw_ct_event_by_date();
727
      $header = '<h2><button>' . t('Events by date') . '</button></h2>';
l26yan's avatar
l26yan committed
728
729
730
731
732
733
      $before = $data['content']['#markup'];
      $data['content']['#markup'] = $header . $before . $by_date;
    }
    else {
      $data['content']['#markup'] = '';
    }
734
  }
l26yan's avatar
l26yan committed
735
736
737

  if ($block->delta == 'event_type_block-events_by_type') {
    if ($event_exist) {
738
      $data['subject'] = '<button>' . t('@subject', array('@subject' => $data['subject'])) . '</button>';
l26yan's avatar
l26yan committed
739
740
    }
  }
741
}
742

l26yan's avatar
l26yan committed
743
744
/**
 * Implements hook_init().
Liam Morland's avatar
Liam Morland committed
745
 *
kpaxman's avatar
kpaxman committed
746
 * Redirect events/archive, events/audience, events/type pages to events
Liam Morland's avatar
Liam Morland committed
747
 * Redirect invalid term ids and dates on above paths to events.
l26yan's avatar
l26yan committed
748
749
750
751
 */
function uw_ct_event_init() {
  $path = current_path();

752
753
  // Redirect events/archive, events/audience,
  // events/type pages to events.
l26yan's avatar
l26yan committed
754
  if ($path == 'events/archive' || $path == 'events/audience' || $path == 'events/type') {
755
    drupal_goto('events', array(), 301);
l26yan's avatar
l26yan committed
756
757
758
  }

  $path = explode("/", $path);
l26yan's avatar
l26yan committed
759

Liam Morland's avatar
Liam Morland committed
760
  // Find out TIDS within uwaterloo_audience.
761
762
  $uw_ct_event_audience_tids = uw_ct_event_get_tid_from_machine_name('uwaterloo_audience');

Liam Morland's avatar
Liam Morland committed
763
  // Find out TIDS within uw_event_type.
764
765
  $uw_ct_event_type_tids = uw_ct_event_get_tid_from_machine_name('uw_event_type');

Liam Morland's avatar
Liam Morland committed
766
  // Find out TIDS within uw_event_tags.
767
  $uw_ct_event_tag_tids = uw_ct_event_get_tid_from_machine_name('uw_event_tags');
768

769
770
  // Redirect from events/category/$PATH[2] to events/audience/$PATH[2]
  // -- e.g. https://uwaterloo.ca/environment/events/category/1
771
  if ($path[0] == 'events' && isset($path[1]) && ($path[1] == 'category') && isset($path[2])) {
772
    if (is_numeric($path[2]) && in_array($path[2], $uw_ct_event_audience_tids)) {
773
      drupal_goto('events/audience/' . $path[2], array(), 301);
774
775
776
    }
  }

777
778
  // Redirect events/audience/$PATH[2],
  // when $PATH[2] is NOT taxonomy term id of audience.
l26yan's avatar
l26yan committed
779
  if ($path[0] == 'events' && isset($path[1]) && ($path[1] == 'audience') && isset($path[2])) {
780
    if (!is_numeric($path[2]) || !in_array($path[2], $uw_ct_event_audience_tids)) {
l26yan's avatar
l26yan committed
781
      drupal_set_message(t('Invalid event audience URL. You have been redirected to the main "events" page.'), 'warning');
782
      drupal_goto('events', array(), 301);
l26yan's avatar
l26yan committed
783
784
785
    }
  }

786
787
  // Redirect events/type/$PATH[2],
  // when $PATH[2] is NOT taxonomy term id of type.
l26yan's avatar
l26yan committed
788
  if ($path[0] == 'events' && isset($path[1]) && ($path[1] == 'type') && isset($path[2])) {
789
    if (!is_numeric($path[2]) || !in_array($path[2], $uw_ct_event_type_tids)) {
l26yan's avatar
l26yan committed
790
      drupal_set_message(t('Invalid event type URL. You have been redirected to the main "events" page.'), 'warning');
791
      drupal_goto('events', array(), 301);
l26yan's avatar
l26yan committed
792
793
    }
  }
kpaxman's avatar
kpaxman committed
794

795
796
  // Redirect events/archive/$PATH[2],
  // when $PATH[2] is NOT in a date format we would pass.
kpaxman's avatar
kpaxman committed
797
  if ($path[0] == 'events' && isset($path[1]) && ($path[1] == 'archive') && isset($path[2])) {
798
    if (!preg_match('/^\d{4}(?:-(?:[123456789]|1[012]))?$/', $path[2])) {
l26yan's avatar
l26yan committed
799
      drupal_set_message(t('Invalid event date URL. You have been redirected to the main "events" page.'), 'warning');
800
      drupal_goto('events', array(), 301);
Liam Morland's avatar
Liam Morland committed
801
    }
kpaxman's avatar
kpaxman committed
802
  }
l26yan's avatar
l26yan committed
803

804
805
806
807
  // Redirect taxonomy/term/$PATH[2],
  // when $PATH[2] is taxonomy term id of tag
  // Only do when the path ends in taxonomy/term/xx,
  // because taxonomy/term/xx/edit breaks otherwise.
808
  if ($path[0] == 'taxonomy' && $path[1] == 'term' && isset($path[2]) && !isset($path[3])) {
809
    if (in_array($path[2], $uw_ct_event_tag_tids)) {
810
      drupal_goto('events/tag/' . $path[2], array(), 301);
l26yan's avatar
l26yan committed
811
812
813
    }
  }

814
815
  // Redirect events/tag/$PATH[2],
  // when $PATH[2] is NOT taxonomy term id of tag.
l26yan's avatar
l26yan committed
816
  if ($path[0] == 'events' && isset($path[1]) && ($path[1] == 'tag') && isset($path[2])) {
817
    if (!is_numeric($path[2]) || !in_array($path[2], $uw_ct_event_tag_tids)) {
l26yan's avatar
l26yan committed
818
      drupal_set_message(t('Invalid event tag URL. You have been redirected to the main "events" page.'), 'warning');
819
      drupal_goto('events', array(), 301);
l26yan's avatar
l26yan committed
820
821
    }
  }
822

Liam Morland's avatar
Liam Morland committed
823
  // Redirect events/calendar/NOTADATE.
824
825
  if ($path[0] == 'events' && isset($path[1]) && $path[1] == 'calendar' && isset($path[2]) && !preg_match('/^[0-9]{4}-(0?[1-9]|1[0-2])$/', $path[2])) {
    drupal_set_message(t('Invalid calendar URL. You have been redirected to the main "calendar" page.'), 'warning');
826
    drupal_goto('events/calendar', array(), 301);
827
828
  }

Liam Morland's avatar
Liam Morland committed
829
  // Redirect events/day/NOTADATE.
830
831
  if ($path[0] == 'events' && isset($path[1]) && $path[1] == 'day' && isset($path[2]) && !preg_match('/^[0-9]{4}-(0?[1-9]|1[0-2])(-[0-9]{1,2})$/', $path[2])) {
    drupal_set_message(t('Invalid day URL. You have been redirected to today\'s "day" page.'), 'warning');
832
    drupal_goto('events/day', array(), 301);
833
  }
l26yan's avatar
l26yan committed
834
835
}

836
837
838
/**
 * Implements hook_page_alter().
 *
839
 * Remove Location if there is no location set. The Location heading stays if a
Liam Morland's avatar
Liam Morland committed
840
841
 * location is set and then removed, so removing it from page if there is no
 * location. See FDSU-1621.
842
843
844
845
846
847
 */
function uw_ct_event_page_alter(&$page) {
  // Get nid of current node.
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);

848
849
    // If there is a location present,
    // step through each one and ensure that it is completely empty.
850
    // If it is empty unset the location.
Liam Morland's avatar
Liam Morland committed
851
    if (isset($page['content']['system_main']['nodes'][$nid]['body']['#object']->field_event_location[LANGUAGE_NONE])) {
852
      foreach ($page['content']['system_main']['nodes'][$nid]['body']['#object']->field_event_location[LANGUAGE_NONE] as $key => $locations) {
Liam Morland's avatar
Liam Morland committed
853
        $location_flag = FALSE;
854
855
856
857
        foreach ($locations as $location_key => $location) {
          if ($location_key !== 'lid' && $location_key !== 'source' && $location_key !== 'is_primary') {
            if ($location_key == 'latitude' || $location_key == "longitude") {
              if ($location !== '0.000000') {
Liam Morland's avatar
Liam Morland committed
858
                $location_flag = TRUE;
859
860
                break;
              }
Liam Morland's avatar
Liam Morland committed
861
862
            }
            else {
863
              if ($location !== "") {
Liam Morland's avatar
Liam Morland committed
864
                $location_flag = TRUE;
865
866
                break;
              }
867
868
869
            }
          }
        }
Liam Morland's avatar
Liam Morland committed
870
        if ($location_flag == FALSE) {
871
872
873
874
875
876
          if (isset($page['content']['system_main']['nodes'][$nid]['field_event_location'])) {
            unset($page['content']['system_main']['nodes'][$nid]['field_event_location']);
          }
          if (isset($page['content']['system_main']['nodes'][$nid]['body']['#object']->field_event_location)) {
            unset($page['content']['system_main']['nodes'][$nid]['body']['#object']->field_event_location);
          }
877
878
879
880
881
882
        }
      }
    }
  }
}

883
884
885
/**
 * Implements hook_page_build().
 *
Liam Morland's avatar
Liam Morland committed
886
 * Add the breadcrumbs for the management view.
887
888
 */
function uw_ct_event_page_build() {
889
  $path = current_path();
890
891
  if ($path == 'admin/workbench/manage/events') {
    $breadcrumb = drupal_get_breadcrumb();
Liam Morland's avatar
Liam Morland committed
892
893
894
    $breadcrumb[1] = l(t('Administration'), 'admin');
    $breadcrumb[2] = l(t('My Workbench'), 'admin/workbench');
    $breadcrumb[3] = l(t('Create/Manage Content'), 'admin/workbench/create');
895
    drupal_set_breadcrumb($breadcrumb);
896

897
898
  }
  else {
899
900
    $path = explode("/", $path);
    switch ($path[0]) {
901
902
903
904
      case 'node':
        $node = isset($path[1]) && $path[1] != 'add' ? node_load($path[1]) : NULL;
        if (isset($node) && is_object($node) && $node->type == 'uw_event') {
          $breadcrumb = drupal_get_breadcrumb();
Liam Morland's avatar
Liam Morland committed
905
          $breadcrumb[1] = l(t('Events'), 'events');
906

l26yan's avatar
l26yan committed
907
          drupal_add_js(drupal_get_path('module', 'uw_ct_event') . '/js/uw_ct_event.js');
lkmorlan's avatar
lkmorlan committed
908

909
910
          // TODO: determine how to handle repeating dates (edge case)
          // currently we only check the very first start date
911
912
          // add the timezone offset to the stored datetime
          // to get the actual datetime (NOTE: having to do this MAY be a bug)
Liam Morland's avatar
Liam Morland committed
913
          $start_date = strtotime($node->field_event_date[$node->language][0]['value']) + $node->field_event_date[$node->language][0]['offset'];
914
915
          $year = format_date($start_date, 'custom', 'Y');
          $month_name = format_date($start_date, 'custom', 'F');
916
          $month_number = format_date($start_date, 'custom', 'n');
lkmorlan's avatar
lkmorlan committed
917
918
          $breadcrumb[2] = l($year, 'events/archive/' . $year);
          $breadcrumb[3] = l($month_name, 'events/archive/' . $year . '-' . $month_number);
919
          drupal_set_breadcrumb($breadcrumb);