You are here

class LdapQuery in Lightweight Directory Access Protocol (LDAP) 8.4

Same name and namespace in other branches
  1. 8.3 ldap_query/src/Plugin/views/query/LdapQuery.php \Drupal\ldap_query\Plugin\views\query\LdapQuery

Views query plugin for an SQL query.

Plugin annotation


@ViewsQuery(
  id = "ldap_query",
  title = @Translation("LDAP Query"),
  help = @Translation("Query will be generated and run via LDAP.")
)

Hierarchy

Expanded class hierarchy of LdapQuery

1 file declares its use of LdapQuery
ViewsSortTest.php in ldap_query/tests/src/Unit/ViewsSortTest.php

File

ldap_query/src/Plugin/views/query/LdapQuery.php, line 24

Namespace

Drupal\ldap_query\Plugin\views\query
View source
class LdapQuery extends QueryPluginBase {

  /**
   * Collection of filter criteria.
   *
   * @var array
   */
  public $where = [];

  /**
   * Collection of sort criteria.
   *
   * @var array
   */
  public $orderby = [];

  /**
   * Maps SQL operators to LDAP operators.
   *
   * @var array
   */
  private const LDAP_FILTER_OPERATORS = [
    'AND' => '&',
    'OR' => '|',
  ];

  /**
   * {@inheritdoc}
   */
  public function build(ViewExecutable $view) : void {

    // Store the view in the object to be able to use it later.
    $this->view = $view;
    $view
      ->initPager();

    // Let the pager modify the query to add limits.
    $view->pager
      ->query();
    $view->build_info['query'] = $this
      ->query();
    $view->build_info['count_query'] = $this
      ->query(TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() : int {
    return 0;
  }

  /**
   * Execute the query.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view.
   *
   * @return bool|void
   *   Nothing if query can be executed.
   */
  public function execute(ViewExecutable $view) {
    if (!isset($this->options['query_id']) || empty($this->options['query_id'])) {
      \Drupal::logger('ldap')
        ->error('You are trying to use Views without having chosen an LDAP Query under Advanced => Query settings.');
      return FALSE;
    }
    $start = microtime(TRUE);

    // @todo Dependency Injection.

    /** @var \Drupal\ldap_query\Controller\QueryController $controller */
    $controller = \Drupal::service('ldap.query');
    $controller
      ->load($this->options['query_id']);
    $filter = $this
      ->buildLdapFilter($controller
      ->getFilter());
    $controller
      ->execute($filter);
    $results = $controller
      ->getRawResults();
    $fields = $controller
      ->availableFields();
    $index = 0;
    $rows = [];
    foreach ($results as $result) {
      $row = [];
      foreach ($fields as $field_key => $void) {
        if ($result
          ->hasAttribute($field_key, FALSE)) {
          $row[$field_key] = $result
            ->getAttribute($field_key, FALSE);
        }
      }
      $row['dn'] = [
        0 => $result
          ->getDn(),
      ];
      $row['index'] = $index++;
      $rows[] = $row;
    }
    if (!empty($this->orderby) && !empty($rows)) {
      $rows = $this
        ->sortResults($rows);
    }
    foreach ($rows as $row) {
      $view->result[] = new ResultRow($row);
    }

    // Pager.
    $totalItems = count($view->result);
    $offset = $view->pager
      ->getCurrentPage() * $view->pager
      ->getItemsPerPage() + $view->pager
      ->getOffset();
    $length = NULL;
    if ($view->pager
      ->getItemsPerPage() > 0) {

      // A Views ExposedInput for items_for_page will return a string value
      // via a querystring parameter.
      $length = (int) $view->pager
        ->getItemsPerPage();
    }
    if ($offset > 0 || $length > 0) {
      $view->result = array_splice($view->result, $offset, $length);
    }
    $view->pager
      ->postExecute($view->result);
    $view->pager->total_items = $totalItems;
    $view->pager
      ->updatePageInfo();
    $view->total_rows = $view->pager
      ->getTotalItems();

    // Timing information.
    $view->execute_time = microtime(TRUE) - $start;
  }

  /**
   * Sort the results.
   *
   * @param array $rows
   *   Results to operate on.
   *
   * @return array
   *   Result data.
   *
   * @todo Should be private, public for easier testing.
   */
  public function sortResults(array $rows) : array {
    $sorts = $this->orderby;
    foreach ($sorts as $sort) {
      foreach ($rows as $key => $row) {
        $rows[$key]['sort_' . $sort['field']] = $row[$sort['field']][0] ?? '';
      }
    }
    $multisortParameters = [];
    foreach ($sorts as $sort) {
      $multisortParameters[] = array_column($rows, 'sort_' . $sort['field']);
      $multisortParameters[] = mb_strtoupper($sort['direction']) === 'ASC' ? SORT_ASC : SORT_DESC;
    }
    $multisortParameters[] =& $rows;
    array_multisort(...$multisortParameters);
    return $rows;
  }

  /**
   * {@inheritdoc}
   */
  public function ensureTable($table, $relationship = NULL) : string {
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function addField($table, $field, $alias = '', $params = []) {
    return $field;
  }

  /**
   * {@inheritdoc}
   */
  public function addOrderBy($table, $field, $order, $alias = '', $params = []) : void {
    $this->orderby[] = [
      'field' => $field,
      'direction' => $order,
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() : array {
    $options = parent::defineOptions();
    $options['query_id'] = [
      'default' => NULL,
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) : void {
    parent::buildOptionsForm($form, $form_state);
    $queries = \Drupal::EntityQuery('ldap_query_entity')
      ->condition('status', 1)
      ->execute();
    $form['query_id'] = [
      '#type' => 'select',
      '#options' => $queries,
      '#title' => $this
        ->t('Ldap Query'),
      '#default_value' => $this->options['query_id'],
      '#description' => $this
        ->t('The LDAP query you want Views to use.'),
      '#required' => TRUE,
    ];
  }

  /**
   * Add a simple WHERE clause to the query.
   *
   * @param mixed $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param mixed $field
   *   The name of the field to check.
   * @param mixed $value
   *   The value to test the field against. In most cases, this is a scalar. For
   *   more complex options, it is an array. The meaning of each element in the
   *   array is dependent on the $operator.
   * @param mixed $operator
   *   The comparison operator, such as =, <, or >=. It also accepts more
   *   complex options such as IN, LIKE, LIKE BINARY, or BETWEEN. Defaults to =.
   *   If $field is a string you have to use 'formula' here.
   */
  public function addWhere($group, $field, $value = NULL, $operator = NULL) : void {

    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
    // the default group.
    if (empty($group)) {
      $group = 0;
    }

    // Check for a group.
    if (!isset($this->where[$group])) {
      $this
        ->setWhereGroup('AND', $group);
    }
    if (!empty($operator) && $operator !== 'LIKE') {
      $this->where[$group]['conditions'][] = [
        'field' => $field,
        'value' => $value,
        'operator' => $operator,
      ];
    }
  }

  /**
   * Compiles all conditions into a set of LDAP requirements.
   *
   * @return string|null
   *   Condition string.
   */
  public function buildConditions() : ?string {
    $groups = [];
    foreach ($this->where as $group) {
      if (!empty($group['conditions'])) {
        $conditions = '';
        foreach ($group['conditions'] as $clause) {
          $conditions .= $this
            ->translateCondition($clause['field'], $clause['value'], $clause['operator']);
        }
        if (count($group['conditions']) > 1) {
          $groups[] = '(' . self::LDAP_FILTER_OPERATORS[$group['type']] . $conditions . ')';
        }
        else {
          $groups[] = $conditions;
        }
      }
    }
    if (count($groups) > 1) {
      $output = '(' . self::LDAP_FILTER_OPERATORS[$this->groupOperator] . implode('', $groups) . ')';
    }
    else {
      $output = array_pop($groups);
    }
    return $output;
  }

  /**
   * Collates Views arguments and filters for a modified query.
   *
   * @param string $standardFilter
   *   The filter in LDAP query which gets overwritten.
   *
   * @return string
   *   Combined string.
   */
  private function buildLdapFilter(string $standardFilter) : string {
    $searchFilter = $this
      ->buildConditions();
    if (!empty($searchFilter)) {
      $finalFilter = '(&' . $standardFilter . $searchFilter . ')';
    }
    else {
      $finalFilter = $standardFilter;
    }
    return $finalFilter;
  }

  /**
   * Produces a filter condition and adds optional negation.
   *
   * @param string $field
   *   LDAP attribute name.
   * @param string $value
   *   Field value.
   * @param string $operator
   *   Negation operator.
   *
   * @return string
   *   LDAP filter such as (cn=Example).
   */
  private function translateCondition(string $field, string $value, string $operator) : string {
    if (mb_strpos($operator, '!') === 0) {
      $condition = sprintf('(!(%s=%s))', $field, Html::escape($value));
    }
    else {
      $condition = sprintf('(%s=%s)', $field, Html::escape($value));
    }
    return $condition;
  }

  /**
   * Let modules modify the query just prior to finalizing it.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   View.
   */
  public function alter(ViewExecutable $view) : void {
    \Drupal::moduleHandler()
      ->invokeAll('views_query_alter', [
      $view,
      $this,
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
LdapQuery::$orderby public property Collection of sort criteria.
LdapQuery::$where public property Collection of filter criteria.
LdapQuery::addField public function
LdapQuery::addOrderBy public function
LdapQuery::addWhere public function Add a simple WHERE clause to the query.
LdapQuery::alter public function Let modules modify the query just prior to finalizing it. Overrides QueryPluginBase::alter
LdapQuery::build public function Builds the necessary info to execute the query. Overrides QueryPluginBase::build
LdapQuery::buildConditions public function Compiles all conditions into a set of LDAP requirements.
LdapQuery::buildLdapFilter private function Collates Views arguments and filters for a modified query.
LdapQuery::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides PluginBase::buildOptionsForm
LdapQuery::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides PluginBase::defineOptions
LdapQuery::ensureTable public function
LdapQuery::execute public function Execute the query. Overrides QueryPluginBase::execute
LdapQuery::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides QueryPluginBase::getCacheMaxAge
LdapQuery::LDAP_FILTER_OPERATORS private constant Maps SQL operators to LDAP operators.
LdapQuery::sortResults public function Sort the results.
LdapQuery::translateCondition private function Produces a filter condition and adds optional negation.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 62
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::init public function Initialize the plugin. Overrides ViewsPluginInterface::init 8
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::validate public function Validate that the plugin is correct and can be saved. Overrides ViewsPluginInterface::validate 6
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
PluginBase::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct
QueryPluginBase::$limit protected property Stores the limit of items that should be requested in the query.
QueryPluginBase::$pager public property A pager plugin that should be provided by the display.
QueryPluginBase::addSignature public function Add a signature to the query, if such a thing is feasible. 1
QueryPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies 1
QueryPluginBase::getAggregationInfo public function Get aggregation info for group by queries. 1
QueryPluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
QueryPluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 1
QueryPluginBase::getDateField public function Returns a Unix timestamp to database native timestamp expression. 1
QueryPluginBase::getDateFormat public function Creates cross-database date formatting. 1
QueryPluginBase::getEntityTableInfo public function Returns an array of all tables from the query that map to an entity type.
QueryPluginBase::getLimit public function Returns the limit of the query.
QueryPluginBase::getTimezoneOffset public function Get the timezone offset in seconds.
QueryPluginBase::loadEntities public function Loads all entities contained in the passed-in $results. . If the entity belongs to the base table, then it gets stored in $result->_entity. Otherwise, it gets stored in $result->_relationship_entities[$relationship_id]; 1
QueryPluginBase::query public function Generate a query and a countquery from all of the information supplied to the object. Overrides PluginBase::query 1
QueryPluginBase::setFieldTimezoneOffset public function Applies a timezone offset to the given field. 2
QueryPluginBase::setGroupOperator public function Control how all WHERE and HAVING groups are put together.
QueryPluginBase::setLimit public function Set a LIMIT on the query, specifying a maximum number of results.
QueryPluginBase::setOffset public function Set an OFFSET on the query, specifying a number of results to skip
QueryPluginBase::setupTimezone public function Set the database to the current user timezone. 1
QueryPluginBase::setWhereGroup public function Create a new grouping for the WHERE or HAVING clause.
QueryPluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides PluginBase::submitOptionsForm 1
QueryPluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides PluginBase::summaryTitle
QueryPluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.