View source  
  <?php
namespace Drupal\views\Plugin\views;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Render\ViewsRenderPipelineMarkup;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\views\ViewsData;
abstract class HandlerBase extends PluginBase implements ViewsHandlerInterface {
  
  public $query = NULL;
  
  public $table;
  
  public $tableAlias;
  
  public $realField;
  
  public $field;
  
  public $relationship = NULL;
  
  protected $moduleHandler;
  
  protected $viewsData;
  
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->is_handler = TRUE;
  }
  
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    
    $this
      ->unpackOptions($this->options, $options);
    
    if (isset($options['table'])) {
      $this->table = $options['table'];
    }
    
    if (isset($this->definition['real table'])) {
      $this->table = $this->definition['real table'];
    }
    if (isset($this->definition['real field'])) {
      $this->realField = $this->definition['real field'];
    }
    if (isset($this->definition['field'])) {
      $this->realField = $this->definition['field'];
    }
    if (isset($options['field'])) {
      $this->field = $options['field'];
      if (!isset($this->realField)) {
        $this->realField = $options['field'];
      }
    }
    $this->query =& $view->query;
  }
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['id'] = [
      'default' => '',
    ];
    $options['table'] = [
      'default' => '',
    ];
    $options['field'] = [
      'default' => '',
    ];
    $options['relationship'] = [
      'default' => 'none',
    ];
    $options['group_type'] = [
      'default' => 'group',
    ];
    $options['admin_label'] = [
      'default' => '',
    ];
    return $options;
  }
  
  public function adminLabel($short = FALSE) {
    if (!empty($this->options['admin_label'])) {
      return $this->options['admin_label'];
    }
    $title = $short && isset($this->definition['title short']) ? $this->definition['title short'] : $this->definition['title'];
    return $this
      ->t('@group: @title', [
      '@group' => $this->definition['group'],
      '@title' => $title,
    ]);
  }
  
  public function getField($field = NULL) {
    if (!isset($field)) {
      if (!empty($this->formula)) {
        $field = $this
          ->getFormula();
      }
      else {
        $field = $this->tableAlias . '.' . $this->realField;
      }
    }
    
    if ($this->view->display_handler
      ->useGroupBy()) {
      $this->view
        ->initQuery();
      if ($this->query) {
        $info = $this->query
          ->getAggregationInfo();
        if (!empty($info[$this->options['group_type']]['method'])) {
          $method = $info[$this->options['group_type']]['method'];
          if (method_exists($this->query, $method)) {
            return $this->query
              ->{$method}($this->options['group_type'], $field);
          }
        }
      }
    }
    return $field;
  }
  
  public function sanitizeValue($value, $type = NULL) {
    switch ($type) {
      case 'xss':
        $value = Xss::filter($value);
        break;
      case 'xss_admin':
        $value = Xss::filterAdmin($value);
        break;
      case 'url':
        $value = Html::escape(UrlHelper::stripDangerousProtocols($value));
        break;
      default:
        $value = Html::escape($value);
        break;
    }
    return ViewsRenderPipelineMarkup::create($value);
  }
  
  protected function caseTransform($string, $option) {
    switch ($option) {
      default:
        return $string;
      case 'upper':
        return mb_strtoupper($string);
      case 'lower':
        return mb_strtolower($string);
      case 'ucfirst':
        return Unicode::ucfirst($string);
      case 'ucwords':
        return Unicode::ucwords($string);
    }
  }
  
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    
    $form['#pre_render'][] = [
      get_class($this),
      'preRenderAddFieldsetMarkup',
    ];
    parent::buildOptionsForm($form, $form_state);
    $form['fieldsets'] = [
      '#type' => 'value',
      '#value' => [
        'more',
        'admin_label',
      ],
    ];
    $form['admin_label'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Administrative title'),
      '#weight' => 150,
    ];
    $form['admin_label']['admin_label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Administrative title'),
      '#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.'),
      '#default_value' => $this->options['admin_label'],
      '#parents' => [
        'options',
        'admin_label',
      ],
    ];
    
    $form['more'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('More'),
      '#weight' => 200,
      '#optional' => TRUE,
    ];
    
    $this
      ->getModuleHandler()
      ->alter('views_handler_options', $this->options, $this->view);
  }
  
  protected function getModuleHandler() {
    if (!$this->moduleHandler) {
      $this->moduleHandler = \Drupal::moduleHandler();
    }
    return $this->moduleHandler;
  }
  
  public function setModuleHandler(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }
  
  public function usesGroupBy() {
    return TRUE;
  }
  
  public function buildGroupByForm(&$form, FormStateInterface $form_state) {
    $display_id = $form_state
      ->get('display_id');
    $type = $form_state
      ->get('type');
    $id = $form_state
      ->get('id');
    $form['#section'] = $display_id . '-' . $type . '-' . $id;
    $this->view
      ->initQuery();
    $info = $this->view->query
      ->getAggregationInfo();
    foreach ($info as $id => $aggregate) {
      $group_types[$id] = $aggregate['title'];
    }
    $form['group_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Aggregation type'),
      '#default_value' => $this->options['group_type'],
      '#description' => $this
        ->t('Select the aggregation function to use on this field.'),
      '#options' => $group_types,
    ];
  }
  
  public function submitGroupByForm(&$form, FormStateInterface $form_state) {
    $form_state
      ->get('handler')->options['group_type'] = $form_state
      ->getValue([
      'options',
      'group_type',
    ]);
  }
  
  public function hasExtraOptions() {
    return FALSE;
  }
  
  public function defineExtraOptions(&$option) {
  }
  
  public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) {
  }
  
  public function validateExtraOptionsForm($form, FormStateInterface $form_state) {
  }
  
  public function submitExtraOptionsForm($form, FormStateInterface $form_state) {
  }
  
  public function canExpose() {
    return FALSE;
  }
  
  public function defaultExposeOptions() {
  }
  
  public function exposedInfo() {
  }
  
  public function buildExposedForm(&$form, FormStateInterface $form_state) {
  }
  
  public function validateExposed(&$form, FormStateInterface $form_state) {
  }
  
  public function submitExposed(&$form, FormStateInterface $form_state) {
  }
  
  public function buildExposeForm(&$form, FormStateInterface $form_state) {
  }
  
  public function validateExposeForm($form, FormStateInterface $form_state) {
  }
  
  public function submitExposeForm($form, FormStateInterface $form_state) {
  }
  
  public function showExposeButton(&$form, FormStateInterface $form_state) {
  }
  
  public function showExposeForm(&$form, FormStateInterface $form_state) {
    if (empty($this->options['exposed'])) {
      return;
    }
    $this
      ->buildExposeForm($form, $form_state);
    
    if ($form_state
      ->get('force_expose_options')) {
      foreach (Element::children($form['expose']) as $id) {
        if (isset($form['expose'][$id]['#default_value']) && !isset($form['expose'][$id]['#value'])) {
          $form['expose'][$id]['#value'] = $form['expose'][$id]['#default_value'];
        }
      }
    }
  }
  
  public function access(AccountInterface $account) {
    if (isset($this->definition['access callback']) && function_exists($this->definition['access callback'])) {
      if (isset($this->definition['access arguments']) && is_array($this->definition['access arguments'])) {
        return call_user_func_array($this->definition['access callback'], [
          $account,
        ] + $this->definition['access arguments']);
      }
      return $this->definition['access callback']($account);
    }
    return TRUE;
  }
  
  public function preQuery() {
  }
  
  public function query() {
  }
  
  public function postExecute(&$values) {
  }
  
  protected function placeholder() {
    return $this->query
      ->placeholder($this->table . '_' . $this->field);
  }
  
  public function setRelationship() {
    
    $this->relationship = NULL;
    
    if (empty($this->options['relationship']) || $this->options['relationship'] == 'none') {
      return;
    }
    $relationship = $this->options['relationship'];
    
    if (empty($this->view->relationship[$relationship])) {
      return;
    }
    
    if (empty($this->view->relationship[$relationship]->alias)) {
      return;
    }
    
    $this->relationship = $this->view->relationship[$relationship]->alias;
  }
  
  public function ensureMyTable() {
    if (!isset($this->tableAlias)) {
      $this->tableAlias = $this->query
        ->ensureTable($this->table, $this->relationship);
    }
    return $this->tableAlias;
  }
  
  public function adminSummary() {
  }
  
  public function isExposed() {
    return !empty($this->options['exposed']);
  }
  
  public function isAGroup() {
    return FALSE;
  }
  
  public function multipleExposedInput() {
    return FALSE;
  }
  
  public function acceptExposedInput($input) {
    return TRUE;
  }
  
  public function storeExposedInput($input, $status) {
    return TRUE;
  }
  
  public function getJoin() {
    
    if (empty($this->query->relationships[$this->relationship])) {
      $base_table = $this->view->storage
        ->get('base_table');
    }
    else {
      $base_table = $this->query->relationships[$this->relationship]['base'];
    }
    $join = $this
      ->getTableJoin($this->table, $base_table);
    if ($join) {
      return clone $join;
    }
  }
  
  public function validate() {
    return [];
  }
  
  public function broken() {
    return FALSE;
  }
  
  public function getDateFormat($format) {
    return $this->query
      ->getDateFormat($this
      ->getDateField(), $format);
  }
  
  public function getDateField() {
    return $this->query
      ->getDateField("{$this->tableAlias}.{$this->realField}");
  }
  
  protected function getViewsData() {
    if (!$this->viewsData) {
      $this->viewsData = Views::viewsData();
    }
    return $this->viewsData;
  }
  
  public function setViewsData(ViewsData $views_data) {
    $this->viewsData = $views_data;
  }
  
  public static function getTableJoin($table, $base_table) {
    $data = Views::viewsData()
      ->get($table);
    if (isset($data['table']['join'][$base_table])) {
      $join_info = $data['table']['join'][$base_table];
      if (!empty($join_info['join_id'])) {
        $id = $join_info['join_id'];
      }
      else {
        $id = 'standard';
      }
      $configuration = $join_info;
      
      if (empty($configuration['table'])) {
        $configuration['table'] = $table;
      }
      
      if (empty($configuration['left_table'])) {
        $configuration['left_table'] = $base_table;
      }
      if (isset($join_info['arguments'])) {
        foreach ($join_info['arguments'] as $key => $argument) {
          $configuration[$key] = $argument;
        }
      }
      $join = Views::pluginManager('join')
        ->createInstance($id, $configuration);
      return $join;
    }
  }
  
  public function getEntityType() {
    
    if (!empty($this->options['relationship']) && $this->options['relationship'] != 'none') {
      $relationship = $this->displayHandler
        ->getOption('relationships')[$this->options['relationship']];
      $table_data = $this
        ->getViewsData()
        ->get($relationship['table']);
      $views_data = $this
        ->getViewsData()
        ->get($table_data[$relationship['field']]['relationship']['base']);
    }
    else {
      $views_data = $this
        ->getViewsData()
        ->get($this->view->storage
        ->get('base_table'));
    }
    if (isset($views_data['table']['entity type'])) {
      return $views_data['table']['entity type'];
    }
    else {
      throw new \Exception("No entity type for field {$this->options['id']} on view {$this->view->storage->id()}");
    }
  }
  
  public static function breakString($str, $force_int = FALSE) {
    $operator = NULL;
    $value = [];
    
    if (preg_match('/^([\\w0-9-_\\.]+[+ ]+)+[\\w0-9-_\\.]+$/u', $str)) {
      
      $operator = 'or';
      $value = preg_split('/[+ ]/', $str);
    }
    elseif (preg_match('/^([\\w0-9-_\\.]+[, ]+)*[\\w0-9-_\\.]+$/u', $str)) {
      $operator = 'and';
      $value = explode(',', $str);
    }
    
    $value = array_values(array_filter($value, 'strlen'));
    if ($force_int) {
      $value = array_map('intval', $value);
    }
    return (object) [
      'value' => $value,
      'operator' => $operator,
    ];
  }
  
  public function displayExposedForm($form, FormStateInterface $form_state) {
    $item =& $this->options;
    
    $item['exposed'] = empty($item['exposed']);
    
    if ($item['exposed']) {
      $this
        ->defaultExposeOptions();
    }
    $view = $form_state
      ->get('view');
    $display_id = $form_state
      ->get('display_id');
    $type = $form_state
      ->get('type');
    $id = $form_state
      ->get('id');
    $view
      ->getExecutable()
      ->setHandler($display_id, $type, $id, $item);
    $view
      ->addFormToStack($form_state
      ->get('form_key'), $display_id, $type, $id, TRUE, TRUE);
    $view
      ->cacheSet();
    $form_state
      ->set('rerender', TRUE);
    $form_state
      ->setRebuild();
    $form_state
      ->set('force_expose_options', TRUE);
  }
  
  public function submitTemporaryForm($form, FormStateInterface $form_state) {
    
    $this
      ->submitOptionsForm($form['options'], $form_state);
    $item = $this->options;
    $types = ViewExecutable::getHandlerTypes();
    
    $handler_type = $type = $form_state
      ->get('type');
    if (!empty($types[$type]['type'])) {
      $handler_type = $types[$type]['type'];
    }
    $override = NULL;
    $view = $form_state
      ->get('view');
    $executable = $view
      ->getExecutable();
    if ($executable->display_handler
      ->useGroupBy() && !empty($item['group_type'])) {
      if (empty($executable->query)) {
        $executable
          ->initQuery();
      }
      $aggregate = $executable->query
        ->getAggregationInfo();
      if (!empty($aggregate[$item['group_type']]['handler'][$type])) {
        $override = $aggregate[$item['group_type']]['handler'][$type];
      }
    }
    
    $handler = Views::handlerManager($handler_type)
      ->getHandler($item, $override);
    $handler
      ->init($executable, $executable->display_handler, $item);
    
    $options = $form_state
      ->getValue('options') + $this->options;
    
    $handler
      ->unpackOptions($handler->options, $options, NULL, FALSE);
    
    $executable = $view
      ->getExecutable();
    $executable->temporary_options[$type][$form_state
      ->get('id')] = $handler->options;
    
    $view
      ->addFormToStack($form_state
      ->get('form_key'), $form_state
      ->get('display_id'), $type, $item['id'], TRUE);
    $form_state
      ->get('rerender', TRUE);
    $form_state
      ->setRebuild();
    
    $view
      ->cacheSet();
  }
  
  public function submitFormCalculateOptions(array $options, array $form_state_options) {
    return $form_state_options + $options;
  }
  
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();
    if ($this->table) {
      
      $data = $this
        ->getViewsData()
        ->get($this->table);
      if (isset($data['table']['provider'])) {
        $dependencies['module'][] = $data['table']['provider'];
      }
    }
    return $dependencies;
  }
}