3f145195a3a51adf02b1faa6a8df641100ee8f03
[yaffs-website] / web / core / modules / views / src / Plugin / views / argument / ArgumentPluginBase.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\argument;
4
5 use Drupal\Component\Plugin\DependentPluginInterface;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\NestedArray;
8 use Drupal\Core\Cache\Cache;
9 use Drupal\Core\Cache\CacheableDependencyInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\views\Plugin\views\display\DisplayPluginBase;
13 use Drupal\views\ViewExecutable;
14 use Drupal\views\Plugin\views\HandlerBase;
15 use Drupal\views\Views;
16
17 /**
18  * @defgroup views_argument_handlers Views argument handlers
19  * @{
20  * Handler plugins for Views contextual filters.
21  *
22  * Handler plugins help build the view query object. Views argument handlers
23  * are for contextual filtering.
24  *
25  * Views argument handlers extend
26  * \Drupal\views\Plugin\views\argument\ArgumentPluginBase. They must be
27  * annotated with \Drupal\views\Annotation\ViewsArgument annotation, and they
28  * must be in namespace directory Plugin\views\argument.
29  *
30  * @ingroup views_plugins
31  * @see plugin_api
32  */
33
34 /**
35  * Base class for argument (contextual filter) handler plugins.
36  *
37  * The basic argument works for very simple arguments such as nid and uid
38  *
39  * Definition terms for this handler:
40  * - name field: The field to use for the name to use in the summary, which is
41  *               the displayed output. For example, for the node: nid argument,
42  *               the argument itself is the nid, but node.title is displayed.
43  * - name table: The table to use for the name, should it not be in the same
44  *               table as the argument.
45  * - empty field name: For arguments that can have no value, such as taxonomy
46  *                     which can have "no term", this is the string which
47  *                     will be displayed for this lack of value. Be sure to use
48  *                     $this->t().
49  * - validate type: A little used string to allow an argument to restrict
50  *                  which validator is available to just one. Use the
51  *                  validator ID. This probably should not be used at all,
52  *                  and may disappear or change.
53  * - numeric: If set to TRUE this field is numeric and will use %d instead of
54  *            %s in queries.
55  */
56 abstract class ArgumentPluginBase extends HandlerBase implements CacheableDependencyInterface {
57
58   public $validator = NULL;
59   public $argument = NULL;
60   public $value = NULL;
61
62   /**
63    * The table to use for the name, should it not be in the same table as the argument.
64    * @var string
65    */
66   public $name_table;
67
68   /**
69    * The field to use for the name to use in the summary, which is
70    * the displayed output. For example, for the node: nid argument,
71    * the argument itself is the nid, but node.title is displayed.
72    * @var string
73    */
74   public $name_field;
75
76   /**
77    * Overrides Drupal\views\Plugin\views\HandlerBase:init().
78    */
79   public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
80     parent::init($view, $display, $options);
81
82     if (!empty($this->definition['name field'])) {
83       $this->name_field = $this->definition['name field'];
84     }
85     if (!empty($this->definition['name table'])) {
86       $this->name_table = $this->definition['name table'];
87     }
88   }
89
90   public function isException($arg = NULL) {
91     if (!isset($arg)) {
92       $arg = isset($this->argument) ? $this->argument : NULL;
93     }
94     return !empty($this->options['exception']['value']) && $this->options['exception']['value'] === $arg;
95   }
96
97   public function exceptionTitle() {
98     // If title overriding is off for the exception, return the normal title.
99     if (empty($this->options['exception']['title_enable'])) {
100       return $this->getTitle();
101     }
102     return $this->options['exception']['title'];
103   }
104
105   /**
106    * Determine if the argument needs a style plugin.
107    *
108    * @return bool
109    */
110   public function needsStylePlugin() {
111     $info = $this->defaultActions($this->options['default_action']);
112     $validate_info = $this->defaultActions($this->options['validate']['fail']);
113     return !empty($info['style plugin']) || !empty($validate_info['style plugin']);
114   }
115
116   protected function defineOptions() {
117     $options = parent::defineOptions();
118
119     $options['default_action'] = ['default' => 'ignore'];
120     $options['exception'] = [
121       'contains' => [
122         'value' => ['default' => 'all'],
123         'title_enable' => ['default' => FALSE],
124         'title' => ['default' => 'All'],
125       ],
126     ];
127     $options['title_enable'] = ['default' => FALSE];
128     $options['title'] = ['default' => ''];
129     $options['default_argument_type'] = ['default' => 'fixed'];
130     $options['default_argument_options'] = ['default' => []];
131     $options['default_argument_skip_url'] = ['default' => FALSE];
132     $options['summary_options'] = ['default' => []];
133     $options['summary'] = [
134       'contains' => [
135         'sort_order' => ['default' => 'asc'],
136         'number_of_records' => ['default' => 0],
137         'format' => ['default' => 'default_summary'],
138       ],
139     ];
140     $options['specify_validation'] = ['default' => FALSE];
141     $options['validate'] = [
142       'contains' => [
143         'type' => ['default' => 'none'],
144         'fail' => ['default' => 'not found'],
145       ],
146     ];
147     $options['validate_options'] = ['default' => []];
148
149     return $options;
150   }
151
152   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
153     parent::buildOptionsForm($form, $form_state);
154
155     $argument_text = $this->view->display_handler->getArgumentText();
156
157     $form['#pre_render'][] = [get_class($this), 'preRenderMoveArgumentOptions'];
158
159     $form['description'] = [
160       '#markup' => $argument_text['description'],
161       '#theme_wrappers' => ['container'],
162       '#attributes' => ['class' => ['description']],
163     ];
164
165     $form['no_argument'] = [
166       '#type' => 'details',
167       '#title' => $argument_text['filter value not present'],
168       '#open' => TRUE,
169     ];
170     // Everything in the details is floated, so the last element needs to
171     // clear those floats.
172     $form['no_argument']['clearfix'] = [
173       '#weight' => 1000,
174       '#markup' => '<div class="clearfix"></div>',
175     ];
176     $form['default_action'] = [
177       '#title' => $this->t('Default actions'),
178       '#title_display' => 'invisible',
179       '#type' => 'radios',
180       '#process' => [[$this, 'processContainerRadios']],
181       '#default_value' => $this->options['default_action'],
182       '#fieldset' => 'no_argument',
183     ];
184
185     $form['exception'] = [
186       '#type' => 'details',
187       '#title' => $this->t('Exceptions'),
188       '#fieldset' => 'no_argument',
189     ];
190     $form['exception']['value'] = [
191       '#type' => 'textfield',
192       '#title' => $this->t('Exception value'),
193       '#size' => 20,
194       '#default_value' => $this->options['exception']['value'],
195       '#description' => $this->t('If this value is received, the filter will be ignored; i.e, "all values"'),
196     ];
197     $form['exception']['title_enable'] = [
198       '#type' => 'checkbox',
199       '#title' => $this->t('Override title'),
200       '#default_value' => $this->options['exception']['title_enable'],
201     ];
202     $form['exception']['title'] = [
203       '#type' => 'textfield',
204       '#title' => $this->t('Override title'),
205       '#title_display' => 'invisible',
206       '#size' => 20,
207       '#default_value' => $this->options['exception']['title'],
208       '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field as well as the "arguments" and "raw_arguments" arrays.'),
209       '#states' => [
210         'visible' => [
211           ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
212         ],
213       ],
214     ];
215
216     $options = [];
217     $defaults = $this->defaultActions();
218     $validate_options = [];
219     foreach ($defaults as $id => $info) {
220       $options[$id] = $info['title'];
221       if (empty($info['default only'])) {
222         $validate_options[$id] = $info['title'];
223       }
224       if (!empty($info['form method'])) {
225         $this->{$info['form method']}($form, $form_state);
226       }
227     }
228     $form['default_action']['#options'] = $options;
229
230     $form['argument_present'] = [
231       '#type' => 'details',
232       '#title' => $argument_text['filter value present'],
233       '#open' => TRUE,
234     ];
235     $form['title_enable'] = [
236       '#type' => 'checkbox',
237       '#title' => $this->t('Override title'),
238       '#default_value' => $this->options['title_enable'],
239       '#fieldset' => 'argument_present',
240     ];
241     $form['title'] = [
242       '#type' => 'textfield',
243       '#title' => $this->t('Provide title'),
244       '#title_display' => 'invisible',
245       '#default_value' => $this->options['title'],
246       '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field.'),
247       '#states' => [
248         'visible' => [
249           ':input[name="options[title_enable]"]' => ['checked' => TRUE],
250         ],
251       ],
252       '#fieldset' => 'argument_present',
253     ];
254
255     $output = $this->getTokenHelp();
256     $form['token_help'] = [
257       '#type' => 'details',
258       '#title' => $this->t('Replacement patterns'),
259       '#value' => $output,
260       '#states' => [
261         'visible' => [
262           [
263             ':input[name="options[title_enable]"]' => ['checked' => TRUE],
264           ],
265           [
266             ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
267           ],
268         ],
269       ],
270     ];
271
272     $form['specify_validation'] = [
273       '#type' => 'checkbox',
274       '#title' => $this->t('Specify validation criteria'),
275       '#default_value' => $this->options['specify_validation'],
276       '#fieldset' => 'argument_present',
277     ];
278
279     $form['validate'] = [
280       '#type' => 'container',
281       '#fieldset' => 'argument_present',
282     ];
283     // Validator options include derivatives with :. These are sanitized for js
284     // and reverted on submission.
285     $form['validate']['type'] = [
286       '#type' => 'select',
287       '#title' => $this->t('Validator'),
288       '#default_value' => static::encodeValidatorId($this->options['validate']['type']),
289       '#states' => [
290         'visible' => [
291           ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
292         ],
293       ],
294     ];
295
296     $plugins = Views::pluginManager('argument_validator')->getDefinitions();
297     foreach ($plugins as $id => $info) {
298       if (!empty($info['no_ui'])) {
299         continue;
300       }
301
302       $valid = TRUE;
303       if (!empty($info['type'])) {
304         $valid = FALSE;
305         if (empty($this->definition['validate type'])) {
306           continue;
307         }
308         foreach ((array) $info['type'] as $type) {
309           if ($type == $this->definition['validate type']) {
310             $valid = TRUE;
311             break;
312           }
313         }
314       }
315
316       // If we decide this validator is ok, add it to the list.
317       if ($valid) {
318         $plugin = $this->getPlugin('argument_validator', $id);
319         if ($plugin) {
320           if ($plugin->access() || $this->options['validate']['type'] == $id) {
321             // Sanitize ID for js.
322             $sanitized_id = static::encodeValidatorId($id);
323             $form['validate']['options'][$sanitized_id] = [
324               '#prefix' => '<div id="edit-options-validate-options-' . $sanitized_id . '-wrapper">',
325               '#suffix' => '</div>',
326               '#type' => 'item',
327               // Even if the plugin has no options add the key to the form_state.
328               '#input' => TRUE, // trick it into checking input to make #process run
329               '#states' => [
330                 'visible' => [
331                   ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
332                   ':input[name="options[validate][type]"]' => ['value' => $sanitized_id],
333                 ],
334               ],
335               '#id' => 'edit-options-validate-options-' . $sanitized_id,
336               '#default_value' => [],
337             ];
338             $plugin->buildOptionsForm($form['validate']['options'][$sanitized_id], $form_state);
339             $validate_types[$sanitized_id] = $info['title'];
340           }
341         }
342       }
343     }
344
345     asort($validate_types);
346     $form['validate']['type']['#options'] = $validate_types;
347
348     $form['validate']['fail'] = [
349       '#type' => 'select',
350       '#title' => $this->t('Action to take if filter value does not validate'),
351       '#default_value' => $this->options['validate']['fail'],
352       '#options' => $validate_options,
353       '#states' => [
354         'visible' => [
355           ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
356         ],
357       ],
358       '#fieldset' => 'argument_present',
359     ];
360   }
361
362   /**
363    * Provide token help information for the argument.
364    *
365    * @return array
366    *   A render array.
367    */
368   protected function getTokenHelp() {
369     $output = [];
370
371     foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
372       /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $handler */
373       $options[(string) t('Arguments')]["{{ arguments.$arg }}"] = $this->t('@argument title', ['@argument' => $handler->adminLabel()]);
374       $options[(string) t('Arguments')]["{{ raw_arguments.$arg }}"] = $this->t('@argument input', ['@argument' => $handler->adminLabel()]);
375     }
376
377     // We have some options, so make a list.
378     if (!empty($options)) {
379       $output[] = [
380         '#markup' => '<p>' . $this->t("The following replacement tokens are available for this argument.") . '</p>',
381       ];
382       foreach (array_keys($options) as $type) {
383         if (!empty($options[$type])) {
384           $items = [];
385           foreach ($options[$type] as $key => $value) {
386             $items[] = $key . ' == ' . $value;
387           }
388           $item_list = [
389             '#theme' => 'item_list',
390             '#items' => $items,
391           ];
392           $output[] = $item_list;
393         }
394       }
395     }
396
397     return $output;
398   }
399
400
401   public function validateOptionsForm(&$form, FormStateInterface $form_state) {
402     $option_values = &$form_state->getValue('options');
403     if (empty($option_values)) {
404       return;
405     }
406
407     // Let the plugins do validation.
408     $default_id = $option_values['default_argument_type'];
409     $plugin = $this->getPlugin('argument_default', $default_id);
410     if ($plugin) {
411       $plugin->validateOptionsForm($form['argument_default'][$default_id], $form_state, $option_values['argument_default'][$default_id]);
412     }
413
414     // summary plugin
415     $summary_id = $option_values['summary']['format'];
416     $plugin = $this->getPlugin('style', $summary_id);
417     if ($plugin) {
418       $plugin->validateOptionsForm($form['summary']['options'][$summary_id], $form_state, $option_values['summary']['options'][$summary_id]);
419     }
420
421     $sanitized_id = $option_values['validate']['type'];
422     // Correct ID for js sanitized version.
423     $validate_id = static::decodeValidatorId($sanitized_id);
424     $plugin = $this->getPlugin('argument_validator', $validate_id);
425     if ($plugin) {
426       $plugin->validateOptionsForm($form['validate']['options'][$default_id], $form_state, $option_values['validate']['options'][$sanitized_id]);
427     }
428
429   }
430
431   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
432     $option_values = &$form_state->getValue('options');
433     if (empty($option_values)) {
434       return;
435     }
436
437     // Let the plugins make submit modifications if necessary.
438     $default_id = $option_values['default_argument_type'];
439     $plugin = $this->getPlugin('argument_default', $default_id);
440     if ($plugin) {
441       $options = &$option_values['argument_default'][$default_id];
442       $plugin->submitOptionsForm($form['argument_default'][$default_id], $form_state, $options);
443       // Copy the now submitted options to their final resting place so they get saved.
444       $option_values['default_argument_options'] = $options;
445     }
446
447     // summary plugin
448     $summary_id = $option_values['summary']['format'];
449     $plugin = $this->getPlugin('style', $summary_id);
450     if ($plugin) {
451       $options = &$option_values['summary']['options'][$summary_id];
452       $plugin->submitOptionsForm($form['summary']['options'][$summary_id], $form_state, $options);
453       // Copy the now submitted options to their final resting place so they get saved.
454       $option_values['summary_options'] = $options;
455     }
456
457     // If the 'Specify validation criteria' checkbox is not checked, reset the
458     // validation options.
459     if (empty($option_values['specify_validation'])) {
460       $option_values['validate']['type'] = 'none';
461       // We need to keep the empty array of options for the 'None' plugin as
462       // it will be needed later.
463       $option_values['validate']['options'] = ['none' => []];
464       $option_values['validate']['fail'] = 'not found';
465     }
466
467     $sanitized_id = $option_values['validate']['type'];
468     // Correct ID for js sanitized version.
469     $option_values['validate']['type'] = $validate_id = static::decodeValidatorId($sanitized_id);
470     $plugin = $this->getPlugin('argument_validator', $validate_id);
471     if ($plugin) {
472       $options = &$option_values['validate']['options'][$sanitized_id];
473       $plugin->submitOptionsForm($form['validate']['options'][$sanitized_id], $form_state, $options);
474       // Copy the now submitted options to their final resting place so they get saved.
475       $option_values['validate_options'] = $options;
476     }
477
478     // Clear out the content of title if it's not enabled.
479     if (empty($option_values['title_enable'])) {
480       $option_values['title'] = '';
481     }
482   }
483
484   /**
485    * Provide a list of default behaviors for this argument if the argument
486    * is not present.
487    *
488    * Override this method to provide additional (or fewer) default behaviors.
489    */
490   protected function defaultActions($which = NULL) {
491     $defaults = [
492       'ignore' => [
493         'title' => $this->t('Display all results for the specified field'),
494         'method' => 'defaultIgnore',
495       ],
496       'default' => [
497         'title' => $this->t('Provide default value'),
498         'method' => 'defaultDefault',
499         'form method' => 'defaultArgumentForm',
500         'has default argument' => TRUE,
501         'default only' => TRUE, // this can only be used for missing argument, not validation failure
502       ],
503       'not found' => [
504         'title' => $this->t('Hide view'),
505         'method' => 'defaultNotFound',
506         'hard fail' => TRUE, // This is a hard fail condition
507       ],
508       'summary' => [
509         'title' => $this->t('Display a summary'),
510         'method' => 'defaultSummary',
511         'form method' => 'defaultSummaryForm',
512         'style plugin' => TRUE,
513       ],
514       'empty' => [
515         'title' => $this->t('Display contents of "No results found"'),
516         'method' => 'defaultEmpty',
517       ],
518       'access denied' => [
519         'title' => $this->t('Display "Access Denied"'),
520         'method' => 'defaultAccessDenied',
521       ],
522     ];
523
524     if ($this->view->display_handler->hasPath()) {
525       $defaults['not found']['title'] = $this->t('Show "Page not found"');
526     }
527
528     if ($which) {
529       if (!empty($defaults[$which])) {
530         return $defaults[$which];
531       }
532     }
533     else {
534       return $defaults;
535     }
536   }
537
538   /**
539    * Provide a form for selecting the default argument when the
540    * default action is set to provide default argument.
541    */
542   public function defaultArgumentForm(&$form, FormStateInterface $form_state) {
543     $plugins = Views::pluginManager('argument_default')->getDefinitions();
544     $options = [];
545
546     $form['default_argument_skip_url'] = [
547       '#type' => 'checkbox',
548       '#title' => $this->t('Skip default argument for view URL'),
549       '#default_value' => $this->options['default_argument_skip_url'],
550       '#description' => $this->t('Select whether to include this default argument when constructing the URL for this view. Skipping default arguments is useful e.g. in the case of feeds.')
551     ];
552
553     $form['default_argument_type'] = [
554       '#prefix' => '<div id="edit-options-default-argument-type-wrapper">',
555       '#suffix' => '</div>',
556       '#type' => 'select',
557       '#id' => 'edit-options-default-argument-type',
558       '#title' => $this->t('Type'),
559       '#default_value' => $this->options['default_argument_type'],
560       '#states' => [
561         'visible' => [
562           ':input[name="options[default_action]"]' => ['value' => 'default'],
563         ],
564       ],
565       // Views custom key, moves this element to the appropriate container
566       // under the radio button.
567       '#argument_option' => 'default',
568     ];
569
570     foreach ($plugins as $id => $info) {
571       if (!empty($info['no_ui'])) {
572         continue;
573       }
574       $plugin = $this->getPlugin('argument_default', $id);
575       if ($plugin) {
576         if ($plugin->access() || $this->options['default_argument_type'] == $id) {
577           $form['argument_default']['#argument_option'] = 'default';
578           $form['argument_default'][$id] = [
579             '#prefix' => '<div id="edit-options-argument-default-options-' . $id . '-wrapper">',
580             '#suffix' => '</div>',
581             '#id' => 'edit-options-argument-default-options-' . $id,
582             '#type' => 'item',
583             // Even if the plugin has no options add the key to the form_state.
584             '#input' => TRUE,
585             '#states' => [
586               'visible' => [
587                 ':input[name="options[default_action]"]' => ['value' => 'default'],
588                 ':input[name="options[default_argument_type]"]' => ['value' => $id],
589               ],
590             ],
591             '#default_value' => [],
592           ];
593           $options[$id] = $info['title'];
594           $plugin->buildOptionsForm($form['argument_default'][$id], $form_state);
595         }
596       }
597     }
598
599     asort($options);
600     $form['default_argument_type']['#options'] = $options;
601   }
602
603   /**
604    * Provide a form for selecting further summary options when the
605    * default action is set to display one.
606    */
607   public function defaultSummaryForm(&$form, FormStateInterface $form_state) {
608     $style_plugins = Views::pluginManager('style')->getDefinitions();
609     $summary_plugins = [];
610     $format_options = [];
611     foreach ($style_plugins as $key => $plugin) {
612       if (isset($plugin['display_types']) && in_array('summary', $plugin['display_types'])) {
613         $summary_plugins[$key] = $plugin;
614         $format_options[$key] = $plugin['title'];
615       }
616     }
617
618     $form['summary'] = [
619       // Views custom key, moves this element to the appropriate container
620       // under the radio button.
621       '#argument_option' => 'summary',
622     ];
623     $form['summary']['sort_order'] = [
624       '#type' => 'radios',
625       '#title' => $this->t('Sort order'),
626       '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
627       '#default_value' => $this->options['summary']['sort_order'],
628       '#states' => [
629         'visible' => [
630           ':input[name="options[default_action]"]' => ['value' => 'summary'],
631         ],
632       ],
633     ];
634     $form['summary']['number_of_records'] = [
635       '#type' => 'radios',
636       '#title' => $this->t('Sort by'),
637       '#default_value' => $this->options['summary']['number_of_records'],
638       '#options' => [
639         0 => $this->getSortName(),
640         1 => $this->t('Number of records')
641       ],
642       '#states' => [
643         'visible' => [
644           ':input[name="options[default_action]"]' => ['value' => 'summary'],
645         ],
646       ],
647     ];
648
649     $form['summary']['format'] = [
650       '#type' => 'radios',
651       '#title' => $this->t('Format'),
652       '#options' => $format_options,
653       '#default_value' => $this->options['summary']['format'],
654       '#states' => [
655         'visible' => [
656           ':input[name="options[default_action]"]' => ['value' => 'summary'],
657         ],
658       ],
659     ];
660
661     foreach ($summary_plugins as $id => $info) {
662       $plugin = $this->getPlugin('style', $id);
663       if (!$plugin->usesOptions()) {
664         continue;
665       }
666       if ($plugin) {
667         $form['summary']['options'][$id] = [
668           '#prefix' => '<div id="edit-options-summary-options-' . $id . '-wrapper">',
669           '#suffix' => '</div>',
670           '#id' => 'edit-options-summary-options-' . $id,
671           '#type' => 'item',
672           '#input' => TRUE, // trick it into checking input to make #process run
673           '#states' => [
674             'visible' => [
675               ':input[name="options[default_action]"]' => ['value' => 'summary'],
676               ':input[name="options[summary][format]"]' => ['value' => $id],
677             ],
678           ],
679           '#default_value' => [],
680         ];
681         $options[$id] = $info['title'];
682         $plugin->buildOptionsForm($form['summary']['options'][$id], $form_state);
683       }
684     }
685   }
686
687   /**
688    * Handle the default action, which means our argument wasn't present.
689    *
690    * Override this method only with extreme care.
691    *
692    * @return
693    *   A boolean value; if TRUE, continue building this view. If FALSE,
694    *   building the view will be aborted here.
695    */
696   public function defaultAction($info = NULL) {
697     if (!isset($info)) {
698       $info = $this->defaultActions($this->options['default_action']);
699     }
700
701     if (!$info) {
702       return FALSE;
703     }
704
705     if (!empty($info['method args'])) {
706       return call_user_func_array([&$this, $info['method']], $info['method args']);
707     }
708     else {
709       return $this->{$info['method']}();
710     }
711   }
712
713   /**
714    * How to act if validation fails.
715    */
716   public function validateFail() {
717     $info = $this->defaultActions($this->options['validate']['fail']);
718     return $this->defaultAction($info);
719   }
720   /**
721    * Default action: ignore.
722    *
723    * If an argument was expected and was not given, in this case, simply
724    * ignore the argument entirely.
725    */
726   public function defaultIgnore() {
727     return TRUE;
728   }
729
730   /**
731    * Default action: not found.
732    *
733    * If an argument was expected and was not given, in this case, report
734    * the view as 'not found' or hide it.
735    */
736   protected function defaultNotFound() {
737     // Set a failure condition and let the display manager handle it.
738     $this->view->build_info['fail'] = TRUE;
739     return FALSE;
740   }
741
742   /**
743    * Default action: access denied.
744    *
745    * If an argument was expected and was not given, in this case, report
746    * the view as 'access denied'.
747    */
748   public function defaultAccessDenied() {
749     $this->view->build_info['denied'] = TRUE;
750     return FALSE;
751   }
752
753   /**
754    * Default action: empty
755    *
756    * If an argument was expected and was not given, in this case, display
757    * the view's empty text
758    */
759   public function defaultEmpty() {
760     // We return with no query; this will force the empty text.
761     $this->view->built = TRUE;
762     $this->view->executed = TRUE;
763     $this->view->result = [];
764     return FALSE;
765   }
766
767   /**
768    * This just returns true. The view argument builder will know where
769    * to find the argument from.
770    */
771   protected function defaultDefault() {
772     return TRUE;
773   }
774
775   /**
776    * Determine if the argument is set to provide a default argument.
777    */
778   public function hasDefaultArgument() {
779     $info = $this->defaultActions($this->options['default_action']);
780     return !empty($info['has default argument']);
781   }
782
783   /**
784    * Get a default argument, if available.
785    */
786   public function getDefaultArgument() {
787     $plugin = $this->getPlugin('argument_default');
788     if ($plugin) {
789       return $plugin->getArgument();
790     }
791   }
792
793   /**
794    * Process the summary arguments for display.
795    *
796    * For example, the validation plugin may want to alter an argument for use in
797    * the URL.
798    */
799   public function processSummaryArguments(&$args) {
800     if ($this->options['validate']['type'] != 'none') {
801       if (isset($this->validator) || $this->validator = $this->getPlugin('argument_validator')) {
802         $this->validator->processSummaryArguments($args);
803       }
804     }
805   }
806
807   /**
808    * Default action: summary.
809    *
810    * If an argument was expected and was not given, in this case, display
811    * a summary query.
812    */
813   protected function defaultSummary() {
814     $this->view->build_info['summary'] = TRUE;
815     $this->view->build_info['summary_level'] = $this->options['id'];
816
817     // Change the display style to the summary style for this
818     // argument.
819     $this->view->style_plugin = Views::pluginManager("style")->createInstance($this->options['summary']['format']);
820     $this->view->style_plugin->init($this->view, $this->displayHandler, $this->options['summary_options']);
821
822     // Clear out the normal primary field and whatever else may have
823     // been added and let the summary do the work.
824     $this->query->clearFields();
825     $this->summaryQuery();
826
827     $by = $this->options['summary']['number_of_records'] ? 'num_records' : NULL;
828     $this->summarySort($this->options['summary']['sort_order'], $by);
829
830     // Summaries have their own sorting and fields, so tell the View not
831     // to build these.
832     $this->view->build_sort = FALSE;
833     return TRUE;
834   }
835
836   /**
837    * Build the info for the summary query.
838    *
839    * This must:
840    * - addGroupBy: group on this field in order to create summaries.
841    * - addField: add a 'num_nodes' field for the count. Usually it will
842    *   be a count on $view->base_field
843    * - setCountField: Reset the count field so we get the right paging.
844    *
845    * @return
846    *   The alias used to get the number of records (count) for this entry.
847    */
848   protected function summaryQuery() {
849     $this->ensureMyTable();
850     // Add the field.
851     $this->base_alias = $this->query->addField($this->tableAlias, $this->realField);
852
853     $this->summaryNameField();
854     return $this->summaryBasics();
855   }
856
857   /**
858    * Add the name field, which is the field displayed in summary queries.
859    * This is often used when the argument is numeric.
860    */
861   protected function summaryNameField() {
862     // Add the 'name' field. For example, if this is a uid argument, the
863     // name field would be 'name' (i.e, the username).
864
865     if (isset($this->name_table)) {
866       // if the alias is different then we're probably added, not ensured,
867       // so look up the join and add it instead.
868       if ($this->tableAlias != $this->name_table) {
869         $j = HandlerBase::getTableJoin($this->name_table, $this->table);
870         if ($j) {
871           $join = clone $j;
872           $join->leftTable = $this->tableAlias;
873           $this->name_table_alias = $this->query->addTable($this->name_table, $this->relationship, $join);
874         }
875       }
876       else {
877         $this->name_table_alias = $this->query->ensureTable($this->name_table, $this->relationship);
878       }
879     }
880     else {
881       $this->name_table_alias = $this->tableAlias;
882     }
883
884     if (isset($this->name_field)) {
885       $this->name_alias = $this->query->addField($this->name_table_alias, $this->name_field);
886     }
887     else {
888       $this->name_alias = $this->base_alias;
889     }
890   }
891
892   /**
893    * Some basic summary behavior that doesn't need to be repeated as much as
894    * code that goes into summaryQuery()
895    */
896   public function summaryBasics($count_field = TRUE) {
897     // Add the number of nodes counter
898     $distinct = ($this->view->display_handler->getOption('distinct') && empty($this->query->no_distinct));
899
900     $count_alias = $this->query->addField($this->view->storage->get('base_table'), $this->view->storage->get('base_field'), 'num_records', ['count' => TRUE, 'distinct' => $distinct]);
901     $this->query->addGroupBy($this->name_alias);
902
903     if ($count_field) {
904       $this->query->setCountField($this->tableAlias, $this->realField);
905     }
906
907     $this->count_alias = $count_alias;
908   }
909
910   /**
911    * Sorts the summary based upon the user's selection. The base variant of
912    * this is usually adequate.
913    *
914    * @param $order
915    *   The order selected in the UI.
916    */
917   public function summarySort($order, $by = NULL) {
918     $this->query->addOrderBy(NULL, NULL, $order, (!empty($by) ? $by : $this->name_alias));
919   }
920
921   /**
922    * Provide the argument to use to link from the summary to the next level;
923    * this will be called once per row of a summary, and used as part of
924    * $view->getUrl().
925    *
926    * @param $data
927    *   The query results for the row.
928    */
929   public function summaryArgument($data) {
930     return $data->{$this->base_alias};
931   }
932
933   /**
934    * Provides the name to use for the summary. By default this is just
935    * the name field.
936    *
937    * @param $data
938    *   The query results for the row.
939    */
940   public function summaryName($data) {
941     $value = $data->{$this->name_alias};
942     if (empty($value) && !empty($this->definition['empty field name'])) {
943       $value = $this->definition['empty field name'];
944     }
945     return $value;
946   }
947
948   /**
949    * Set up the query for this argument.
950    *
951    * The argument sent may be found at $this->argument.
952    */
953   public function query($group_by = FALSE) {
954     $this->ensureMyTable();
955     $this->query->addWhere(0, "$this->tableAlias.$this->realField", $this->argument);
956   }
957
958   /**
959    * Get the title this argument will assign the view, given the argument.
960    *
961    * This usually needs to be overridden to provide a proper title.
962    */
963   public function title() {
964     return $this->argument;
965   }
966
967   /**
968    * Called by the view object to get the title. This may be set by a
969    * validator so we don't necessarily call through to title().
970    */
971   public function getTitle() {
972     if (isset($this->validated_title)) {
973       return $this->validated_title;
974     }
975     else {
976       return $this->title();
977     }
978   }
979
980   /**
981    * Validate that this argument works. By default, all arguments are valid.
982    */
983   public function validateArgument($arg) {
984     // By using % in URLs, arguments could be validated twice; this eases
985     // that pain.
986     if (isset($this->argument_validated)) {
987       return $this->argument_validated;
988     }
989
990     if ($this->isException($arg)) {
991       return $this->argument_validated = TRUE;
992     }
993
994     $plugin = $this->getPlugin('argument_validator');
995     return $this->argument_validated = $plugin->validateArgument($arg);
996   }
997
998   /**
999    * Called by the menu system to validate an argument.
1000    *
1001    * This checks to see if this is a 'soft fail', which means that if the
1002    * argument fails to validate, but there is an action to take anyway,
1003    * then validation cannot actually fail.
1004    */
1005   public function validateMenuArgument($arg) {
1006     $validate_info = $this->defaultActions($this->options['validate']['fail']);
1007     if (empty($validate_info['hard fail'])) {
1008       return TRUE;
1009     }
1010
1011     $rc = $this->validateArgument($arg);
1012
1013     // If the validator has changed the validate fail condition to a
1014     // soft fail, deal with that:
1015     $validate_info = $this->defaultActions($this->options['validate']['fail']);
1016     if (empty($validate_info['hard fail'])) {
1017       return TRUE;
1018     }
1019
1020     return $rc;
1021   }
1022
1023   /**
1024    * Set the input for this argument
1025    *
1026    * @return TRUE if it successfully validates; FALSE if it does not.
1027    */
1028   public function setArgument($arg) {
1029     $this->argument = $arg;
1030     return $this->validateArgument($arg);
1031   }
1032
1033   /**
1034    * Get the value of this argument.
1035    */
1036   public function getValue() {
1037     // If we already processed this argument, we're done.
1038     if (isset($this->argument)) {
1039       return $this->argument;
1040     }
1041
1042     // Otherwise, we have to pretend to process ourselves to find the value.
1043     $value = NULL;
1044     // Find the position of this argument within the view.
1045     $position = 0;
1046     foreach ($this->view->argument as $id => $argument) {
1047       if ($id == $this->options['id']) {
1048         break;
1049       }
1050       $position++;
1051     }
1052
1053     $arg = isset($this->view->args[$position]) ? $this->view->args[$position] : NULL;
1054     $this->position = $position;
1055
1056     // Clone ourselves so that we don't break things when we're really
1057     // processing the arguments.
1058     $argument = clone $this;
1059     if (!isset($arg) && $argument->hasDefaultArgument()) {
1060       $arg = $argument->getDefaultArgument();
1061
1062       // remember that this argument was computed, not passed on the URL.
1063       $this->is_default = TRUE;
1064     }
1065     // Set the argument, which will also validate that the argument can be set.
1066     if ($argument->setArgument($arg)) {
1067       $value = $argument->argument;
1068     }
1069     unset($argument);
1070     return $value;
1071   }
1072
1073   /**
1074    * Get the display or row plugin, if it exists.
1075    */
1076   public function getPlugin($type = 'argument_default', $name = NULL) {
1077     $options = [];
1078     switch ($type) {
1079       case 'argument_default':
1080         if (!isset($this->options['default_argument_type'])) {
1081           return;
1082         }
1083         $plugin_name = $this->options['default_argument_type'];
1084         $options_name = 'default_argument_options';
1085         break;
1086       case 'argument_validator':
1087         if (!isset($this->options['validate']['type'])) {
1088           return;
1089         }
1090         $plugin_name = $this->options['validate']['type'];
1091         $options_name = 'validate_options';
1092         break;
1093       case 'style':
1094         if (!isset($this->options['summary']['format'])) {
1095           return;
1096         }
1097         $plugin_name = $this->options['summary']['format'];
1098         $options_name = 'summary_options';
1099     }
1100
1101     if (!$name) {
1102       $name = $plugin_name;
1103     }
1104
1105     // we only fetch the options if we're fetching the plugin actually
1106     // in use.
1107     if ($name == $plugin_name) {
1108       $options = isset($this->options[$options_name]) ? $this->options[$options_name] : [];
1109     }
1110
1111     $plugin = Views::pluginManager($type)->createInstance($name);
1112     if ($plugin) {
1113       $plugin->init($this->view, $this->displayHandler, $options);
1114
1115       if ($type !== 'style') {
1116         // It's an argument_default/argument_validate plugin, so set the argument.
1117         $plugin->setArgument($this);
1118       }
1119       return $plugin;
1120     }
1121   }
1122
1123   /**
1124    * Return a description of how the argument would normally be sorted.
1125    *
1126    * Subclasses should override this to specify what the default sort order of
1127    * their argument is (e.g. alphabetical, numeric, date).
1128    */
1129   public function getSortName() {
1130     return $this->t('Default sort', [], ['context' => 'Sort order']);
1131   }
1132
1133   /**
1134    * Custom form radios process function.
1135    *
1136    * Roll out a single radios element to a list of radios, using the options
1137    * array as index. While doing that, create a container element underneath
1138    * each option, which contains the settings related to that option.
1139    *
1140    * @see \Drupal\Core\Render\Element\Radios::processRadios()
1141    */
1142   public static function processContainerRadios($element) {
1143     if (count($element['#options']) > 0) {
1144       foreach ($element['#options'] as $key => $choice) {
1145         $element += [$key => []];
1146         // Generate the parents as the autogenerator does, so we will have a
1147         // unique id for each radio button.
1148         $parents_for_id = array_merge($element['#parents'], [$key]);
1149
1150         $element[$key] += [
1151           '#type' => 'radio',
1152           '#title' => $choice,
1153           // The key is sanitized in drupal_attributes() during output from the
1154           // theme function.
1155           '#return_value' => $key,
1156           '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
1157           '#attributes' => $element['#attributes'],
1158           '#parents' => $element['#parents'],
1159           '#id' => Html::getUniqueId('edit-' . implode('-', $parents_for_id)),
1160           '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
1161         ];
1162         $element[$key . '_options'] = [
1163           '#type' => 'container',
1164           '#attributes' => ['class' => ['views-admin-dependent']],
1165         ];
1166       }
1167     }
1168     return $element;
1169   }
1170
1171   /**
1172    * Moves argument options into their place.
1173    *
1174    * When configuring the default argument behavior, almost each of the radio
1175    * buttons has its own fieldset shown below it when the radio button is
1176    * clicked. That fieldset is created through a custom form process callback.
1177    * Each element that has #argument_option defined and pointing to a default
1178    * behavior gets moved to the appropriate fieldset.
1179    * So if #argument_option is specified as 'default', the element is moved
1180    * to the 'default_options' fieldset.
1181    */
1182   public static function preRenderMoveArgumentOptions($form) {
1183     foreach (Element::children($form) as $key) {
1184       $element = $form[$key];
1185       if (!empty($element['#argument_option'])) {
1186         $container_name = $element['#argument_option'] . '_options';
1187         if (isset($form['no_argument']['default_action'][$container_name])) {
1188           $form['no_argument']['default_action'][$container_name][$key] = $element;
1189         }
1190         // Remove the original element this duplicates.
1191         unset($form[$key]);
1192       }
1193     }
1194
1195     return $form;
1196   }
1197
1198   /**
1199    * Sanitize validator options including derivatives with : for js.
1200    *
1201    * Reason and alternative: https://www.drupal.org/node/2035345.
1202    *
1203    * @param string $id
1204    *   The identifier to be sanitized.
1205    *
1206    * @return string
1207    *   The sanitized identifier.
1208    *
1209    * @see decodeValidatorId()
1210    */
1211   public static function encodeValidatorId($id) {
1212     return str_replace(':', '---', $id);
1213   }
1214
1215   /**
1216    * Revert sanitized validator options.
1217    *
1218    * @param string $id
1219    *   The sanitized identifier to be reverted.
1220    *
1221    * @return string
1222    *   The original identifier.
1223    */
1224   public static function decodeValidatorId($id) {
1225     return str_replace('---', ':', $id);
1226   }
1227
1228   /**
1229    * Splits an argument into value and operator properties on this instance.
1230    *
1231    * @param bool $force_int
1232    *   Enforce that values should be numeric.
1233    */
1234   protected function unpackArgumentValue($force_int = FALSE) {
1235     $break = static::breakString($this->argument, $force_int);
1236     $this->value = $break->value;
1237     $this->operator = $break->operator;
1238   }
1239
1240   /**
1241    * {@inheritdoc}
1242    */
1243   public function getCacheMaxAge() {
1244     $max_age = Cache::PERMANENT;
1245
1246     // Asks all subplugins (argument defaults, argument validator and styles).
1247     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1248       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1249     }
1250
1251     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1252       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1253     }
1254
1255     // Summaries use style plugins.
1256     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1257       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1258     }
1259
1260     return $max_age;
1261   }
1262
1263   /**
1264    * {@inheritdoc}
1265    */
1266   public function getCacheContexts() {
1267     $contexts = [];
1268     // By definition arguments depends on the URL.
1269     // @todo Once contexts are properly injected into block views we could pull
1270     //   the information from there.
1271     $contexts[] = 'url';
1272
1273     // Asks all subplugins (argument defaults, argument validator and styles).
1274     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1275       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1276     }
1277
1278     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1279       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1280     }
1281
1282     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1283       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1284     }
1285
1286     return $contexts;
1287   }
1288
1289   /**
1290    * {@inheritdoc}
1291    */
1292   public function getCacheTags() {
1293     $tags = [];
1294
1295     // Asks all subplugins (argument defaults, argument validator and styles).
1296     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1297       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1298     }
1299
1300     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1301       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1302     }
1303
1304     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1305       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1306     }
1307
1308     return $tags;
1309   }
1310
1311   /**
1312    * {@inheritdoc}
1313    */
1314   public function calculateDependencies() {
1315     $dependencies = [];
1316     if (($argument_default = $this->getPlugin('argument_default')) && $argument_default instanceof DependentPluginInterface) {
1317       $dependencies = NestedArray::mergeDeep($dependencies, $argument_default->calculateDependencies());
1318     }
1319     if (($argument_validator = $this->getPlugin('argument_validator')) && $argument_validator instanceof DependentPluginInterface) {
1320       $dependencies = NestedArray::mergeDeep($dependencies, $argument_validator->calculateDependencies());
1321     }
1322     if (($style = $this->getPlugin('style')) && $style instanceof DependentPluginInterface) {
1323       $dependencies = NestedArray::mergeDeep($dependencies, $style->calculateDependencies());
1324     }
1325
1326     return $dependencies;
1327   }
1328
1329   /**
1330    * Returns a context definition for this argument.
1331    *
1332    * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null
1333    *   A context definition that represents the argument or NULL if that is
1334    *   not possible.
1335    */
1336   public function getContextDefinition() {
1337     return $this->getPlugin('argument_validator')->getContextDefinition();
1338   }
1339
1340 }
1341
1342 /**
1343  * @}
1344  */