Projet

Général

Profil

Paste
Télécharger (19,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / plugins / views_plugin_style.inc @ 7547bb19

1
<?php
2

    
3
/**
4
 * @file
5
 * Definition of views_plugin_style.
6
 */
7

    
8
/**
9
 * @defgroup views_style_plugins Views style plugins
10
 * @{
11
 * Style plugins control how a view is rendered. For example, they
12
 * can choose to display a collection of fields, node_view() output,
13
 * table output, or any kind of crazy output they want.
14
 *
15
 * Many style plugins can have an optional 'row' plugin, that displays
16
 * a single record. Not all style plugins can utilize this, so it is
17
 * up to the plugin to set this up and call through to the row plugin.
18
 *
19
 * @see hook_views_plugins()
20
 */
21

    
22
/**
23
 * Base class to define a style plugin handler.
24
 */
25
class views_plugin_style extends views_plugin {
26
  /**
27
   * Store all available tokens row rows.
28
   */
29
  var $row_tokens = array();
30

    
31
  /**
32
   * Contains the row plugin, if it's initialized
33
   * and the style itself supports it.
34
   *
35
   * @var views_plugin_row
36
   */
37
  var $row_plugin;
38

    
39
  /**
40
   * Initialize a style plugin.
41
   *
42
   * @param $view
43
   * @param $display
44
   * @param $options
45
   *   The style options might come externally as the style can be sourced
46
   *   from at least two locations. If it's not included, look on the display.
47
   */
48
  function init(&$view, &$display, $options = NULL) {
49
    $this->view = &$view;
50
    $this->display = &$display;
51

    
52
    // Overlay incoming options on top of defaults
53
    $this->unpack_options($this->options, isset($options) ? $options : $display->handler->get_option('style_options'));
54

    
55
    if ($this->uses_row_plugin() && $display->handler->get_option('row_plugin')) {
56
      $this->row_plugin = $display->handler->get_plugin('row');
57
    }
58

    
59
    $this->options += array(
60
      'grouping' => array(),
61
    );
62

    
63
    $this->definition += array(
64
      'uses grouping' => TRUE,
65
    );
66
  }
67

    
68
  function destroy() {
69
    parent::destroy();
70

    
71
    if (isset($this->row_plugin)) {
72
      $this->row_plugin->destroy();
73
    }
74
  }
75

    
76
  /**
77
   * Return TRUE if this style also uses a row plugin.
78
   */
79
  function uses_row_plugin() {
80
    return !empty($this->definition['uses row plugin']);
81
  }
82

    
83
  /**
84
   * Return TRUE if this style also uses a row plugin.
85
   */
86
  function uses_row_class() {
87
    return !empty($this->definition['uses row class']);
88
  }
89

    
90
  /**
91
   * Return TRUE if this style also uses fields.
92
   *
93
   * @return bool
94
   */
95
  function uses_fields() {
96
    // If we use a row plugin, ask the row plugin. Chances are, we don't
97
    // care, it does.
98
    $row_uses_fields = FALSE;
99
    if ($this->uses_row_plugin() && !empty($this->row_plugin)) {
100
      $row_uses_fields = $this->row_plugin->uses_fields();
101
    }
102
    // Otherwise, check the definition or the option.
103
    return $row_uses_fields || !empty($this->definition['uses fields']) || !empty($this->options['uses_fields']);
104
  }
105

    
106
  /**
107
   * Return TRUE if this style uses tokens.
108
   *
109
   * Used to ensure we don't fetch tokens when not needed for performance.
110
   */
111
  function uses_tokens() {
112
    if ($this->uses_row_class()) {
113
      $class = $this->options['row_class'];
114
      if (strpos($class, '[') !== FALSE || strpos($class, '!') !== FALSE || strpos($class, '%') !== FALSE) {
115
        return TRUE;
116
      }
117
    }
118
  }
119

    
120
  /**
121
   * Return the token replaced row class for the specified row.
122
   */
123
  function get_row_class($row_index) {
124
    if ($this->uses_row_class()) {
125
      $class = $this->options['row_class'];
126

    
127
      if ($this->uses_fields() && $this->view->field) {
128
        $classes = array();
129

    
130
        // Explode the value by whitespace, this allows the function to handle
131
        // a single class name and multiple class names that are then tokenized.
132
        foreach(explode(' ', $class) as $token_class) {
133
          $classes[] = strip_tags($this->tokenize_value($token_class, $row_index));
134
        }
135
      }
136
      else {
137
        $classes = explode(' ', $class);
138
      }
139

    
140
      // Convert whatever the result is to a nice clean class name
141
      foreach ($classes as &$class) {
142
        $class = drupal_html_class($class);
143
      }
144
      return implode(' ', $classes);
145
    }
146
  }
147

    
148
  /**
149
   * Take a value and apply token replacement logic to it.
150
   */
151
  function tokenize_value($value, $row_index) {
152
    if (strpos($value, '[') !== FALSE || strpos($value, '!') !== FALSE || strpos($value, '%') !== FALSE) {
153
      $fake_item = array(
154
        'alter_text' => TRUE,
155
        'text' => $value,
156
      );
157

    
158
      // Row tokens might be empty, for example for node row style.
159
      $tokens = isset($this->row_tokens[$row_index]) ? $this->row_tokens[$row_index] : array();
160
      if (!empty($this->view->build_info['substitutions'])) {
161
        $tokens += $this->view->build_info['substitutions'];
162
      }
163

    
164
      if ($tokens) {
165
        $value = strtr($value, $tokens);
166
      }
167
    }
168

    
169
    return $value;
170
  }
171

    
172
  /**
173
   * Should the output of the style plugin be rendered even if it's a empty view.
174
   */
175
  function even_empty() {
176
    return !empty($this->definition['even empty']);
177
  }
178

    
179
  function option_definition() {
180
    $options = parent::option_definition();
181
    $options['grouping'] = array('default' => array());
182
    if ($this->uses_row_class()) {
183
      $options['row_class'] = array('default' => '');
184
      $options['default_row_class'] = array('default' => TRUE, 'bool' => TRUE);
185
      $options['row_class_special'] = array('default' => TRUE, 'bool' => TRUE);
186
    }
187
    $options['uses_fields'] = array('default' => FALSE, 'bool' => TRUE);
188

    
189
    return $options;
190
  }
191

    
192
  function options_form(&$form, &$form_state) {
193
    parent::options_form($form, $form_state);
194
    // Only fields-based views can handle grouping.  Style plugins can also exclude
195
    // themselves from being groupable by setting their "use grouping" definition
196
    // key to FALSE.
197
    // @TODO: Document "uses grouping" in docs.php when docs.php is written.
198
    if ($this->uses_fields() && $this->definition['uses grouping']) {
199
      $options = array('' => t('- None -'));
200
      $field_labels = $this->display->handler->get_field_labels(TRUE);
201
      $options += $field_labels;
202
      // If there are no fields, we can't group on them.
203
      if (count($options) > 1) {
204
        // This is for backward compatibility, when there was just a single select form.
205
        if (is_string($this->options['grouping'])) {
206
          $grouping = $this->options['grouping'];
207
          $this->options['grouping'] = array();
208
          $this->options['grouping'][0]['field'] = $grouping;
209
        }
210
        if (isset($this->options['group_rendered']) && is_string($this->options['group_rendered'])) {
211
          $this->options['grouping'][0]['rendered'] = $this->options['group_rendered'];
212
          unset($this->options['group_rendered']);
213
        }
214

    
215
        $c = count($this->options['grouping']);
216
        // Add a form for every grouping, plus one.
217
        for ($i = 0; $i <= $c; $i++) {
218
          $grouping = !empty($this->options['grouping'][$i]) ? $this->options['grouping'][$i] : array();
219
          $grouping += array('field' => '', 'rendered' => TRUE, 'rendered_strip' => FALSE);
220
          $form['grouping'][$i]['field'] = array(
221
            '#type' => 'select',
222
            '#title' => t('Grouping field Nr.@number', array('@number' => $i + 1)),
223
            '#options' => $options,
224
            '#default_value' => $grouping['field'],
225
            '#description' => t('You may optionally specify a field by which to group the records. Leave blank to not group.'),
226
          );
227
          $form['grouping'][$i]['rendered'] = array(
228
            '#type' => 'checkbox',
229
            '#title' => t('Use rendered output to group rows'),
230
            '#default_value' => $grouping['rendered'],
231
            '#description' => t('If enabled the rendered output of the grouping field is used to group the rows.'),
232
            '#dependency' => array(
233
              'edit-style-options-grouping-' . $i . '-field' => array_keys($field_labels),
234
            )
235
          );
236
          $form['grouping'][$i]['rendered_strip'] = array(
237
            '#type' => 'checkbox',
238
            '#title' => t('Remove tags from rendered output'),
239
            '#default_value' => $grouping['rendered_strip'],
240
            '#dependency' => array(
241
              'edit-style-options-grouping-' . $i . '-field' => array_keys($field_labels),
242
            )
243
          );
244
        }
245
      }
246
    }
247

    
248
    if ($this->uses_row_class()) {
249
      $form['row_class'] = array(
250
        '#title' => t('Row class'),
251
        '#description' => t('The class to provide on each row.'),
252
        '#type' => 'textfield',
253
        '#default_value' => $this->options['row_class'],
254
      );
255

    
256
      if ($this->uses_fields()) {
257
        $form['row_class']['#description'] .= ' ' . t('You may use field tokens from as per the "Replacement patterns" used in "Rewrite the output of this field" for all fields.');
258
      }
259

    
260
      $form['default_row_class'] = array(
261
        '#title' => t('Add views row classes'),
262
        '#description' => t('Add the default row classes like views-row-1 to the output. You can use this to quickly reduce the amount of markup the view provides by default, at the cost of making it more difficult to apply CSS.'),
263
        '#type' => 'checkbox',
264
        '#default_value' => $this->options['default_row_class'],
265
      );
266
      $form['row_class_special'] = array(
267
        '#title' => t('Add striping (odd/even), first/last row classes'),
268
        '#description' => t('Add css classes to the first and last line, as well as odd/even classes for striping.'),
269
        '#type' => 'checkbox',
270
        '#default_value' => $this->options['row_class_special'],
271
      );
272
    }
273

    
274
    if (!$this->uses_fields() || !empty($this->options['uses_fields'])) {
275
      $form['uses_fields'] = array(
276
        '#type' => 'checkbox',
277
        '#title' => t('Force using fields'),
278
        '#description' => t('If neither the row nor the style plugin supports fields, this field allows to enable them, so you can for example use groupby.'),
279
        '#default_value' => $this->options['uses_fields'],
280
      );
281
    }
282
  }
283

    
284
  function options_validate(&$form, &$form_state) {
285
    // Don't run validation on style plugins without the grouping setting.
286
    if (isset($form_state['values']['style_options']['grouping'])) {
287
      // Don't save grouping if no field is specified.
288
      foreach ($form_state['values']['style_options']['grouping'] as $index => $grouping) {
289
        if (empty($grouping['field'])) {
290
          unset($form_state['values']['style_options']['grouping'][$index]);
291
        }
292
      }
293
    }
294
  }
295

    
296
  /**
297
   * Called by the view builder to see if this style handler wants to
298
   * interfere with the sorts. If so it should build; if it returns
299
   * any non-TRUE value, normal sorting will NOT be added to the query.
300
   */
301
  function build_sort() { return TRUE; }
302

    
303
  /**
304
   * Called by the view builder to let the style build a second set of
305
   * sorts that will come after any other sorts in the view.
306
   */
307
  function build_sort_post() { }
308

    
309
  /**
310
   * Allow the style to do stuff before each row is rendered.
311
   *
312
   * @param $result
313
   *   The full array of results from the query.
314
   */
315
  function pre_render($result) {
316
    if (!empty($this->row_plugin)) {
317
      $this->row_plugin->pre_render($result);
318
    }
319
  }
320

    
321
  /**
322
   * Render the display in this style.
323
   */
324
  function render() {
325
    if ($this->uses_row_plugin() && empty($this->row_plugin)) {
326
      debug('views_plugin_style_default: Missing row plugin');
327
      return;
328
    }
329

    
330
    // Group the rows according to the grouping instructions, if specified.
331
    $sets = $this->render_grouping(
332
      $this->view->result,
333
      $this->options['grouping'],
334
      TRUE
335
    );
336

    
337
    return $this->render_grouping_sets($sets);
338
  }
339

    
340
  /**
341
   * Render the grouping sets.
342
   *
343
   * Plugins may override this method if they wish some other way of handling
344
   * grouping.
345
   *
346
   * @param $sets
347
   *   Array containing the grouping sets to render.
348
   * @param $level
349
   *   Integer indicating the hierarchical level of the grouping.
350
   *
351
   * @return string
352
   *   Rendered output of given grouping sets.
353
   */
354
  function render_grouping_sets($sets, $level = 0) {
355
    $output = '';
356
    foreach ($sets as $set) {
357
      $row = reset($set['rows']);
358
      // Render as a grouping set.
359
      if (is_array($row) && isset($row['group'])) {
360
        $output .= theme(views_theme_functions('views_view_grouping', $this->view, $this->display),
361
          array(
362
            'view' => $this->view,
363
            'grouping' => $this->options['grouping'][$level],
364
            'grouping_level' => $level,
365
            'rows' => $set['rows'],
366
            'title' => $set['group'])
367
        );
368
      }
369
      // Render as a record set.
370
      else {
371
        if ($this->uses_row_plugin()) {
372
          foreach ($set['rows'] as $index => $row) {
373
            $this->view->row_index = $index;
374
            $set['rows'][$index] = $this->row_plugin->render($row);
375
          }
376
        }
377

    
378
        $output .= theme($this->theme_functions(),
379
          array(
380
            'view' => $this->view,
381
            'options' => $this->options,
382
            'grouping_level' => $level,
383
            'rows' => $set['rows'],
384
            'title' => $set['group'])
385
        );
386
      }
387
    }
388
    unset($this->view->row_index);
389
    return $output;
390
  }
391

    
392
  /**
393
   * Group records as needed for rendering.
394
   *
395
   * @param $records
396
   *   An array of records from the view to group.
397
   * @param $groupings
398
   *   An array of grouping instructions on which fields to group. If empty, the
399
   *   result set will be given a single group with an empty string as a label.
400
   * @param $group_rendered
401
   *   Boolean value whether to use the rendered or the raw field value for
402
   *   grouping. If set to NULL the return is structured as before
403
   *   Views 7.x-3.0-rc2. After Views 7.x-3.0 this boolean is only used if
404
   *   $groupings is an old-style string or if the rendered option is missing
405
   *   for a grouping instruction.
406
   * @return
407
   *   The grouped record set.
408
   *   A nested set structure is generated if multiple grouping fields are used.
409
   *
410
   *   @code
411
   *   array(
412
   *     'grouping_field_1:grouping_1' => array(
413
   *       'group' => 'grouping_field_1:content_1',
414
   *       'rows' => array(
415
   *         'grouping_field_2:grouping_a' => array(
416
   *           'group' => 'grouping_field_2:content_a',
417
   *           'rows' => array(
418
   *             $row_index_1 => $row_1,
419
   *             $row_index_2 => $row_2,
420
   *             // ...
421
   *           )
422
   *         ),
423
   *       ),
424
   *     ),
425
   *     'grouping_field_1:grouping_2' => array(
426
   *       // ...
427
   *     ),
428
   *   )
429
   *   @endcode
430
   */
431
  function render_grouping($records, $groupings = array(), $group_rendered = NULL) {
432
    // This is for backward compatibility, when $groupings was a string containing
433
    // the ID of a single field.
434
    if (is_string($groupings)) {
435
      $rendered = $group_rendered === NULL ? TRUE : $group_rendered;
436
      $groupings = array(array('field' => $groupings, 'rendered' => $rendered));
437
    }
438

    
439
    // Make sure fields are rendered
440
    $this->render_fields($this->view->result);
441
    $sets = array();
442
    if ($groupings) {
443
      foreach ($records as $index => $row) {
444
        // Iterate through configured grouping fields to determine the
445
        // hierarchically positioned set where the current row belongs to.
446
        // While iterating, parent groups, that do not exist yet, are added.
447
        $set = &$sets;
448
        foreach ($groupings as $info) {
449
          $field = $info['field'];
450
          $rendered = isset($info['rendered']) ? $info['rendered'] : $group_rendered;
451
          $rendered_strip = isset($info['rendered_strip']) ? $info['rendered_strip'] : FALSE;
452
          $grouping = '';
453
          $group_content = '';
454
          // Group on the rendered version of the field, not the raw.  That way,
455
          // we can control any special formatting of the grouping field through
456
          // the admin or theme layer or anywhere else we'd like.
457
          if (isset($this->view->field[$field])) {
458
            $group_content = $this->get_field($index, $field);
459
            if ($this->view->field[$field]->options['label']) {
460
              $group_content = $this->view->field[$field]->options['label'] . ': ' . $group_content;
461
            }
462
            if ($rendered) {
463
              $grouping = $group_content;
464
              if ($rendered_strip) {
465
                $group_content = $grouping = strip_tags(htmlspecialchars_decode($group_content));
466
              }
467
            }
468
            else {
469
              $grouping = $this->get_field_value($index, $field);
470
              // Not all field handlers return a scalar value,
471
              // e.g. views_handler_field_field.
472
              if (!is_scalar($grouping)) {
473
                $grouping = md5(serialize($grouping));
474
              }
475
            }
476
          }
477

    
478
          // Create the group if it does not exist yet.
479
          if (empty($set[$grouping])) {
480
            $set[$grouping]['group'] = $group_content;
481
            $set[$grouping]['rows'] = array();
482
          }
483

    
484
          // Move the set reference into the row set of the group we just determined.
485
          $set = &$set[$grouping]['rows'];
486
        }
487
        // Add the row to the hierarchically positioned row set we just determined.
488
        $set[$index] = $row;
489
      }
490
    }
491
    else {
492
      // Create a single group with an empty grouping field.
493
      $sets[''] = array(
494
        'group' => '',
495
        'rows' => $records,
496
      );
497
    }
498

    
499
    // If this parameter isn't explicitly set modify the output to be fully
500
    // backward compatible to code before Views 7.x-3.0-rc2.
501
    // @TODO Remove this as soon as possible e.g. October 2020
502
    if ($group_rendered === NULL) {
503
      $old_style_sets = array();
504
      foreach ($sets as $group) {
505
        $old_style_sets[$group['group']] = $group['rows'];
506
      }
507
      $sets = $old_style_sets;
508
    }
509

    
510
    return $sets;
511
  }
512

    
513
  /**
514
   * Render all of the fields for a given style and store them on the object.
515
   *
516
   * @param $result
517
   *   The result array from $view->result
518
   */
519
  function render_fields($result) {
520
    if (!$this->uses_fields()) {
521
      return;
522
    }
523

    
524
    if (!isset($this->rendered_fields)) {
525
      $this->rendered_fields = array();
526
      $this->view->row_index = 0;
527
      $keys = array_keys($this->view->field);
528

    
529
      // If all fields have a field::access FALSE there might be no fields, so
530
      // there is no reason to execute this code.
531
      if (!empty($keys)) {
532
        foreach ($result as $count => $row) {
533
          $this->view->row_index = $count;
534
          foreach ($keys as $id) {
535
            $this->rendered_fields[$count][$id] = $this->view->field[$id]->theme($row);
536
          }
537

    
538
          $this->row_tokens[$count] = $this->view->field[$id]->get_render_tokens(array());
539
        }
540
      }
541
      unset($this->view->row_index);
542
    }
543

    
544
    return $this->rendered_fields;
545
  }
546

    
547
  /**
548
   * Get a rendered field.
549
   *
550
   * @param $index
551
   *   The index count of the row.
552
   * @param $field
553
   *    The id of the field.
554
   */
555
  function get_field($index, $field) {
556
    if (!isset($this->rendered_fields)) {
557
      $this->render_fields($this->view->result);
558
    }
559

    
560
    if (isset($this->rendered_fields[$index][$field])) {
561
      return $this->rendered_fields[$index][$field];
562
    }
563
  }
564

    
565
  /**
566
  * Get the raw field value.
567
  *
568
  * @param $index
569
  *   The index count of the row.
570
  * @param $field
571
  *    The id of the field.
572
  */
573
  function get_field_value($index, $field) {
574
    $this->view->row_index = $index;
575
    $value = $this->view->field[$field]->get_value($this->view->result[$index]);
576
    unset($this->view->row_index);
577
    return $value;
578
  }
579

    
580
  function validate() {
581
    $errors = parent::validate();
582

    
583
    if ($this->uses_row_plugin()) {
584
      $plugin = $this->display->handler->get_plugin('row');
585
      if (empty($plugin)) {
586
        $errors[] = t('Style @style requires a row style but the row plugin is invalid.', array('@style' => $this->definition['title']));
587
      }
588
      else {
589
        $result = $plugin->validate();
590
        if (!empty($result) && is_array($result)) {
591
          $errors = array_merge($errors, $result);
592
        }
593
      }
594
    }
595
    return $errors;
596
  }
597

    
598
  function query() {
599
    parent::query();
600
    if (isset($this->row_plugin)) {
601
      $this->row_plugin->query();
602
    }
603
  }
604
}
605

    
606
/**
607
 * @}
608
 */