fd273ddfa8380e19f0e95b017918c3b5bcb880d0
[yaffs-website] / web / core / modules / views / src / Plugin / views / filter / FilterPluginBase.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\filter;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableDependencyInterface;
7 use Drupal\Core\Form\FormHelper;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Render\Element;
10 use Drupal\Core\Render\Element\Checkboxes;
11 use Drupal\user\RoleInterface;
12 use Drupal\views\Plugin\views\HandlerBase;
13 use Drupal\Component\Utility\Html;
14 use Drupal\views\Plugin\views\display\DisplayPluginBase;
15 use Drupal\views\ViewExecutable;
16
17 /**
18  * @defgroup views_filter_handlers Views filter handler plugins
19  * @{
20  * Plugins that handle views filtering.
21  *
22  * Filter handler plugins extend
23  * \Drupal\views\Plugin\views\filter\FilterPluginBase. They must be annotated
24  * with \Drupal\views\Annotation\ViewsFilter annotation, and they must be in
25  * namespace directory Plugin\views\filter.
26  *
27  * The following items can go into a hook_views_data() implementation in a
28  * filter section to affect how the filter handler will behave:
29  * - allow empty: If true, the 'IS NULL' and 'IS NOT NULL' operators become
30  *   available as standard operators.
31  *
32  * You can refine the behavior of filters by setting the following Boolean
33  * member variables to TRUE in your plugin class:
34  * - $alwaysMultiple: Disable the possibility of forcing a single value.
35  * - $no_operator: Disable the possibility of using operators.
36  * - $always_required: Disable the possibility of allowing an exposed input to
37  *   be optional.
38  *
39  * @ingroup views_plugins
40  * @see plugin_api
41  */
42
43 /**
44  * Base class for Views filters handler plugins.
45  */
46 abstract class FilterPluginBase extends HandlerBase implements CacheableDependencyInterface {
47
48   /**
49    * Contains the actual value of the field,either configured in the views ui
50    * or entered in the exposed filters.
51    */
52   public $value = NULL;
53
54   /**
55    * Contains the operator which is used on the query.
56    *
57    * @var string
58    */
59   public $operator = '=';
60
61   /**
62    * Contains the information of the selected item in a grouped filter.
63    */
64   public $group_info = NULL;
65
66   /**
67    * @var bool
68    * Disable the possibility to force a single value.
69    */
70   protected $alwaysMultiple = FALSE;
71
72   /**
73    * @var bool
74    * Disable the possibility to use operators.
75    */
76   public $no_operator = FALSE;
77
78   /**
79    * @var bool
80    * Disable the possibility to allow a exposed input to be optional.
81    */
82   public $always_required = FALSE;
83
84   /**
85    * Overrides \Drupal\views\Plugin\views\HandlerBase::init().
86    *
87    * Provide some extra help to get the operator/value easier to use.
88    *
89    * This likely has to be overridden by filters which are more complex
90    * than simple operator/value.
91    */
92   public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
93     parent::init($view, $display, $options);
94
95     $this->operator = $this->options['operator'];
96     $this->value = $this->options['value'];
97     $this->group_info = $this->options['group_info']['default_group'];
98
99     // Set the default value of the operator ID.
100     if (!empty($options['exposed']) && !empty($options['expose']['operator']) && !isset($options['expose']['operator_id'])) {
101       $this->options['expose']['operator_id'] = $options['expose']['operator'];
102     }
103
104     if ($this->multipleExposedInput()) {
105       $this->group_info = array_filter($options['group_info']['default_group_multiple']);
106       $this->options['expose']['multiple'] = TRUE;
107     }
108
109     // If there are relationships in the view, allow empty should be true
110     // so that we can do IS NULL checks on items. Not all filters respect
111     // allow empty, but string and numeric do and that covers enough.
112     if ($this->view->display_handler->getOption('relationships')) {
113       $this->definition['allow empty'] = TRUE;
114     }
115   }
116
117   protected function defineOptions() {
118     $options = parent::defineOptions();
119
120     $options['operator'] = ['default' => '='];
121     $options['value'] = ['default' => ''];
122     $options['group'] = ['default' => '1'];
123     $options['exposed'] = ['default' => FALSE];
124     $options['expose'] = [
125       'contains' => [
126         'operator_id' => ['default' => FALSE],
127         'label' => ['default' => ''],
128         'description' => ['default' => ''],
129         'use_operator' => ['default' => FALSE],
130         'operator' => ['default' => ''],
131         'identifier' => ['default' => ''],
132         'required' => ['default' => FALSE],
133         'remember' => ['default' => FALSE],
134         'multiple' => ['default' => FALSE],
135         'remember_roles' => [
136           'default' => [
137             RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID,
138           ],
139         ],
140       ],
141     ];
142
143     // A group is a combination of a filter, an operator and a value
144     // operating like a single filter.
145     // Users can choose from a select box which group they want to apply.
146     // Views will filter the view according to the defined values.
147     // Because it acts as a standard filter, we have to define
148     // an identifier and other settings like the widget and the label.
149     // This settings are saved in another array to allow users to switch
150     // between a normal filter and a group of filters with a single click.
151     $options['is_grouped'] = ['default' => FALSE];
152     $options['group_info'] = [
153       'contains' => [
154         'label' => ['default' => ''],
155         'description' => ['default' => ''],
156         'identifier' => ['default' => ''],
157         'optional' => ['default' => TRUE],
158         'widget' => ['default' => 'select'],
159         'multiple' => ['default' => FALSE],
160         'remember' => ['default' => 0],
161         'default_group' => ['default' => 'All'],
162         'default_group_multiple' => ['default' => []],
163         'group_items' => ['default' => []],
164       ],
165     ];
166
167     return $options;
168   }
169
170   /**
171    * Display the filter on the administrative summary
172    */
173   public function adminSummary() {
174     return $this->operator . ' ' . $this->value;
175   }
176
177   /**
178    * Determine if a filter can be exposed.
179    */
180   public function canExpose() {
181     return TRUE;
182   }
183
184   /**
185    * Determine if a filter can be converted into a group.
186    * Only exposed filters with operators available can be converted into groups.
187    */
188   protected function canBuildGroup() {
189     return $this->isExposed() && (count($this->operatorOptions()) > 0);
190   }
191
192   /**
193    * Returns TRUE if the exposed filter works like a grouped filter.
194    */
195   public function isAGroup() {
196     return $this->isExposed() && !empty($this->options['is_grouped']);
197   }
198
199   /**
200    * Provide the basic form which calls through to subforms.
201    * If overridden, it is best to call through to the parent,
202    * or to at least make sure all of the functions in this form
203    * are called.
204    */
205   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
206     parent::buildOptionsForm($form, $form_state);
207     if ($this->canExpose()) {
208       $this->showExposeButton($form, $form_state);
209     }
210     if ($this->canBuildGroup()) {
211       $this->showBuildGroupButton($form, $form_state);
212     }
213     $form['clear_markup_start'] = [
214       '#markup' => '<div class="clearfix">',
215     ];
216     if ($this->isAGroup()) {
217       if ($this->canBuildGroup()) {
218         $form['clear_markup_start'] = [
219           '#markup' => '<div class="clearfix">',
220         ];
221         // Render the build group form.
222         $this->showBuildGroupForm($form, $form_state);
223         $form['clear_markup_end'] = [
224           '#markup' => '</div>',
225         ];
226       }
227     }
228     else {
229       // Add the subform from operatorForm().
230       $this->showOperatorForm($form, $form_state);
231       // Add the subform from valueForm().
232       $this->showValueForm($form, $form_state);
233       $form['clear_markup_end'] = [
234         '#markup' => '</div>',
235       ];
236       if ($this->canExpose()) {
237         // Add the subform from buildExposeForm().
238         $this->showExposeForm($form, $form_state);
239       }
240     }
241   }
242
243   /**
244    * Simple validate handler
245    */
246   public function validateOptionsForm(&$form, FormStateInterface $form_state) {
247     $this->operatorValidate($form, $form_state);
248     $this->valueValidate($form, $form_state);
249     if (!empty($this->options['exposed']) && !$this->isAGroup()) {
250       $this->validateExposeForm($form, $form_state);
251     }
252     if ($this->isAGroup()) {
253       $this->buildGroupValidate($form, $form_state);
254     }
255   }
256
257   /**
258    * Simple submit handler
259    */
260   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
261     // Do not store these values.
262     $form_state->unsetValue('expose_button');
263     $form_state->unsetValue('group_button');
264
265     if (!$this->isAGroup()) {
266       $this->operatorSubmit($form, $form_state);
267       $this->valueSubmit($form, $form_state);
268     }
269     if (!empty($this->options['exposed'])) {
270       $this->submitExposeForm($form, $form_state);
271     }
272     if ($this->isAGroup()) {
273       $this->buildGroupSubmit($form, $form_state);
274     }
275   }
276
277   /**
278    * Shortcut to display the operator form.
279    */
280   public function showOperatorForm(&$form, FormStateInterface $form_state) {
281     $this->operatorForm($form, $form_state);
282     $form['operator']['#prefix'] = '<div class="views-group-box views-left-30">';
283     $form['operator']['#suffix'] = '</div>';
284   }
285
286   /**
287    * Options form subform for setting the operator.
288    *
289    * This may be overridden by child classes, and it must
290    * define $form['operator'];
291    *
292    * @see buildOptionsForm()
293    */
294   protected function operatorForm(&$form, FormStateInterface $form_state) {
295     $options = $this->operatorOptions();
296     if (!empty($options)) {
297       $form['operator'] = [
298         '#type' => count($options) < 10 ? 'radios' : 'select',
299         '#title' => $this->t('Operator'),
300         '#default_value' => $this->operator,
301         '#options' => $options,
302       ];
303     }
304   }
305
306   /**
307    * Provide a list of options for the default operator form.
308    * Should be overridden by classes that don't override operatorForm
309    */
310   public function operatorOptions() {
311     return [];
312   }
313
314   /**
315    * Validate the operator form.
316    */
317   protected function operatorValidate($form, FormStateInterface $form_state) {}
318
319   /**
320    * Perform any necessary changes to the form values prior to storage.
321    * There is no need for this function to actually store the data.
322    */
323   public function operatorSubmit($form, FormStateInterface $form_state) {}
324
325   /**
326    * Shortcut to display the value form.
327    */
328   protected function showValueForm(&$form, FormStateInterface $form_state) {
329     $this->valueForm($form, $form_state);
330     if (empty($this->no_operator)) {
331       $form['value']['#prefix'] = '<div class="views-group-box views-right-70">' . (isset($form['value']['#prefix']) ? $form['value']['#prefix'] : '');
332       $form['value']['#suffix'] = (isset($form['value']['#suffix']) ? $form['value']['#suffix'] : '') . '</div>';
333     }
334   }
335
336   /**
337    * Options form subform for setting options.
338    *
339    * This should be overridden by all child classes and it must
340    * define $form['value']
341    *
342    * @see buildOptionsForm()
343    */
344   protected function valueForm(&$form, FormStateInterface $form_state) {
345     $form['value'] = [];
346   }
347
348   /**
349    * Validate the options form.
350    */
351   protected function valueValidate($form, FormStateInterface $form_state) {}
352
353   /**
354    * Perform any necessary changes to the form values prior to storage.
355    * There is no need for this function to actually store the data.
356    */
357   protected function valueSubmit($form, FormStateInterface $form_state) {}
358
359   /**
360    * Shortcut to display the exposed options form.
361    */
362   public function showBuildGroupForm(&$form, FormStateInterface $form_state) {
363     if (empty($this->options['is_grouped'])) {
364       return;
365     }
366
367     $this->buildExposedFiltersGroupForm($form, $form_state);
368
369     // When we click the expose button, we add new gadgets to the form but they
370     // have no data in POST so their defaults get wiped out. This prevents
371     // these defaults from getting wiped out. This setting will only be TRUE
372     // during a 2nd pass rerender.
373     if ($form_state->get('force_build_group_options')) {
374       foreach (Element::children($form['group_info']) as $id) {
375         if (isset($form['group_info'][$id]['#default_value']) && !isset($form['group_info'][$id]['#value'])) {
376           $form['group_info'][$id]['#value'] = $form['group_info'][$id]['#default_value'];
377         }
378       }
379     }
380   }
381
382   /**
383    * Shortcut to display the build_group/hide button.
384    */
385   protected function showBuildGroupButton(&$form, FormStateInterface $form_state) {
386
387     $form['group_button'] = [
388       '#prefix' => '<div class="views-grouped clearfix">',
389       '#suffix' => '</div>',
390       // Should always come after the description and the relationship.
391       '#weight' => -190,
392     ];
393
394     $grouped_description = $this->t('Grouped filters allow a choice between predefined operator|value pairs.');
395     $form['group_button']['radios'] = [
396       '#theme_wrappers' => ['container'],
397       '#attributes' => ['class' => ['js-only']],
398     ];
399     $form['group_button']['radios']['radios'] = [
400       '#title' => $this->t('Filter type to expose'),
401       '#description' => $grouped_description,
402       '#type' => 'radios',
403       '#options' => [
404         $this->t('Single filter'),
405         $this->t('Grouped filters'),
406       ],
407     ];
408
409     if (empty($this->options['is_grouped'])) {
410       $form['group_button']['markup'] = [
411         '#markup' => '<div class="description grouped-description">' . $grouped_description . '</div>',
412       ];
413       $form['group_button']['button'] = [
414         '#limit_validation_errors' => [],
415         '#type' => 'submit',
416         '#value' => $this->t('Grouped filters'),
417         '#submit' => [[$this, 'buildGroupForm']],
418       ];
419       $form['group_button']['radios']['radios']['#default_value'] = 0;
420     }
421     else {
422       $form['group_button']['button'] = [
423         '#limit_validation_errors' => [],
424         '#type' => 'submit',
425         '#value' => $this->t('Single filter'),
426         '#submit' => [[$this, 'buildGroupForm']],
427       ];
428       $form['group_button']['radios']['radios']['#default_value'] = 1;
429     }
430   }
431
432   /**
433    * Displays the Build Group form.
434    */
435   public function buildGroupForm($form, FormStateInterface $form_state) {
436     $item = &$this->options;
437     // flip. If the filter was a group, set back to a standard filter.
438     $item['is_grouped'] = empty($item['is_grouped']);
439
440     // If necessary, set new defaults:
441     if ($item['is_grouped']) {
442       $this->buildGroupOptions();
443     }
444
445     $view = $form_state->get('view');
446     $display_id = $form_state->get('display_id');
447     $type = $form_state->get('type');
448     $id = $form_state->get('id');
449     $view->getExecutable()->setHandler($display_id, $type, $id, $item);
450
451     $view->addFormToStack($form_state->get('form_key'), $display_id, $type, $id, TRUE, TRUE);
452
453     $view->cacheSet();
454     $form_state->set('rerender', TRUE);
455     $form_state->setRebuild();
456     $form_state->get('force_build_group_options', TRUE);
457   }
458
459   /**
460    * Shortcut to display the expose/hide button.
461    */
462   public function showExposeButton(&$form, FormStateInterface $form_state) {
463     $form['expose_button'] = [
464       '#prefix' => '<div class="views-expose clearfix">',
465       '#suffix' => '</div>',
466       // Should always come after the description and the relationship.
467       '#weight' => -200,
468     ];
469
470     // Add a checkbox for JS users, which will have behavior attached to it
471     // so it can replace the button.
472     $form['expose_button']['checkbox'] = [
473       '#theme_wrappers' => ['container'],
474       '#attributes' => ['class' => ['js-only']],
475     ];
476     $form['expose_button']['checkbox']['checkbox'] = [
477       '#title' => $this->t('Expose this filter to visitors, to allow them to change it'),
478       '#type' => 'checkbox',
479     ];
480
481     // Then add the button itself.
482     if (empty($this->options['exposed'])) {
483       $form['expose_button']['markup'] = [
484         '#markup' => '<div class="description exposed-description">' . $this->t('This filter is not exposed. Expose it to allow the users to change it.') . '</div>',
485       ];
486       $form['expose_button']['button'] = [
487         '#limit_validation_errors' => [],
488         '#type' => 'submit',
489         '#value' => $this->t('Expose filter'),
490         '#submit' => [[$this, 'displayExposedForm']],
491       ];
492       $form['expose_button']['checkbox']['checkbox']['#default_value'] = 0;
493     }
494     else {
495       $form['expose_button']['markup'] = [
496         '#markup' => '<div class="description exposed-description">' . $this->t('This filter is exposed. If you hide it, users will not be able to change it.') . '</div>',
497       ];
498       $form['expose_button']['button'] = [
499         '#limit_validation_errors' => [],
500         '#type' => 'submit',
501         '#value' => $this->t('Hide filter'),
502         '#submit' => [[$this, 'displayExposedForm']],
503       ];
504       $form['expose_button']['checkbox']['checkbox']['#default_value'] = 1;
505     }
506   }
507
508   /**
509    * Options form subform for exposed filter options.
510    *
511    * @see buildOptionsForm()
512    */
513   public function buildExposeForm(&$form, FormStateInterface $form_state) {
514     $form['#theme'] = 'views_ui_expose_filter_form';
515     // #flatten will move everything from $form['expose'][$key] to $form[$key]
516     // prior to rendering. That's why the preRender for it needs to run first,
517     // so that when the next preRender (the one for fieldsets) runs, it gets
518     // the flattened data.
519     array_unshift($form['#pre_render'], [get_class($this), 'preRenderFlattenData']);
520     $form['expose']['#flatten'] = TRUE;
521
522     if (empty($this->always_required)) {
523       $form['expose']['required'] = [
524         '#type' => 'checkbox',
525         '#title' => $this->t('Required'),
526         '#default_value' => $this->options['expose']['required'],
527       ];
528     }
529     else {
530       $form['expose']['required'] = [
531         '#type' => 'value',
532         '#value' => TRUE,
533       ];
534     }
535     $form['expose']['label'] = [
536       '#type' => 'textfield',
537       '#default_value' => $this->options['expose']['label'],
538       '#title' => $this->t('Label'),
539       '#size' => 40,
540     ];
541
542     $form['expose']['description'] = [
543       '#type' => 'textfield',
544       '#default_value' => $this->options['expose']['description'],
545       '#title' => $this->t('Description'),
546       '#size' => 60,
547     ];
548
549     if (!empty($form['operator']['#type'])) {
550       // Increase the width of the left (operator) column.
551       $form['operator']['#prefix'] = '<div class="views-group-box views-left-40">';
552       $form['operator']['#suffix'] = '</div>';
553       $form['value']['#prefix'] = '<div class="views-group-box views-right-60">';
554       $form['value']['#suffix'] = '</div>';
555
556       $form['expose']['use_operator'] = [
557         '#type' => 'checkbox',
558         '#title' => $this->t('Expose operator'),
559         '#description' => $this->t('Allow the user to choose the operator.'),
560         '#default_value' => !empty($this->options['expose']['use_operator']),
561       ];
562       $form['expose']['operator_id'] = [
563         '#type' => 'textfield',
564         '#default_value' => $this->options['expose']['operator_id'],
565         '#title' => $this->t('Operator identifier'),
566         '#size' => 40,
567         '#description' => $this->t('This will appear in the URL after the ? to identify this operator.'),
568         '#states' => [
569           'visible' => [
570             ':input[name="options[expose][use_operator]"]' => ['checked' => TRUE],
571           ],
572         ],
573       ];
574     }
575     else {
576       $form['expose']['operator_id'] = [
577         '#type' => 'value',
578         '#value' => '',
579       ];
580     }
581
582     if (empty($this->alwaysMultiple)) {
583       $form['expose']['multiple'] = [
584         '#type' => 'checkbox',
585         '#title' => $this->t('Allow multiple selections'),
586         '#description' => $this->t('Enable to allow users to select multiple items.'),
587         '#default_value' => $this->options['expose']['multiple'],
588       ];
589     }
590     $form['expose']['remember'] = [
591       '#type' => 'checkbox',
592       '#title' => $this->t('Remember the last selection'),
593       '#description' => $this->t('Enable to remember the last selection made by the user.'),
594       '#default_value' => $this->options['expose']['remember'],
595     ];
596
597     $role_options = array_map('\Drupal\Component\Utility\Html::escape', user_role_names());
598     $form['expose']['remember_roles'] = [
599       '#type' => 'checkboxes',
600       '#title' => $this->t('User roles'),
601       '#description' => $this->t('Remember exposed selection only for the selected user role(s). If you select no roles, the exposed data will never be stored.'),
602       '#default_value' => $this->options['expose']['remember_roles'],
603       '#options' => $role_options,
604       '#states' => [
605         'invisible' => [
606           ':input[name="options[expose][remember]"]' => ['checked' => FALSE],
607         ],
608       ],
609     ];
610
611     $form['expose']['identifier'] = [
612       '#type' => 'textfield',
613       '#default_value' => $this->options['expose']['identifier'],
614       '#title' => $this->t('Filter identifier'),
615       '#size' => 40,
616       '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
617     ];
618   }
619
620   /**
621    * Validate the options form.
622    */
623   public function validateExposeForm($form, FormStateInterface $form_state) {
624     $identifier = $form_state->getValue(['options', 'expose', 'identifier']);
625     $this->validateIdentifier($identifier, $form_state, $form['expose']['identifier']);
626   }
627
628   /**
629    * Determines if the given grouped filter entry has a valid value.
630    *
631    * @param array $group
632    *   A group entry as defined by buildGroupForm().
633    *
634    * @return bool
635    */
636   protected function hasValidGroupedValue(array $group) {
637     $operators = $this->operators();
638     if ($operators[$group['operator']]['values'] == 0) {
639       // Some filters, such as "is empty," do not require a value to be
640       // specified in order to be valid entries.
641       return TRUE;
642     }
643     else {
644       if (is_string($group['value'])) {
645         return trim($group['value']) != '';
646       }
647       elseif (is_array($group['value'])) {
648         // Some filters allow multiple options to be selected (for example, node
649         // types). Ensure at least the minimum number of values is present for
650         // this entry to be considered valid.
651         $min_values = $operators[$group['operator']]['values'];
652         $actual_values = count(array_filter($group['value'], 'static::arrayFilterZero'));
653         return $actual_values >= $min_values;
654       }
655     }
656     return FALSE;
657   }
658
659
660   /**
661    * Validate the build group options form.
662    */
663   protected function buildGroupValidate($form, FormStateInterface $form_state) {
664     if (!$form_state->isValueEmpty(['options', 'group_info'])) {
665       $identifier = $form_state->getValue(['options', 'group_info', 'identifier']);
666       $this->validateIdentifier($identifier, $form_state, $form['group_info']['identifier']);
667     }
668
669     if ($group_items = $form_state->getValue(['options', 'group_info', 'group_items'])) {
670       foreach ($group_items as $id => $group) {
671         if (empty($group['remove'])) {
672           $has_valid_value = $this->hasValidGroupedValue($group);
673           if ($has_valid_value && $group['title'] == '') {
674             $operators = $this->operators();
675             if ($operators[$group['operator']]['values'] == 0) {
676               $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required for the specified operator.'));
677             }
678             else {
679               $form_state->setError($form['group_info']['group_items'][$id]['title'], $this->t('A label is required if the value for this item is defined.'));
680             }
681           }
682           if (!$has_valid_value && $group['title'] != '') {
683             $form_state->setError($form['group_info']['group_items'][$id]['value'], $this->t('A value is required if the label for this item is defined.'));
684           }
685         }
686       }
687     }
688   }
689
690   /**
691    * Validates a filter identifier.
692    *
693    * Sets the form error if $form_state is passed or a error string if
694    * $form_state is not passed.
695    *
696    * @param string $identifier
697    *   The identifier to check.
698    * @param \Drupal\Core\Form\FormStateInterface $form_state
699    * @param array $form_group
700    *   The form element to set any errors on.
701    *
702    * @return string
703    */
704   protected function validateIdentifier($identifier, FormStateInterface $form_state = NULL, &$form_group = []) {
705     $error = '';
706     if (empty($identifier)) {
707       $error = $this->t('The identifier is required if the filter is exposed.');
708     }
709     elseif ($identifier == 'value') {
710       $error = $this->t('This identifier is not allowed.');
711     }
712     elseif (preg_match('/[^a-zA-z0-9_~\.\-]/', $identifier)) {
713       $error = $this->t('This identifier has illegal characters.');
714     }
715
716     if ($form_state && !$this->view->display_handler->isIdentifierUnique($form_state->get('id'), $identifier)) {
717       $error = $this->t('This identifier is used by another handler.');
718     }
719
720     if (!empty($form_state) && !empty($error)) {
721       $form_state->setError($form_group, $error);
722     }
723     return $error;
724   }
725
726   /**
727    * Save new group items, re-enumerates and remove groups marked to delete.
728    */
729   protected function buildGroupSubmit($form, FormStateInterface $form_state) {
730     $groups = [];
731     $group_items = $form_state->getValue(['options', 'group_info', 'group_items']);
732     uasort($group_items, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
733     // Filter out removed items.
734
735     // Start from 1 to avoid problems with #default_value in the widget.
736     $new_id = 1;
737     $new_default = 'All';
738     foreach ($group_items as $id => $group) {
739       if (empty($group['remove'])) {
740         // Don't store this.
741         unset($group['remove']);
742         unset($group['weight']);
743         $groups[$new_id] = $group;
744
745         if ($form_state->getValue(['options', 'group_info', 'default_group']) == $id) {
746           $new_default = $new_id;
747         }
748       }
749       $new_id++;
750     }
751     if ($new_default != 'All') {
752       $form_state->setValue(['options', 'group_info', 'default_group'], $new_default);
753     }
754     $filter_default_multiple = $form_state->getValue(['options', 'group_info', 'default_group_multiple']);
755     $form_state->setValue(['options', 'group_info', 'default_group_multiple'], array_filter($filter_default_multiple));
756
757     $form_state->setValue(['options', 'group_info', 'group_items'], $groups);
758   }
759
760   /**
761    * Provide default options for exposed filters.
762    */
763   public function defaultExposeOptions() {
764     $this->options['expose'] = [
765       'use_operator' => FALSE,
766       'operator' => $this->options['id'] . '_op',
767       'identifier' => $this->options['id'],
768       'label' => $this->definition['title'],
769       'description' => NULL,
770       'remember' => FALSE,
771       'multiple' => FALSE,
772       'required' => FALSE,
773     ];
774   }
775
776   /**
777    * Provide default options for exposed filters.
778    */
779   protected function buildGroupOptions() {
780     $this->options['group_info'] = [
781       'label' => $this->definition['title'],
782       'description' => NULL,
783       'identifier' => $this->options['id'],
784       'optional' => TRUE,
785       'widget' => 'select',
786       'multiple' => FALSE,
787       'remember' => FALSE,
788       'default_group' => 'All',
789       'default_group_multiple' => [],
790       'group_items' => [],
791     ];
792   }
793
794   /**
795    * Build a form containing a group of operator | values to apply as a
796    * single filter.
797    */
798   public function groupForm(&$form, FormStateInterface $form_state) {
799     if (!empty($this->options['group_info']['optional']) && !$this->multipleExposedInput()) {
800       $groups = ['All' => $this->t('- Any -')];
801     }
802     foreach ($this->options['group_info']['group_items'] as $id => $group) {
803       if (!empty($group['title'])) {
804         $groups[$id] = $id != 'All' ? $this->t($group['title']) : $group['title'];
805       }
806     }
807
808     if (count($groups)) {
809       $value = $this->options['group_info']['identifier'];
810
811       $form[$value] = [
812         '#title' => $this->options['group_info']['label'],
813         '#type' => $this->options['group_info']['widget'],
814         '#default_value' => $this->group_info,
815         '#options' => $groups,
816       ];
817       if (!empty($this->options['group_info']['multiple'])) {
818         if (count($groups) < 5) {
819           $form[$value]['#type'] = 'checkboxes';
820         }
821         else {
822           $form[$value]['#type'] = 'select';
823           $form[$value]['#size'] = 5;
824           $form[$value]['#multiple'] = TRUE;
825         }
826         unset($form[$value]['#default_value']);
827         $user_input = $form_state->getUserInput();
828         if (empty($user_input)) {
829           $user_input[$value] = $this->group_info;
830           $form_state->setUserInput($user_input);
831         }
832       }
833
834       $this->options['expose']['label'] = '';
835     }
836   }
837
838
839   /**
840    * Render our chunk of the exposed filter form when selecting
841    *
842    * You can override this if it doesn't do what you expect.
843    */
844   public function buildExposedForm(&$form, FormStateInterface $form_state) {
845     if (empty($this->options['exposed'])) {
846       return;
847     }
848
849     // Build the exposed form, when its based on an operator.
850     if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id'])) {
851       $operator = $this->options['expose']['operator_id'];
852       $this->operatorForm($form, $form_state);
853       $form[$operator] = $form['operator'];
854
855       $this->exposedTranslate($form[$operator], 'operator');
856
857       unset($form['operator']);
858     }
859
860     // Build the form and set the value based on the identifier.
861     if (!empty($this->options['expose']['identifier'])) {
862       $value = $this->options['expose']['identifier'];
863       $this->valueForm($form, $form_state);
864       $form[$value] = $form['value'];
865
866       if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
867         unset($form[$value]['#title']);
868       }
869
870       $this->exposedTranslate($form[$value], 'value');
871
872       if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
873         unset($form[$value]['#default_value']);
874       }
875
876       if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
877         $form[$value]['#default_value'] = 'All';
878       }
879
880       if ($value != 'value') {
881         unset($form['value']);
882       }
883     }
884   }
885
886   /**
887    * Build the form to let users create the group of exposed filters.
888    * This form is displayed when users click on button 'Build group'
889    */
890   protected function buildExposedFiltersGroupForm(&$form, FormStateInterface $form_state) {
891     if (empty($this->options['exposed']) || empty($this->options['is_grouped'])) {
892       return;
893     }
894     $form['#theme'] = 'views_ui_build_group_filter_form';
895
896     // #flatten will move everything from $form['group_info'][$key] to $form[$key]
897     // prior to rendering. That's why the preRender for it needs to run first,
898     // so that when the next preRender (the one for fieldsets) runs, it gets
899     // the flattened data.
900     array_unshift($form['#pre_render'], [get_class($this), 'preRenderFlattenData']);
901     $form['group_info']['#flatten'] = TRUE;
902
903     if (!empty($this->options['group_info']['identifier'])) {
904       $identifier = $this->options['group_info']['identifier'];
905     }
906     else {
907       $identifier = 'group_' . $this->options['expose']['identifier'];
908     }
909     $form['group_info']['identifier'] = [
910       '#type' => 'textfield',
911       '#default_value' => $identifier,
912       '#title' => $this->t('Filter identifier'),
913       '#size' => 40,
914       '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
915     ];
916     $form['group_info']['label'] = [
917       '#type' => 'textfield',
918       '#default_value' => $this->options['group_info']['label'],
919       '#title' => $this->t('Label'),
920       '#size' => 40,
921     ];
922     $form['group_info']['description'] = [
923       '#type' => 'textfield',
924       '#default_value' => $this->options['group_info']['description'],
925       '#title' => $this->t('Description'),
926       '#size' => 60,
927     ];
928     $form['group_info']['optional'] = [
929       '#type' => 'checkbox',
930       '#title' => $this->t('Optional'),
931       '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
932       '#default_value' => $this->options['group_info']['optional'],
933     ];
934     $form['group_info']['multiple'] = [
935       '#type' => 'checkbox',
936       '#title' => $this->t('Allow multiple selections'),
937       '#description' => $this->t('Enable to allow users to select multiple items.'),
938       '#default_value' => $this->options['group_info']['multiple'],
939     ];
940     $form['group_info']['widget'] = [
941       '#type' => 'radios',
942       '#default_value' => $this->options['group_info']['widget'],
943       '#title' => $this->t('Widget type'),
944       '#options' => [
945         'radios' => $this->t('Radios'),
946         'select' => $this->t('Select'),
947       ],
948       '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
949     ];
950     $form['group_info']['remember'] = [
951       '#type' => 'checkbox',
952       '#title' => $this->t('Remember'),
953       '#description' => $this->t('Remember the last setting the user gave this filter.'),
954       '#default_value' => $this->options['group_info']['remember'],
955     ];
956
957     if (!empty($this->options['group_info']['identifier'])) {
958       $identifier = $this->options['group_info']['identifier'];
959     }
960     else {
961       $identifier = 'group_' . $this->options['expose']['identifier'];
962     }
963     $form['group_info']['identifier'] = [
964       '#type' => 'textfield',
965       '#default_value' => $identifier,
966       '#title' => $this->t('Filter identifier'),
967       '#size' => 40,
968       '#description' => $this->t('This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.'),
969     ];
970     $form['group_info']['label'] = [
971       '#type' => 'textfield',
972       '#default_value' => $this->options['group_info']['label'],
973       '#title' => $this->t('Label'),
974       '#size' => 40,
975     ];
976     $form['group_info']['optional'] = [
977       '#type' => 'checkbox',
978       '#title' => $this->t('Optional'),
979       '#description' => $this->t('This exposed filter is optional and will have added options to allow it not to be set.'),
980       '#default_value' => $this->options['group_info']['optional'],
981     ];
982     $form['group_info']['widget'] = [
983       '#type' => 'radios',
984       '#default_value' => $this->options['group_info']['widget'],
985       '#title' => $this->t('Widget type'),
986       '#options' => [
987         'radios' => $this->t('Radios'),
988         'select' => $this->t('Select'),
989       ],
990       '#description' => $this->t('Select which kind of widget will be used to render the group of filters'),
991     ];
992     $form['group_info']['remember'] = [
993       '#type' => 'checkbox',
994       '#title' => $this->t('Remember'),
995       '#description' => $this->t('Remember the last setting the user gave this filter.'),
996       '#default_value' => $this->options['group_info']['remember'],
997     ];
998
999     // The string '- Any -' will not be rendered.
1000     // @see theme_views_ui_build_group_filter_form()
1001     $groups = ['All' => $this->t('- Any -')];
1002
1003     // Provide 3 options to start when we are in a new group.
1004     if (count($this->options['group_info']['group_items']) == 0) {
1005       $this->options['group_info']['group_items'] = array_fill(1, 3, []);
1006     }
1007
1008     // After the general settings, comes a table with all the existent groups.
1009     $default_weight = 0;
1010     foreach ($this->options['group_info']['group_items'] as $item_id => $item) {
1011       if (!$form_state->isValueEmpty(['options', 'group_info', 'group_items', $item_id, 'remove'])) {
1012         continue;
1013       }
1014       // Each rows contains three widgets:
1015       // a) The title, where users define how they identify a pair of operator | value
1016       // b) The operator
1017       // c) The value (or values) to use in the filter with the selected operator
1018
1019       // In each row, we have to display the operator form and the value from
1020       // $row acts as a fake form to render each widget in a row.
1021       $row = [];
1022       $groups[$item_id] = $this->t('Grouping @id', ['@id' => $item_id]);
1023       $this->operatorForm($row, $form_state);
1024       // Force the operator form to be a select box. Some handlers uses
1025       // radios and they occupy a lot of space in a table row.
1026       $row['operator']['#type'] = 'select';
1027       $row['operator']['#title'] = '';
1028       $this->valueForm($row, $form_state);
1029
1030       // Fix the dependencies to update value forms when operators changes. This
1031       // is needed because forms are inside a new form and their IDs changes.
1032       // Dependencies are used when operator changes from to 'Between',
1033       // 'Not Between', etc, and two or more widgets are displayed.
1034       FormHelper::rewriteStatesSelector($row['value'], ':input[name="options[operator]"]', ':input[name="options[group_info][group_items][' . $item_id . '][operator]"]');
1035
1036       // Set default values.
1037       $children = Element::children($row['value']);
1038       if (!empty($children)) {
1039         foreach ($children as $child) {
1040           if (!empty($row['value'][$child]['#states']['visible'])) {
1041             foreach ($row['value'][$child]['#states']['visible'] as $state) {
1042               if (isset($state[':input[name="options[group_info][group_items][' . $item_id . '][operator]"]'])) {
1043                 $row['value'][$child]['#title'] = '';
1044
1045                 // Exit this loop and process the next child element.
1046                 break;
1047               }
1048             }
1049           }
1050
1051           if (!empty($this->options['group_info']['group_items'][$item_id]['value'][$child])) {
1052             $row['value'][$child]['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'][$child];
1053           }
1054         }
1055       }
1056       else {
1057         if (isset($this->options['group_info']['group_items'][$item_id]['value']) && $this->options['group_info']['group_items'][$item_id]['value'] != '') {
1058           $row['value']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['value'];
1059         }
1060       }
1061
1062       if (!empty($this->options['group_info']['group_items'][$item_id]['operator'])) {
1063         $row['operator']['#default_value'] = $this->options['group_info']['group_items'][$item_id]['operator'];
1064       }
1065
1066       $default_title = '';
1067       if (!empty($this->options['group_info']['group_items'][$item_id]['title'])) {
1068         $default_title = $this->options['group_info']['group_items'][$item_id]['title'];
1069       }
1070
1071       // Per item group, we have a title that identifies it.
1072       $form['group_info']['group_items'][$item_id] = [
1073         'title' => [
1074           '#title' => $this->t('Label'),
1075           '#title_display' => 'invisible',
1076           '#type' => 'textfield',
1077           '#size' => 20,
1078           '#default_value' => $default_title,
1079         ],
1080         'operator' => $row['operator'],
1081         'value' => $row['value'],
1082         // No title is given here, since this input is never displayed. It is
1083         // only triggered by JavaScript.
1084         'remove' => [
1085           '#type' => 'checkbox',
1086           '#id' => 'views-removed-' . $item_id,
1087           '#attributes' => ['class' => ['views-remove-checkbox']],
1088           '#default_value' => 0,
1089         ],
1090         'weight' => [
1091           '#title' => $this->t('Weight'),
1092           '#title_display' => 'invisible',
1093           '#type' => 'weight',
1094           '#delta' => count($this->options['group_info']['group_items']),
1095           '#default_value' => $default_weight++,
1096           '#attributes' => ['class' => ['weight']],
1097         ],
1098       ];
1099     }
1100     // From all groups, let chose which is the default.
1101     $form['group_info']['default_group'] = [
1102       '#type' => 'radios',
1103       '#options' => $groups,
1104       '#default_value' => $this->options['group_info']['default_group'],
1105       '#required' => TRUE,
1106       '#attributes' => [
1107         'class' => ['default-radios'],
1108       ]
1109     ];
1110     // From all groups, let chose which is the default.
1111     $form['group_info']['default_group_multiple'] = [
1112       '#type' => 'checkboxes',
1113       '#options' => $groups,
1114       '#default_value' => $this->options['group_info']['default_group_multiple'],
1115       '#attributes' => [
1116         'class' => ['default-checkboxes'],
1117       ]
1118     ];
1119
1120     $form['group_info']['add_group'] = [
1121       '#prefix' => '<div class="views-build-group clear-block">',
1122       '#suffix' => '</div>',
1123       '#type' => 'submit',
1124       '#value' => $this->t('Add another item'),
1125       '#submit' => [[$this, 'addGroupForm']],
1126     ];
1127
1128     $js = [];
1129     $js['tableDrag']['views-filter-groups']['weight'][0] = [
1130       'target' => 'weight',
1131       'source' => NULL,
1132       'relationship' => 'sibling',
1133       'action' => 'order',
1134       'hidden' => TRUE,
1135       'limit' => 0,
1136     ];
1137     $js_settings = $form_state->get('js_settings');
1138     if ($js_settings && is_array($js)) {
1139       $js_settings = array_merge($js_settings, $js);
1140     }
1141     else {
1142       $js_settings = $js;
1143     }
1144     $form_state->set('js_settings', $js_settings);
1145   }
1146
1147   /**
1148    * Add a new group to the exposed filter groups.
1149    */
1150   public function addGroupForm($form, FormStateInterface $form_state) {
1151     $item = &$this->options;
1152
1153     // Add a new row.
1154     $item['group_info']['group_items'][] = [];
1155
1156     $view = $form_state->get('view');
1157     $display_id = $form_state->get('display_id');
1158     $type = $form_state->get('type');
1159     $id = $form_state->get('id');
1160     $view->getExecutable()->setHandler($display_id, $type, $id, $item);
1161
1162     $view->cacheSet();
1163     $form_state->set('rerender', TRUE);
1164     $form_state->setRebuild();
1165     $form_state->get('force_build_group_options', TRUE);
1166   }
1167
1168
1169   /**
1170    * Make some translations to a form item to make it more suitable to
1171    * exposing.
1172    */
1173   protected function exposedTranslate(&$form, $type) {
1174     if (!isset($form['#type'])) {
1175       return;
1176     }
1177
1178     if ($form['#type'] == 'radios') {
1179       $form['#type'] = 'select';
1180     }
1181     // Checkboxes don't work so well in exposed forms due to GET conversions.
1182     if ($form['#type'] == 'checkboxes') {
1183       if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
1184         $form['#type'] = 'select';
1185       }
1186       if (!empty($this->options['expose']['multiple'])) {
1187         $form['#multiple'] = TRUE;
1188       }
1189     }
1190     if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
1191       unset($form['#multiple']);
1192       $form['#size'] = NULL;
1193     }
1194
1195     // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
1196     if ($form['#type'] == 'select') {
1197       $this->prepareFilterSelectOptions($form['#options']);
1198     }
1199
1200     if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
1201       $form['#options'] = ['All' => $this->t('- Any -')] + $form['#options'];
1202       $form['#default_value'] = 'All';
1203     }
1204
1205     if (!empty($this->options['expose']['required'])) {
1206       $form['#required'] = TRUE;
1207     }
1208   }
1209
1210
1211   /**
1212    * Sanitizes the HTML select element's options.
1213    *
1214    * The function is recursive to support optgroups.
1215    */
1216   protected function prepareFilterSelectOptions(&$options) {
1217     foreach ($options as $value => $label) {
1218       // Recurse for optgroups.
1219       if (is_array($label)) {
1220         $this->prepareFilterSelectOptions($options[$value]);
1221       }
1222       // FAPI has some special value to allow hierarchy.
1223       // @see _form_options_flatten
1224       elseif (is_object($label) && isset($label->option)) {
1225         $this->prepareFilterSelectOptions($options[$value]->option);
1226       }
1227       else {
1228         // Cast the label to a string since it can be an object.
1229         // @see \Drupal\Core\StringTranslation\TranslatableMarkup
1230         $options[$value] = strip_tags(Html::decodeEntities((string) $label));
1231       }
1232     }
1233   }
1234
1235   /**
1236    * Tell the renderer about our exposed form. This only needs to be
1237    * overridden for particularly complex forms. And maybe not even then.
1238    *
1239    * @return array|null
1240    *   For standard exposed filters. An array with the following keys:
1241    *   - operator: The $form key of the operator. Set to NULL if no operator.
1242    *   - value: The $form key of the value. Set to NULL if no value.
1243    *   - label: The label to use for this piece.
1244    *   For grouped exposed filters. An array with the following keys:
1245    *   - value: The $form key of the value. Set to NULL if no value.
1246    *   - label: The label to use for this piece.
1247    */
1248   public function exposedInfo() {
1249     if (empty($this->options['exposed'])) {
1250       return;
1251     }
1252
1253     if ($this->isAGroup()) {
1254       return [
1255         'value' => $this->options['group_info']['identifier'],
1256         'label' => $this->options['group_info']['label'],
1257         'description' => $this->options['group_info']['description'],
1258       ];
1259     }
1260
1261     return [
1262       'operator' => $this->options['expose']['operator_id'],
1263       'value' => $this->options['expose']['identifier'],
1264       'label' => $this->options['expose']['label'],
1265       'description' => $this->options['expose']['description'],
1266     ];
1267   }
1268
1269   /**
1270    * Transform the input from a grouped filter into a standard filter.
1271    *
1272    * When a filter is a group, find the set of operator and values
1273    * that the chosen item represents, and inform views that a normal
1274    * filter was submitted by telling the operator and the value selected.
1275    *
1276    * The param $selected_group_id is only passed when the filter uses the
1277    * checkboxes widget, and this function will be called for each item
1278    * chosen in the checkboxes.
1279    */
1280   public function convertExposedInput(&$input, $selected_group_id = NULL) {
1281     if ($this->isAGroup()) {
1282       // If it is already defined the selected group, use it. Only valid
1283       // when the filter uses checkboxes for widget.
1284       if (!empty($selected_group_id)) {
1285         $selected_group = $selected_group_id;
1286       }
1287       else {
1288         $selected_group = $input[$this->options['group_info']['identifier']];
1289       }
1290       if ($selected_group == 'All' && !empty($this->options['group_info']['optional'])) {
1291         return NULL;
1292       }
1293       if ($selected_group != 'All' && empty($this->options['group_info']['group_items'][$selected_group])) {
1294         return FALSE;
1295       }
1296       if (isset($selected_group) && isset($this->options['group_info']['group_items'][$selected_group])) {
1297         $input[$this->options['expose']['operator']] = $this->options['group_info']['group_items'][$selected_group]['operator'];
1298
1299         // Value can be optional, For example for 'empty' and 'not empty' filters.
1300         if (isset($this->options['group_info']['group_items'][$selected_group]['value']) && $this->options['group_info']['group_items'][$selected_group]['value'] !== '') {
1301           $input[$this->options['expose']['identifier']] = $this->options['group_info']['group_items'][$selected_group]['value'];
1302         }
1303         $this->options['expose']['use_operator'] = TRUE;
1304
1305         $this->group_info = $input[$this->options['group_info']['identifier']];
1306         return TRUE;
1307       }
1308       else {
1309         return FALSE;
1310       }
1311     }
1312   }
1313
1314   /**
1315    * Returns the options available for a grouped filter that users checkboxes
1316    * as widget, and therefore has to be applied several times, one per
1317    * item selected.
1318    */
1319   public function groupMultipleExposedInput(&$input) {
1320     if (!empty($input[$this->options['group_info']['identifier']])) {
1321       return array_filter($input[$this->options['group_info']['identifier']]);
1322     }
1323     return [];
1324   }
1325
1326   /**
1327    * Returns TRUE if users can select multiple groups items of a
1328    * grouped exposed filter.
1329    */
1330   public function multipleExposedInput() {
1331     return $this->isAGroup() && !empty($this->options['group_info']['multiple']);
1332   }
1333
1334   /**
1335    * If set to remember exposed input in the session, store it there.
1336    * This function is similar to storeExposedInput but modified to
1337    * work properly when the filter is a group.
1338    */
1339   public function storeGroupInput($input, $status) {
1340     if (!$this->isAGroup() || empty($this->options['group_info']['identifier'])) {
1341       return TRUE;
1342     }
1343
1344     if (empty($this->options['group_info']['remember'])) {
1345       return;
1346     }
1347
1348     // Figure out which display id is responsible for the filters, so we
1349     // know where to look for session stored values.
1350     $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
1351
1352     // False means that we got a setting that means to recurse ourselves,
1353     // so we should erase whatever happened to be there.
1354     if ($status === FALSE && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1355       $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1356
1357       if (isset($session[$this->options['group_info']['identifier']])) {
1358         unset($session[$this->options['group_info']['identifier']]);
1359       }
1360     }
1361
1362     if ($status !== FALSE) {
1363       if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1364         $_SESSION['views'][$this->view->storage->id()][$display_id] = [];
1365       }
1366
1367       $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1368
1369       $session[$this->options['group_info']['identifier']] = $input[$this->options['group_info']['identifier']];
1370     }
1371   }
1372
1373   /**
1374    * Determines if the input from a filter should change the generated query.
1375    *
1376    * @param array $input
1377    *   The exposed data for this view.
1378    *
1379    * @return bool
1380    *   TRUE if the input for this filter should be included in the view query.
1381    *   FALSE otherwise.
1382    */
1383   public function acceptExposedInput($input) {
1384     if (empty($this->options['exposed'])) {
1385       return TRUE;
1386     }
1387
1388     if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
1389       $this->operator = $input[$this->options['expose']['operator_id']];
1390     }
1391
1392     if (!empty($this->options['expose']['identifier'])) {
1393       $value = $input[$this->options['expose']['identifier']];
1394
1395       // Various ways to check for the absence of non-required input.
1396       if (empty($this->options['expose']['required'])) {
1397         if (($this->operator == 'empty' || $this->operator == 'not empty') && $value === '') {
1398           $value = ' ';
1399         }
1400
1401         if ($this->operator != 'empty' && $this->operator != 'not empty') {
1402           if ($value == 'All' || $value === []) {
1403             return FALSE;
1404           }
1405
1406           // If checkboxes are used to render this filter, do not include the
1407           // filter if no options are checked.
1408           if (is_array($value) && Checkboxes::detectEmptyCheckboxes($value)) {
1409             return FALSE;
1410           }
1411         }
1412
1413         if (!empty($this->alwaysMultiple) && $value === '') {
1414           return FALSE;
1415         }
1416       }
1417       if (isset($value)) {
1418         $this->value = $value;
1419         if (empty($this->alwaysMultiple) && empty($this->options['expose']['multiple']) && !is_array($value)) {
1420           $this->value = [$value];
1421         }
1422       }
1423       else {
1424         return FALSE;
1425       }
1426     }
1427
1428     return TRUE;
1429   }
1430
1431   public function storeExposedInput($input, $status) {
1432     if (empty($this->options['exposed']) || empty($this->options['expose']['identifier'])) {
1433       return TRUE;
1434     }
1435
1436     if (empty($this->options['expose']['remember'])) {
1437       return;
1438     }
1439
1440     // Check if we store exposed value for current user.
1441     $user = \Drupal::currentUser();
1442     $allowed_rids = empty($this->options['expose']['remember_roles']) ? [] : array_filter($this->options['expose']['remember_roles']);
1443     $intersect_rids = array_intersect(array_keys($allowed_rids), $user->getRoles());
1444     if (empty($intersect_rids)) {
1445       return;
1446     }
1447
1448     // Figure out which display id is responsible for the filters, so we
1449     // know where to look for session stored values.
1450     $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;
1451
1452     // shortcut test.
1453     $operator = !empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']);
1454
1455     // False means that we got a setting that means to recurse ourselves,
1456     // so we should erase whatever happened to be there.
1457     if (!$status && isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1458       $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1459       if ($operator && isset($session[$this->options['expose']['operator_id']])) {
1460         unset($session[$this->options['expose']['operator_id']]);
1461       }
1462
1463       if (isset($session[$this->options['expose']['identifier']])) {
1464         unset($session[$this->options['expose']['identifier']]);
1465       }
1466     }
1467
1468     if ($status) {
1469       if (!isset($_SESSION['views'][$this->view->storage->id()][$display_id])) {
1470         $_SESSION['views'][$this->view->storage->id()][$display_id] = [];
1471       }
1472
1473       $session = &$_SESSION['views'][$this->view->storage->id()][$display_id];
1474
1475       if ($operator && isset($input[$this->options['expose']['operator_id']])) {
1476         $session[$this->options['expose']['operator_id']] = $input[$this->options['expose']['operator_id']];
1477       }
1478
1479       $session[$this->options['expose']['identifier']] = $input[$this->options['expose']['identifier']];
1480     }
1481   }
1482
1483   /**
1484    * Add this filter to the query.
1485    *
1486    * Due to the nature of fapi, the value and the operator have an unintended
1487    * level of indirection. You will find them in $this->operator
1488    * and $this->value respectively.
1489    */
1490   public function query() {
1491     $this->ensureMyTable();
1492     $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", $this->value, $this->operator);
1493   }
1494
1495   /**
1496    * Can this filter be used in OR groups?
1497    *
1498    * Some filters have complicated where clauses that cannot be easily used
1499    * with OR groups. Some filters must also use HAVING which also makes
1500    * them not groupable. These filters will end up in a special group
1501    * if OR grouping is in use.
1502    *
1503    * @return bool
1504    */
1505   public function canGroup() {
1506     return TRUE;
1507   }
1508
1509   /**
1510    * {@inheritdoc}
1511    */
1512   public function getCacheMaxAge() {
1513     return Cache::PERMANENT;
1514   }
1515
1516   /**
1517    * {@inheritdoc}
1518    */
1519   public function getCacheContexts() {
1520     $cache_contexts = [];
1521     // An exposed filter allows the user to change a view's filters. They accept
1522     // input from GET parameters, which are part of the URL. Hence a view with
1523     // an exposed filter is cacheable per URL.
1524     if ($this->isExposed()) {
1525       $cache_contexts[] = 'url';
1526     }
1527     return $cache_contexts;
1528   }
1529
1530   /**
1531    * {@inheritdoc}
1532    */
1533   public function getCacheTags() {
1534     return [];
1535   }
1536
1537   /**
1538    * {@inheritdoc}
1539    */
1540   public function validate() {
1541     if (!empty($this->options['exposed']) && $error = $this->validateIdentifier($this->options['expose']['identifier'])) {
1542       return [$error];
1543     }
1544   }
1545
1546   /**
1547    * Filter by no empty values, though allow the use of (string) "0".
1548    *
1549    * @param string $var
1550    *   The variable to evaluate.
1551    *
1552    * @return bool
1553    *   TRUE if the value is equal to an empty string, FALSE otherwise.
1554    */
1555   protected static function arrayFilterZero($var) {
1556     if (is_int($var)) {
1557       return $var != 0;
1558     }
1559     return trim($var) != '';
1560   }
1561
1562 }
1563
1564 /**
1565  * @}
1566  */