Projet

Général

Profil

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

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

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

    
8
// @codingStandardsIgnoreStart
9
class date_views_filter_handler_simple extends views_handler_filter_date {
10
  var $date_handler = NULL;
11
  var $offset = NULL;
12

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

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

    
33
  }
34

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

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

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

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

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

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

    
111
    return str_replace(' ', 'T', $input);
112
  }
113

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

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

    
131
  }
132

    
133
  function op_between($field) {
134

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

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

    
163
  function op_simple($field) {
164

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

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

    
183
  function op_contains($field) {
184

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

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

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

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

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

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

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

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

    
253
    if (!empty($this->definition['field_name'])) {
254
      $field = field_info_field($this->definition['field_name']);
255
    }
256
    $form['add_delta'] = array(
257
      '#type' => 'radios',
258
      '#title' => t('Add multiple value identifier'),
259
      '#default_value' => $this->options['add_delta'],
260
      '#options' => array('' => t('No'), 'yes' => t('Yes')),
261
      '#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.'),
262
      // Only let mere mortals tweak this setting for multi-value fields
263
      '#access' => !empty($field) ? $field['cardinality'] != 1 : 0,
264
    );
265
  }
266

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

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

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

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

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

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

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

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

    
316
  }
317

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

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

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

    
363
    if (!empty($form_state['exposed'])) {
364
      // UI when the date selector is exposed.
365
      $default_date = $this->date_default_value($prefix);
366
      $id = 'edit-' . str_replace('_', '-', $this->field) . '-' . $prefix;
367
      $form[$prefix] = array(
368
        '#title' => check_plain($label),
369
        '#type' => $type,
370
        '#size' => 20,
371
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
372
        '#date_format' => date_limit_format($format, $granularity),
373
        '#date_label_position' => 'within',
374
        '#date_year_range' => $this->options['year_range'],
375
        '#process' => array($type . '_element_process'),
376
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '-inside-wrapper">',
377
        '#suffix' => '</div></div>',
378
      );
379
      if ($which == 'all') {
380
        $form[$prefix]['#pre_render'][] = 'ctools_dependent_pre_render';
381
        $form[$prefix]['#dependency'] = array($source => $operator_values);
382
      }
383
      if (!isset($form_state['input'][$identifier][$prefix])) {
384
        // Ensure these exist.
385
        foreach ($granularity as $key) {
386
          $form_state['input'][$identifier][$prefix][$key] = NULL;
387
        }
388
      }
389
    }
390
    else {
391
      // UI when the date selector is on the views configuration screen.
392
      $default_date = '';
393
      $id = 'edit-options-value-' . $prefix;
394
      $form[$prefix . '_group'] = array(
395
        '#type' => 'fieldset',
396
        '#attributes' => array('class' => array('date-views-filter-fieldset')),
397
      );
398
      $form[$prefix . '_group'][$prefix . '_choose_input_type'] = array(
399
        '#title' => check_plain($label),
400
        '#type' => 'select',
401
        '#options' => array('date' => t('Select a date'), 'relative' => ('Enter a relative date')),
402
        '#attributes' => array('class' => array($prefix . '-choose-input-type')),
403
        '#default_value' => !empty($relative_value) ? 'relative' : 'date',
404
      );
405
      $form[$prefix . '_group'][$prefix] = array(
406
        '#title' => t('Select a date'),
407
        '#type' => $type,
408
        '#size' => 20,
409
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
410
        '#date_format' => date_limit_format($format, $granularity),
411
        '#date_label_position' => 'within',
412
        '#date_year_range' => $this->options['year_range'],
413
        '#process' => array($type . '_element_process'),
414
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '-inside-wrapper">',
415
        '#suffix' => '</div></div>',
416
        '#states' => array(
417
          'visible' => array(
418
            ":input.{$prefix}-choose-input-type" => array('value' => 'date'),
419
          ),
420
        ),
421
      );
422
      $form[$prefix . '_group'][$relative_id] = array(
423
        '#type' => 'textfield',
424
        '#title' => check_plain($relative_label),
425
        '#default_value' => $relative_value,
426
        '#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')),
427
        '#states' => array(
428
          'visible' => array(
429
            ":input.{$prefix}-choose-input-type" => array('value' => 'relative'),
430
          ),
431
        ),
432
      );
433
      if ($which == 'all') {
434
        $form[$prefix . '_group']['#pre_render'][] = 'ctools_dependent_pre_render';
435
        $form[$prefix . '_group']['#dependency'] = array($source => $operator_values);
436
      }
437
    }
438
    return $form;
439
  }
440

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

    
453
    $options = &$form_state['values']['options'];
454

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

    
507
  /**
508
   * Validate that the time values convert to something usable.
509
   */
510
  function validate_valid_time(&$form, $operator, $value) {
511
    // Override the core date filter validation.
512
    // Our date widgets do their own validation.
513
  }
514

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

    
537
}
538
// @codingStandardsIgnoreEnd