Projet

Général

Profil

Paste
Télécharger (23,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / date / date_views / includes / date_views_filter_handler_simple.inc @ db9ffd17

1
<?php
2
/**
3
 * @file
4
 * A standard Views filter for a single date field, using Date API form selectors and sql handling.
5
 */
6

    
7
class date_views_filter_handler_simple extends views_handler_filter_date {
8
  var $date_handler = NULL;
9
  var $offset = NULL;
10

    
11
  function init(&$view, &$options) {
12
    parent::init($view, $options);
13
    module_load_include('inc', 'date_api', 'date_api_sql');
14
    $this->date_handler = new date_sql_handler(DATE_UNIX);
15
    if (!empty($this->definition['field_name'])) {
16
      $field = field_info_field($this->definition['field_name']);
17
      if (!empty($field) && !empty($field['type'])) {
18
        $this->date_handler->date_type = $field['type'];
19
      }
20
      $this->date_handler->db_timezone = date_get_timezone_db($field['settings']['tz_handling']);
21
      $this->date_handler->local_timezone = date_get_timezone($field['settings']['tz_handling']);
22
    }
23
    $this->form_submitted = FALSE;
24
    $this->date_handler->granularity = isset($options['granularity']) ? $options['granularity'] : 'day';
25
    $this->format = $this->date_handler->views_formats($this->options['granularity'], 'sql');
26

    
27
    // Identify the base table for this field.
28
    // It will be used to call for the right query field options.
29
    $this->base_table = $this->table;
30

    
31
  }
32

    
33
  // Set default values for the date filter.
34
  function option_definition() {
35
    $options = parent::option_definition();
36
    $options['granularity'] = array('default' => 'day');
37
    $options['form_type'] = array('default' => 'date_select');
38
    $options['default_date'] = array('default' => '');
39
    $options['default_to_date'] = array('default' => '');
40
    $options['year_range'] = array('default' => '-3:+3');
41
    $options['add_delta'] = array('default' => '');
42
    return $options;
43
  }
44

    
45
  function operators() {
46
    $operators = parent::operators();
47
    $operators['contains'] = array(
48
      'title' => t('Contains'),
49
      'method' => 'op_contains',
50
      'short' => t('contains'),
51
      'values' => 1,
52
    );
53
    return $operators;
54
  }
55

    
56
  /**
57
   * Helper function to find a default value.
58
   */
59
  function date_default_value($prefix, $options = NULL) {
60
    $default_date = '';
61
    if (empty($options)) {
62
      $options = $this->options;
63
    }
64
    // If this is a remembered value, use the value from the SESSION.
65
    if (!empty($this->options['expose']['remember'])) {
66
      $display_id = ($this->view->display_handler->is_defaulted('filters')) ? 'default' : $this->view->current_display;
67
      if (!empty($_SESSION['views'][$this->view->name][$display_id][$this->options['expose']['identifier']][$prefix])) {
68
        return $_SESSION['views'][$this->view->name][$display_id][$this->options['expose']['identifier']][$prefix];
69
      }
70
    }
71

    
72
    // This is a date that needs to be constructed from options like 'now' .
73
    $default_option = $prefix == 'max' ? $options['default_to_date'] : $options['default_date'];
74
    if (!empty($default_option)) {
75
      str_replace('now', 'today', $default_option);
76
      $date = date_create($default_option, date_default_timezone_object());
77
      $default_date = !empty($date) ? $date->format($this->format) : '';
78

    
79
      // The format for our filter is in ISO format, but the widget will need it in datetime format.
80
      $default_date = str_replace('T', ' ', $default_date);
81
    }
82
    // This a fixed date.
83
    else {
84
      $default_date = $options['value'][$prefix];
85
    }
86
    return $default_date;
87
  }
88

    
89
  /**
90
   * Helper function to see if we need to swap in the default value.
91
   *
92
   * Views exposed filters treat everything as submitted, so if it's an empty value we have to
93
   * see if anything actually was submitted. If nothing has really been submitted, we need
94
   * to swap in our default value logic.
95
   */
96
  function get_filter_value($prefix, $input) {
97
    // All our date widgets provide datetime values but we use ISO in our SQL
98
    // for consistency between the way filters and arguments work (arguments
99
    // cannot contain spaces).
100
    if (empty($input)) {
101
      if (empty($this->options['exposed'])) {
102
        return str_replace(' ', 'T', $this->date_default_value($prefix));
103
      }
104
      elseif (isset($this->options['expose']['identifier']) && !isset($_GET[$this->options['expose']['identifier']])) {
105
        return str_replace(' ', 'T', $this->date_default_value($prefix));
106
      }
107
    }
108

    
109
    return str_replace(' ', 'T', $input);
110
  }
111

    
112
  function accept_exposed_input($input) {
113
    if (!empty($this->options['exposed'])) {
114
      $element_input = $input[$this->options['expose']['identifier']];
115
      $element_input['value'] = $this->get_filter_value('value', !empty($element_input['value']) ? $element_input['value'] : '');
116
      $element_input['min'] = $this->get_filter_value('min', !empty($element_input['min']) ? $element_input['min'] : '');
117
      $element_input['max'] = $this->get_filter_value('max', !empty($element_input['max']) ? $element_input['max'] : '');
118
      if (is_array($element_input) && isset($element_input['default_date'])) {
119
        unset($element_input['default_date']);
120
      }
121
      if (is_array($element_input) && isset($element_input['default_to_date'])) {
122
        unset($element_input['default_to_date']);
123
      }
124

    
125
      $input[$this->options['expose']['identifier']] = $element_input;
126
    }
127
    return parent::accept_exposed_input($input);
128

    
129
  }
130

    
131
  function op_between($field) {
132

    
133
    // Add the delta field to the view so we can later find the value that matched our query.
134
    list($table_name, $field_name) = explode('.', $field);
135
    if (!empty($this->options['add_delta']) && (substr($field_name, -6) == '_value' || substr($field_name, -7) == '_value2')) {
136
      $this->query->add_field($table_name, 'delta');
137
      $real_field_name = str_replace(array('_value', '_value2'), '', $this->real_field);
138
      $this->query->add_field($table_name, 'entity_id', 'date_id_' . $real_field_name);
139
      $this->query->add_field($table_name, 'delta', 'date_delta_' . $real_field_name);
140
    }
141

    
142
    $min_value = $this->get_filter_value('min', $this->value['min']);
143
    $min_comp_date = new DateObject($min_value, date_default_timezone(), $this->format);
144
    $max_value = $this->get_filter_value('max', $this->value['max']);
145
    $max_comp_date = new DateObject($max_value, date_default_timezone(), $this->format);
146
    $field_min = $this->date_handler->sql_field($field, NULL, $min_comp_date);
147
    $field_min = $this->date_handler->sql_format($this->format, $field_min);
148
    $field_max = $this->date_handler->sql_field($field, NULL, $max_comp_date);
149
    $field_max = $this->date_handler->sql_format($this->format, $field_max);
150
    $placeholder_min = $this->placeholder();
151
    $placeholder_max = $this->placeholder();
152
    $group = !empty($this->options['date_group']) ? $this->options['date_group'] : $this->options['group'];
153
    if ($this->operator == 'between') {
154
      $this->query->add_where_expression($group, "$field_min >= $placeholder_min AND $field_max <= $placeholder_max", array($placeholder_min => $min_value, $placeholder_max => $max_value));
155
    }
156
    else {
157
      $this->query->add_where_expression($group, "$field_min < $placeholder_min OR $field_max > $placeholder_max", array($placeholder_min => $min_value, $placeholder_max => $max_value));
158
    }
159
  }
160

    
161
  function op_simple($field) {
162

    
163
    // Add the delta field to the view so we can later find the value that matched our query.
164
    list($table_name, $field_name) = explode('.', $field);
165
    if (!empty($this->options['add_delta']) && (substr($field_name, -6) == '_value' || substr($field_name, -7) == '_value2')) {
166
      $this->query->add_field($table_name, 'delta');
167
      $real_field_name = str_replace(array('_value', '_value2'), '', $this->real_field);
168
      $this->query->add_field($table_name, 'entity_id', 'date_id_' . $real_field_name);
169
      $this->query->add_field($table_name, 'delta', 'date_delta_' . $real_field_name);
170
    }
171

    
172
    $value = $this->get_filter_value('value', $this->value['value']);
173
    $comp_date = new DateObject($value, date_default_timezone(), $this->format);
174
    $field = $this->date_handler->sql_field($field, NULL, $comp_date);
175
    $field = $this->date_handler->sql_format($this->format, $field);
176
    $placeholder = $this->placeholder();
177
    $group = !empty($this->options['date_group']) ? $this->options['date_group'] : $this->options['group'];
178
    $this->query->add_where_expression($group, "$field $this->operator $placeholder", array($placeholder => $value));
179
  }
180

    
181
  function op_contains($field) {
182

    
183
    // Add the delta field to the view so we can later find the value that matched our query.
184
    list($table_name, $field_name) = explode('.', $field);
185
    if (!empty($this->options['add_delta']) && (substr($field_name, -6) == '_value' || substr($field_name, -7) == '_value2')) {
186
      $this->query->add_field($table_name, 'delta');
187
    }
188

    
189
    $value = $this->get_filter_value('value', $this->value['value']);
190
    $comp_date = new DateObject($value, date_default_timezone(), $this->format);
191
    $fields = date_views_fields($this->base_table);
192
    $fields = $fields['name'];
193
    $fromto = $fields[$field]['fromto'];
194
    $field_min = $this->date_handler->sql_field($fromto[0], NULL, $comp_date);
195
    $field_min = $this->date_handler->sql_format($this->format, $field_min);
196
    $field_max = $this->date_handler->sql_field($fromto[1], NULL, $comp_date);
197
    $field_max = $this->date_handler->sql_format($this->format, $field_max);
198
    $placeholder_min = $this->placeholder();
199
    $placeholder_max = $this->placeholder();
200
    $group = !empty($this->options['date_group']) ? $this->options['date_group'] : $this->options['group'];
201
    $this->query->add_where_expression($group, "$field_max >= $placeholder_min AND $field_min <= $placeholder_max", array($placeholder_min => $value, $placeholder_max => $value));
202
  }
203

    
204
  /**
205
   * Set the granularity of the date parts to use in the filter.
206
    */
207
  function has_extra_options() { return TRUE; }
208

    
209
  /**
210
   * Date selection options.
211
   */
212
  function widget_options() {
213
    $options = array(
214
      'date_select' => t('Select'),
215
      'date_text' => t('Text'),
216
      'date_popup' => t('Popup'),
217
      );
218
    if (!module_exists('date_popup')) {
219
      unset($options['date_popup']);
220
    }
221
    return $options;
222
  }
223

    
224
  function year_range() {
225
    $year_range = explode(':', $this->options['year_range']);
226
    if (substr($this->options['year_range'], 0, 1) == '-' || $year_range[0] < 0) {
227
      $this_year = date_format(date_now(), 'Y');
228
      $year_range[0] = $this_year + $year_range[0];
229
      $year_range[1] = $this_year + $year_range[1];
230
    }
231
    return $year_range;
232
  }
233

    
234
  function extra_options_form(&$form, &$form_state) {
235
    parent::extra_options_form($form, $form_state);
236
    $form['form_type'] = array(
237
      '#type' => 'radios',
238
      '#title' => t('Date selection form element'),
239
      '#default_value' => $this->options['form_type'],
240
      '#options' => $this->widget_options(),
241
      );
242

    
243
    $form['granularity'] = $this->date_handler->granularity_form($this->options['granularity']);
244
    $form['granularity']['#title'] = t('Filter granularity');
245

    
246
    $form['year_range'] = array(
247
      '#type' => 'date_year_range',
248
      '#default_value' => $this->options['year_range'],
249
    );
250

    
251
    if (!empty($this->definition['field_name'])) {
252
      $field = field_info_field($this->definition['field_name']);
253
    }
254
    $form['add_delta'] = array(
255
      '#type' => 'radios',
256
      '#title' => t('Add multiple value identifier'),
257
      '#default_value' => $this->options['add_delta'],
258
      '#options' => array('' => t('No'), 'yes' => t('Yes')),
259
      '#description' => t('Add an identifier to the view to show which multiple value date fields meet the filter criteria. Note: This option may introduce duplicate values into the view. Required when using multiple value fields in a Calendar or any time you want the node view of multiple value dates to display only the values that match the view filters.'),
260
      // Only let mere mortals tweak this setting for multi-value fields
261
      '#access' => !empty($field) ? $field['cardinality'] != 1 : 0,
262
    );
263
  }
264

    
265
  function extra_options_validate($form, &$form_state) {
266
    if (!preg_match('/^(?:\-[0-9]{1,4}|[0-9]{4}):(?:[\+|\-][0-9]{1,4}|[0-9]{4})$/', $form_state['values']['options']['year_range'])) {
267
      form_error($form['year_range'], t('Date year range must be in the format -9:+9, 2005:2010, -9:2010, or 2005:+9'));
268
    }
269
  }
270

    
271
  /**
272
   * Add the selectors to the value form using the date handler.
273
   */
274
  function value_form(&$form, &$form_state) {
275
    // We use different values than the parent form, so we must
276
    // construct our own form element.
277
    $form['value'] = array();
278
    $form['value']['#tree'] = TRUE;
279

    
280
    // Below section copied from views_handler_filter_numeric.inc.
281
    $which = 'all';
282
    $source = '';
283
    if (!empty($form['operator'])) {
284
      $source = ($form['operator']['#type'] == 'radios') ? 'radio:options[operator]' : 'edit-options-operator';
285
    }
286

    
287
    $identifier = $this->options['expose']['identifier'];
288
    if (!empty($form_state['exposed'])) {
289

    
290
      if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) {
291
        // exposed and locked.
292
        $which = in_array($this->operator, $this->operator_values(2)) ? 'minmax' : 'value';
293
      }
294
      else {
295
        $source = 'edit-' . drupal_html_id($this->options['expose']['operator_id']);
296
      }
297
    }
298

    
299
    if ($which == 'all' || $which == 'value') {
300
      $form['value'] += $this->date_parts_form($form_state, 'value', $source, $which, $this->operator_values(1), $identifier, 'default_date');
301
    }
302

    
303
    if ($which == 'all' || $which == 'minmax') {
304
      $form['value'] += $this->date_parts_form($form_state, 'min', $source, $which, $this->operator_values(2), $identifier, 'default_date');
305
      $form['value'] += $this->date_parts_form($form_state, 'max', $source, $which, $this->operator_values(2), $identifier, 'default_to_date');
306
    }
307

    
308
    // Add some extra validation for the select widget to be sure that
309
    // the user inputs all parts of the date.
310
    if ($this->options['form_type'] == 'date_select') {
311
      $form['value']['#element_validate'] = array('date_views_select_validate');
312
    }
313

    
314
  }
315

    
316
  /**
317
   * A form element to select date part values.
318
   *
319
   * @param string $prefix
320
   *   A prefix for the date values, 'value', 'min', or 'max' .
321
   * @param string $source
322
   *   The operator for this element.
323
   * @param string $which
324
   *   Which element to provide, 'all', 'value', or 'minmax' .
325
   * @param array $operator_values
326
   *   An array of the allowed operators for this element.
327
   * @param array $identifier
328
   *   Identifier of the exposed element.
329
   * @param array $relative_id
330
   *   Form element id to use for the relative date field.
331
   *
332
   * @return
333
   *   The form date part element for this instance.
334
   */
335
  function date_parts_form($form_state, $prefix, $source, $which, $operator_values, $identifier, $relative_id) {
336
    module_load_include('inc', 'date_api', 'date_api_elements');
337
    switch ($prefix) {
338
      case 'min':
339
        $label = t('Start date');
340
        $relative_label = t('Relative start date');
341
        break;
342
      case 'max':
343
        $label = t('End date');
344
        $relative_label = t('Relative end date');
345
        break;
346
      default:
347
        $label = '';
348
        $relative_label = t('Relative date');
349
        break;
350
    }
351

    
352
    $type = $this->options['form_type'];
353
    if ($type == 'date_popup' && !module_exists('date_popup')) {
354
      $type = 'date_text';
355
    }
356

    
357
    $format = $this->date_handler->views_formats($this->options['granularity'], 'display');
358
    $granularity = array_keys($this->date_handler->date_parts($this->options['granularity']));
359
    $relative_value = ($prefix == 'max' ? $this->options['default_to_date'] : $this->options['default_date']);
360

    
361
    if (!empty($form_state['exposed'])) {
362
      // UI when the date selector is exposed.
363
      $default_date = $this->date_default_value($prefix);
364
      $id = 'edit-' . str_replace('_', '-', $this->field) . '-' . $prefix;
365
      $form[$prefix] = array(
366
        '#title' => check_plain($label),
367
        '#type' => $type,
368
        '#size' => 20,
369
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
370
        '#date_format' => date_limit_format($format, $granularity),
371
        '#date_label_position' => 'within',
372
        '#date_year_range' => $this->options['year_range'],
373
        '#process' => array($type . '_element_process'),
374
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '-inside-wrapper">',
375
        '#suffix' => '</div></div>',
376
      );
377
      if ($which == 'all') {
378
        $form[$prefix]['#pre_render'][] = 'ctools_dependent_pre_render';
379
        $form[$prefix]['#dependency'] = array($source => $operator_values);
380
      }
381
      if (!isset($form_state['input'][$identifier][$prefix])) {
382
        $form_state['input'][$identifier][$prefix] = $this->value[$prefix];
383
      }
384
    }
385
    else {
386
      // UI when the date selector is on the views configuration screen.
387
      $default_date = '';
388
      $id = 'edit-options-value-' . $prefix;
389
      $form[$prefix . '_group'] = array(
390
        '#type' => 'fieldset',
391
        '#attributes' => array('class' => array('date-views-filter-fieldset')),
392
      );
393
      $form[$prefix . '_group'][$prefix . '_choose_input_type'] = array(
394
        '#title' => check_plain($label),
395
        '#type' => 'select',
396
        '#options' => array('date' => t('Select a date'), 'relative' => ('Enter a relative date')),
397
        '#attributes' => array('class' => array($prefix . '-choose-input-type')),
398
        '#default_value' => !empty($relative_value) ? 'relative' : 'date',
399
      );
400
      $form[$prefix . '_group'][$prefix] = array(
401
        '#title' => t('Select a date'),
402
        '#type' => $type,
403
        '#size' => 20,
404
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
405
        '#date_format' => date_limit_format($format, $granularity),
406
        '#date_label_position' => 'within',
407
        '#date_year_range' => $this->options['year_range'],
408
        '#process' => array($type . '_element_process'),
409
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '-inside-wrapper">',
410
        '#suffix' => '</div></div>',
411
        '#states' => array(
412
          'visible' => array(
413
            ":input.{$prefix}-choose-input-type" => array('value' => 'date'),
414
          ),
415
        ),
416
      );
417
      $form[$prefix . '_group'][$relative_id] = array(
418
        '#type' => 'textfield',
419
        '#title' => check_plain($relative_label),
420
        '#default_value' => $relative_value,
421
        '#description' => t("Relative dates are computed when the view is displayed. Examples: now, now +1 day, 12AM today, Monday next week. <a href=\"@relative_format\">More examples of relative date formats in the PHP documentation</a>.", array('@relative_format' => 'http://www.php.net/manual/en/datetime.formats.relative.php')),
422
        '#states' => array(
423
          'visible' => array(
424
            ":input.{$prefix}-choose-input-type" => array('value' => 'relative'),
425
          ),
426
        ),
427
      );
428
      if ($which == 'all') {
429
        $form[$prefix . '_group']['#pre_render'][] = 'ctools_dependent_pre_render';
430
        $form[$prefix . '_group']['#dependency'] = array($source => $operator_values);
431
      }
432
    }
433
    return $form;
434
  }
435

    
436
  /**
437
   * Value validation.
438
   *
439
   * TODO add in more validation.
440
   *
441
   * We are setting an extra option using a value form
442
   * because it makes more sense to set it there.
443
   * That's not the normal method, so we have to manually
444
   * transfer the selected value back to the option.
445
   */
446
  function value_validate($form, &$form_state) {
447

    
448
    $options = &$form_state['values']['options'];
449

    
450
    if ($options['operator'] == 'between' || $options['operator'] == 'not between') {
451
      if ($options['value']['min_group']['min_choose_input_type'] == 'relative') {
452
        if (empty($options['value']['min_group']['default_date'])) {
453
          form_set_error('options][value][min_group][default_date', t('Relative start date not specified.'));
454
        }
455
        else {
456
          $this->options['default_date'] = $options['value']['min_group']['default_date'];
457
          // NULL out the value field, user wanted the relative value to take hold.
458
          $options['value']['min_group']['min'] = NULL;
459
        }
460
      }
461
      // If an absolute date was used, be sure to wipe the relative date.
462
      else {
463
        $this->options['default_date'] = '';
464
      }
465
      if ($options['value']['max_group']['max_choose_input_type'] == 'relative') {
466
        if (empty($options['value']['max_group']['default_to_date'])) {
467
          form_set_error('options][value][max_group][default_to_date', t('Relative end date not specified.'));
468
        }
469
        else {
470
          $this->options['default_to_date'] = $options['value']['max_group']['default_to_date'];
471
          // NULL out the value field, user wanted the relative value to take hold.
472
          $options['value']['max_group']['max'] = NULL;
473
        }
474
      }
475
      // If an absolute date was used, be sure to wipe the relative date.
476
      else {
477
        $this->options['default_to_date'] = '';
478
      }
479
    }
480
    elseif (in_array($options['operator'], array('<', '<=', '=', '!=', '>=', '>'))) {
481
      if ($options['value']['value_group']['value_choose_input_type'] == 'relative') {
482
        if (empty($options['value']['value_group']['default_date'])) {
483
          form_set_error('options][value][value_group][default_date', t('Relative date not specified.'));
484
        }
485
        else {
486
          $this->options['default_date'] = $options['value']['value_group']['default_date'];
487
          // NULL out the value field, user wanted the relative value to take hold.
488
          $options['value']['value_group']['value'] = NULL;
489
        }
490
      }
491
      // If an absolute date was used, be sure to wipe the relative date.
492
      else {
493
        $this->options['default_date'] = '';
494
      }
495
    }
496
    // Flatten the form structure for views, so the values can be saved.
497
    foreach (array('value', 'min', 'max') as $key) {
498
      $options['value'][$key] = $options['value'][$key . '_group'][$key];
499
    }
500
  }
501

    
502
  /**
503
   * Validate that the time values convert to something usable.
504
   */
505
  function validate_valid_time(&$form, $operator, $value) {
506
    // Override the core date filter validation.
507
    // Our date widgets do their own validation.
508
  }
509

    
510
  // Update the summary values to provide
511
  // meaningful information for each option.
512
  function admin_summary() {
513
    $parts = $this->date_handler->date_parts();
514
    $widget_options = $this->widget_options();
515
    // If the filter is exposed, display the granularity.
516
    if ($this->options['exposed']) {
517
      return t('<strong>Exposed</strong> @widget @format', array('@format' => $parts[$this->date_handler->granularity], '@widget' => $widget_options[$this->options['form_type']]));
518
    }
519
    // If not exposed, display the value.
520
    $output = '';
521
    if (in_array($this->operator, $this->operator_values(2))) {
522
      $min = check_plain(!empty($this->options['default_date']) ? $this->options['default_date'] : $this->options['value']['min']);
523
      $max = check_plain(!empty($this->options['default_to_date']) ? $this->options['default_to_date'] : $this->options['value']['max']);
524
      $output .= t('@min and @max', array('@min' => $min, '@max' => $max));
525
    }
526
    else {
527
      $output .= check_plain(!empty($this->options['default_date']) ? $this->options['default_date'] : $this->options['value']['value']);
528
    }
529
    return $output;
530
  }
531

    
532
}