3 namespace Drupal\views\Plugin\views;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Component\Utility\UrlHelper;
8 use Drupal\Component\Utility\Xss;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\Core\Session\AccountInterface;
13 use Drupal\views\Plugin\views\display\DisplayPluginBase;
14 use Drupal\views\Render\ViewsRenderPipelineMarkup;
15 use Drupal\views\ViewExecutable;
16 use Drupal\views\Views;
17 use Drupal\views\ViewsData;
20 * Base class for Views handler plugins.
22 * @ingroup views_plugins
24 abstract class HandlerBase extends PluginBase implements ViewsHandlerInterface {
27 * Where the $query object will reside:
29 * @var \Drupal\views\Plugin\views\query\QueryPluginBase
34 * The table this handler is attached to.
41 * The alias of the table of this handler which is used in the query.
48 * The actual field in the database table, maybe different
49 * on other kind of query plugins/special handlers.
56 * With field you can override the realField if the real field is not set.
63 * The relationship used for this field.
67 public $relationship = NULL;
72 * @var \Drupal\Core\Extension\ModuleHandlerInterface
74 protected $moduleHandler;
77 * The views data service.
79 * @var \Drupal\views\ViewsData
84 * Constructs a Handler object.
86 * @param array $configuration
87 * A configuration array containing information about the plugin instance.
88 * @param string $plugin_id
89 * The plugin_id for the plugin instance.
90 * @param mixed $plugin_definition
91 * The plugin implementation definition.
93 public function __construct(array $configuration, $plugin_id, $plugin_definition) {
94 parent::__construct($configuration, $plugin_id, $plugin_definition);
95 $this->is_handler = TRUE;
101 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
102 parent::init($view, $display, $options);
104 // Check to see if this handler type is defaulted. Note that
105 // we have to do a lookup because the type is singular but the
106 // option is stored as the plural.
108 $this->unpackOptions($this->options, $options);
110 // This exist on most handlers, but not all. So they are still optional.
111 if (isset($options['table'])) {
112 $this->table = $options['table'];
115 // Allow aliases on both fields and tables.
116 if (isset($this->definition['real table'])) {
117 $this->table = $this->definition['real table'];
120 if (isset($this->definition['real field'])) {
121 $this->realField = $this->definition['real field'];
124 if (isset($this->definition['field'])) {
125 $this->realField = $this->definition['field'];
128 if (isset($options['field'])) {
129 $this->field = $options['field'];
130 if (!isset($this->realField)) {
131 $this->realField = $options['field'];
135 $this->query = &$view->query;
138 protected function defineOptions() {
139 $options = parent::defineOptions();
141 $options['id'] = ['default' => ''];
142 $options['table'] = ['default' => ''];
143 $options['field'] = ['default' => ''];
144 $options['relationship'] = ['default' => 'none'];
145 $options['group_type'] = ['default' => 'group'];
146 $options['admin_label'] = ['default' => ''];
154 public function adminLabel($short = FALSE) {
155 if (!empty($this->options['admin_label'])) {
156 return $this->options['admin_label'];
158 $title = ($short && isset($this->definition['title short'])) ? $this->definition['title short'] : $this->definition['title'];
159 return $this->t('@group: @title', ['@group' => $this->definition['group'], '@title' => $title]);
165 public function getField($field = NULL) {
166 if (!isset($field)) {
167 if (!empty($this->formula)) {
168 $field = $this->getFormula();
171 $field = $this->tableAlias . '.' . $this->realField;
175 // If grouping, check to see if the aggregation method needs to modify the field.
176 if ($this->view->display_handler->useGroupBy()) {
177 $this->view->initQuery();
179 $info = $this->query->getAggregationInfo();
180 if (!empty($info[$this->options['group_type']]['method'])) {
181 $method = $info[$this->options['group_type']]['method'];
182 if (method_exists($this->query, $method)) {
183 return $this->query->$method($this->options['group_type'], $field);
195 public function sanitizeValue($value, $type = NULL) {
198 $value = Xss::filter($value);
201 $value = Xss::filterAdmin($value);
204 $value = Html::escape(UrlHelper::stripDangerousProtocols($value));
207 $value = Html::escape($value);
210 return ViewsRenderPipelineMarkup::create($value);
214 * Transform a string by a certain method.
217 * The input you want to transform.
219 * How do you want to transform it, possible values:
220 * - upper: Uppercase the string.
221 * - lower: lowercase the string.
222 * - ucfirst: Make the first char uppercase.
223 * - ucwords: Make each word in the string uppercase.
226 * The transformed string.
228 protected function caseTransform($string, $option) {
233 return Unicode::strtoupper($string);
235 return Unicode::strtolower($string);
237 return Unicode::ucfirst($string);
239 return Unicode::ucwords($string);
246 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
247 // Some form elements belong in a fieldset for presentation, but can't
248 // be moved into one because of the $form_state->getValues() hierarchy. Those
249 // elements can add a #fieldset => 'fieldset_name' property, and they'll
250 // be moved to their fieldset during pre_render.
251 $form['#pre_render'][] = [get_class($this), 'preRenderAddFieldsetMarkup'];
253 parent::buildOptionsForm($form, $form_state);
255 $form['fieldsets'] = [
257 '#value' => ['more', 'admin_label'],
260 $form['admin_label'] = [
261 '#type' => 'details',
262 '#title' => $this->t('Administrative title'),
265 $form['admin_label']['admin_label'] = [
266 '#type' => 'textfield',
267 '#title' => $this->t('Administrative title'),
268 '#description' => $this->t('This title will be displayed on the views edit page instead of the default one. This might be useful if you have the same item twice.'),
269 '#default_value' => $this->options['admin_label'],
270 '#parents' => ['options', 'admin_label'],
273 // This form is long and messy enough that the "Administrative title" option
274 // belongs in "Administrative title" fieldset at the bottom of the form.
276 '#type' => 'details',
277 '#title' => $this->t('More'),
282 // Allow to alter the default values brought into the form.
283 // @todo Do we really want to keep this hook.
284 $this->getModuleHandler()->alter('views_handler_options', $this->options, $this->view);
288 * Gets the module handler.
290 * @return \Drupal\Core\Extension\ModuleHandlerInterface
292 protected function getModuleHandler() {
293 if (!$this->moduleHandler) {
294 $this->moduleHandler = \Drupal::moduleHandler();
297 return $this->moduleHandler;
301 * Sets the module handler.
303 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
304 * The module handler.
306 public function setModuleHandler(ModuleHandlerInterface $module_handler) {
307 $this->moduleHandler = $module_handler;
311 * Provides the handler some groupby.
313 public function usesGroupBy() {
317 * Provide a form for aggregation settings.
319 public function buildGroupByForm(&$form, FormStateInterface $form_state) {
320 $display_id = $form_state->get('display_id');
321 $type = $form_state->get('type');
322 $id = $form_state->get('id');
324 $form['#section'] = $display_id . '-' . $type . '-' . $id;
326 $this->view->initQuery();
327 $info = $this->view->query->getAggregationInfo();
328 foreach ($info as $id => $aggregate) {
329 $group_types[$id] = $aggregate['title'];
332 $form['group_type'] = [
334 '#title' => $this->t('Aggregation type'),
335 '#default_value' => $this->options['group_type'],
336 '#description' => $this->t('Select the aggregation function to use on this field.'),
337 '#options' => $group_types,
342 * Perform any necessary changes to the form values prior to storage.
343 * There is no need for this function to actually store the data.
345 public function submitGroupByForm(&$form, FormStateInterface $form_state) {
346 $form_state->get('handler')->options['group_type'] = $form_state->getValue(['options', 'group_type']);
350 * If a handler has 'extra options' it will get a little settings widget and
351 * another form called extra_options.
353 public function hasExtraOptions() { return FALSE; }
356 * Provide defaults for the handler.
358 public function defineExtraOptions(&$option) { }
361 * Provide a form for setting options.
363 public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) { }
366 * Validate the options form.
368 public function validateExtraOptionsForm($form, FormStateInterface $form_state) { }
371 * Perform any necessary changes to the form values prior to storage.
372 * There is no need for this function to actually store the data.
374 public function submitExtraOptionsForm($form, FormStateInterface $form_state) { }
377 * Determine if a handler can be exposed.
379 public function canExpose() { return FALSE; }
382 * Set new exposed option defaults when exposed setting is flipped
385 public function defaultExposeOptions() { }
388 * Get information about the exposed form for the form renderer.
390 public function exposedInfo() { }
393 * Render our chunk of the exposed handler form when selecting
395 public function buildExposedForm(&$form, FormStateInterface $form_state) { }
398 * Validate the exposed handler form
400 public function validateExposed(&$form, FormStateInterface $form_state) { }
403 * Submit the exposed handler form
405 public function submitExposed(&$form, FormStateInterface $form_state) { }
408 * Form for exposed handler options.
410 public function buildExposeForm(&$form, FormStateInterface $form_state) { }
413 * Validate the options form.
415 public function validateExposeForm($form, FormStateInterface $form_state) { }
418 * Perform any necessary changes to the form exposes prior to storage.
419 * There is no need for this function to actually store the data.
421 public function submitExposeForm($form, FormStateInterface $form_state) { }
424 * Shortcut to display the expose/hide button.
426 public function showExposeButton(&$form, FormStateInterface $form_state) { }
429 * Shortcut to display the exposed options form.
431 public function showExposeForm(&$form, FormStateInterface $form_state) {
432 if (empty($this->options['exposed'])) {
436 $this->buildExposeForm($form, $form_state);
438 // When we click the expose button, we add new gadgets to the form but they
439 // have no data in POST so their defaults get wiped out. This prevents
440 // these defaults from getting wiped out. This setting will only be TRUE
441 // during a 2nd pass rerender.
442 if ($form_state->get('force_expose_options')) {
443 foreach (Element::children($form['expose']) as $id) {
444 if (isset($form['expose'][$id]['#default_value']) && !isset($form['expose'][$id]['#value'])) {
445 $form['expose'][$id]['#value'] = $form['expose'][$id]['#default_value'];
454 public function access(AccountInterface $account) {
455 if (isset($this->definition['access callback']) && function_exists($this->definition['access callback'])) {
456 if (isset($this->definition['access arguments']) && is_array($this->definition['access arguments'])) {
457 return call_user_func_array($this->definition['access callback'], [$account] + $this->definition['access arguments']);
459 return $this->definition['access callback']($account);
468 public function preQuery() {
474 public function query() {
480 public function postExecute(&$values) { }
483 * Provides a unique placeholders for handlers.
486 * A placeholder which contains the table and the fieldname.
488 protected function placeholder() {
489 return $this->query->placeholder($this->table . '_' . $this->field);
495 public function setRelationship() {
496 // Ensure this gets set to something.
497 $this->relationship = NULL;
499 // Don't process non-existent relationships.
500 if (empty($this->options['relationship']) || $this->options['relationship'] == 'none') {
504 $relationship = $this->options['relationship'];
506 // Ignore missing/broken relationships.
507 if (empty($this->view->relationship[$relationship])) {
511 // Check to see if the relationship has already processed. If not, then we
512 // cannot process it.
513 if (empty($this->view->relationship[$relationship]->alias)) {
518 $this->relationship = $this->view->relationship[$relationship]->alias;
524 public function ensureMyTable() {
525 if (!isset($this->tableAlias)) {
526 $this->tableAlias = $this->query->ensureTable($this->table, $this->relationship);
528 return $this->tableAlias;
534 public function adminSummary() { }
537 * Determine if this item is 'exposed', meaning it provides form elements
538 * to let users modify the view.
542 public function isExposed() {
543 return !empty($this->options['exposed']);
547 * Returns TRUE if the exposed filter works like a grouped filter.
549 public function isAGroup() { return FALSE; }
552 * Define if the exposed input has to be submitted multiple times.
553 * This is TRUE when exposed filters grouped are using checkboxes as
556 public function multipleExposedInput() { return FALSE; }
559 * Take input from exposed handlers and assign to this handler, if necessary.
561 public function acceptExposedInput($input) { return TRUE; }
564 * If set to remember exposed input in the session, store it there.
566 public function storeExposedInput($input, $status) { return TRUE; }
571 public function getJoin() {
572 // get the join from this table that links back to the base table.
573 // Determine the primary table to seek
574 if (empty($this->query->relationships[$this->relationship])) {
575 $base_table = $this->view->storage->get('base_table');
578 $base_table = $this->query->relationships[$this->relationship]['base'];
581 $join = $this->getTableJoin($this->table, $base_table);
590 public function validate() { return []; }
595 public function broken() {
600 * Creates cross-database SQL date formatting.
602 * @param string $format
603 * A format string for the result, like 'Y-m-d H:i:s'.
606 * An appropriate SQL string for the DB type and field type.
608 public function getDateFormat($format) {
609 return $this->query->getDateFormat($this->getDateField(), $format);
613 * Creates cross-database SQL dates.
616 * An appropriate SQL string for the db type and field type.
618 public function getDateField() {
619 return $this->query->getDateField("$this->tableAlias.$this->realField");
623 * Gets views data service.
625 * @return \Drupal\views\ViewsData
627 protected function getViewsData() {
628 if (!$this->viewsData) {
629 $this->viewsData = Views::viewsData();
632 return $this->viewsData;
638 public function setViewsData(ViewsData $views_data) {
639 $this->viewsData = $views_data;
645 public static function getTableJoin($table, $base_table) {
646 $data = Views::viewsData()->get($table);
647 if (isset($data['table']['join'][$base_table])) {
648 $join_info = $data['table']['join'][$base_table];
649 if (!empty($join_info['join_id'])) {
650 $id = $join_info['join_id'];
656 $configuration = $join_info;
657 // Fill in some easy defaults.
658 if (empty($configuration['table'])) {
659 $configuration['table'] = $table;
661 // If this is empty, it's a direct link.
662 if (empty($configuration['left_table'])) {
663 $configuration['left_table'] = $base_table;
666 if (isset($join_info['arguments'])) {
667 foreach ($join_info['arguments'] as $key => $argument) {
668 $configuration[$key] = $argument;
672 $join = Views::pluginManager('join')->createInstance($id, $configuration);
681 public function getEntityType() {
682 // If the user has configured a relationship on the handler take that into
684 if (!empty($this->options['relationship']) && $this->options['relationship'] != 'none') {
685 $relationship = $this->displayHandler->getOption('relationships')[$this->options['relationship']];
686 $table_data = $this->getViewsData()->get($relationship['table']);
687 $views_data = $this->getViewsData()->get($table_data[$relationship['field']]['relationship']['base']);
690 $views_data = $this->getViewsData()->get($this->view->storage->get('base_table'));
693 if (isset($views_data['table']['entity type'])) {
694 return $views_data['table']['entity type'];
697 throw new \Exception("No entity type for field {$this->options['id']} on view {$this->view->storage->id()}");
704 public static function breakString($str, $force_int = FALSE) {
708 // Determine if the string has 'or' operators (plus signs) or 'and'
709 // operators (commas) and split the string accordingly.
710 if (preg_match('/^([\w0-9-_\.]+[+ ]+)+[\w0-9-_\.]+$/u', $str)) {
711 // The '+' character in a query string may be parsed as ' '.
713 $value = preg_split('/[+ ]/', $str);
715 elseif (preg_match('/^([\w0-9-_\.]+[, ]+)*[\w0-9-_\.]+$/u', $str)) {
717 $value = explode(',', $str);
720 // Filter any empty matches (Like from '++' in a string) and reset the
721 // array keys. 'strlen' is used as the filter callback so we do not lose
722 // 0 values (would otherwise evaluate == FALSE).
723 $value = array_values(array_filter($value, 'strlen'));
726 $value = array_map('intval', $value);
729 return (object) ['value' => $value, 'operator' => $operator];
733 * Displays the Expose form.
735 public function displayExposedForm($form, FormStateInterface $form_state) {
736 $item = &$this->options;
738 $item['exposed'] = empty($item['exposed']);
740 // If necessary, set new defaults:
741 if ($item['exposed']) {
742 $this->defaultExposeOptions();
745 $view = $form_state->get('view');
746 $display_id = $form_state->get('display_id');
747 $type = $form_state->get('type');
748 $id = $form_state->get('id');
749 $view->getExecutable()->setHandler($display_id, $type, $id, $item);
751 $view->addFormToStack($form_state->get('form_key'), $display_id, $type, $id, TRUE, TRUE);
754 $form_state->set('rerender', TRUE);
755 $form_state->setRebuild();
756 $form_state->set('force_expose_options', TRUE);
760 * A submit handler that is used for storing temporary items when using
761 * multi-step changes, such as ajax requests.
763 public function submitTemporaryForm($form, FormStateInterface $form_state) {
764 // Run it through the handler's submit function.
765 $this->submitOptionsForm($form['options'], $form_state);
766 $item = $this->options;
767 $types = ViewExecutable::getHandlerTypes();
769 // For footer/header $handler_type is area but $type is footer/header.
770 // For all other handle types it's the same.
771 $handler_type = $type = $form_state->get('type');
772 if (!empty($types[$type]['type'])) {
773 $handler_type = $types[$type]['type'];
777 $view = $form_state->get('view');
778 $executable = $view->getExecutable();
779 if ($executable->display_handler->useGroupBy() && !empty($item['group_type'])) {
780 if (empty($executable->query)) {
781 $executable->initQuery();
783 $aggregate = $executable->query->getAggregationInfo();
784 if (!empty($aggregate[$item['group_type']]['handler'][$type])) {
785 $override = $aggregate[$item['group_type']]['handler'][$type];
789 // Create a new handler and unpack the options from the form onto it. We
790 // can use that for storage.
791 $handler = Views::handlerManager($handler_type)->getHandler($item, $override);
792 $handler->init($executable, $executable->display_handler, $item);
794 // Add the incoming options to existing options because items using
795 // the extra form may not have everything in the form here.
796 $options = $form_state->getValue('options') + $this->options;
798 // This unpacks only options that are in the definition, ensuring random
799 // extra stuff on the form is not sent through.
800 $handler->unpackOptions($handler->options, $options, NULL, FALSE);
802 // Store the item back on the view.
803 $executable = $view->getExecutable();
804 $executable->temporary_options[$type][$form_state->get('id')] = $handler->options;
806 // @todo Decide if \Drupal\views_ui\Form\Ajax\ViewsFormBase::getForm() is
807 // perhaps the better place to fix the issue.
808 // \Drupal\views_ui\Form\Ajax\ViewsFormBase::getForm() drops the current
809 // form from the stack, even if it's an #ajax. So add the item back to the top
811 $view->addFormToStack($form_state->get('form_key'), $form_state->get('display_id'), $type, $item['id'], TRUE);
813 $form_state->get('rerender', TRUE);
814 $form_state->setRebuild();
820 * Calculates options stored on the handler
822 * @param array $options
823 * The options stored in the handler
824 * @param array $form_state_options
825 * The newly submitted form state options.
830 public function submitFormCalculateOptions(array $options, array $form_state_options) {
831 return $form_state_options + $options;