SimpleSitemapViews.php 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
<?php

namespace Drupal\simple_sitemap_views;

use Drupal\simple_sitemap_views\Plugin\views\display_extender\SimpleSitemapDisplayExtender;
use Drupal\Core\Database\Query\ConditionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Query\Condition;
use Drupal\views\ViewEntityInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\Database\Database;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;

/**
 * Class to manage sitemap data for views.
 */
class SimpleSitemapViews {

  /**
   * Separator between arguments.
   */
  const ARGUMENT_SEPARATOR = '/';

  /**
   * Views display extender plugin ID.
   */
  const PLUGIN_ID = 'simple_sitemap_display_extender';

  /**
   * View entities storage.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $viewStorage;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The queue factory.
   *
   * @var \Drupal\Core\Queue\QueueFactory
   */
  protected $queueFactory;

  /**
   * The current active database's master connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * SimpleSitemapViews constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Queue\QueueFactory $queue_factory
   *   The queue factory.
   * @param \Drupal\Core\Database\Connection $database
   *   The current active database's master connection.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    ConfigFactoryInterface $config_factory,
    QueueFactory $queue_factory,
    Connection $database
  ) {
    $this->viewStorage = $entity_type_manager->getStorage('view');
    $this->configFactory = $config_factory;
    $this->queueFactory = $queue_factory;
    $this->database = $database;
  }

  /**
   * Checks that views support is enabled.
   *
   * @return bool
   *   Returns TRUE if support is enabled, and FALSE otherwise.
   */
  public function isEnabled() {
    // Support enabled when views display extender is enabled.
    $enabled = Views::getEnabledDisplayExtenders();
    return isset($enabled[self::PLUGIN_ID]);
  }

  /**
   * Enables sitemap support for views.
   */
  public function enable() {
    $config = $this->configFactory->getEditable('views.settings');
    $display_extenders = $config->get('display_extenders') ?: [];

    // Enable views display extender plugin.
    $display_extenders[self::PLUGIN_ID] = self::PLUGIN_ID;
    $config->set('display_extenders', $display_extenders);
    $config->save();
  }

  /**
   * Disables sitemap support for views.
   */
  public function disable() {
    $config = $this->configFactory->getEditable('views.settings');
    $display_extenders = $config->get('display_extenders') ?: [];

    // Disable views display extender plugin.
    unset($display_extenders[self::PLUGIN_ID]);
    $config->set('display_extenders', $display_extenders);
    $config->save();
120 121 122 123 124 125

    // Clear the table with indexed arguments.
    // Clear the garbage collection queue.
    $this->removeArgumentsFromIndex();
    $queue = $this->queueFactory->get('simple_sitemap.views.garbage_collector');
    $queue->deleteQueue();
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
  }

  /**
   * Get sitemap settings for view display.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   A view executable instance.
   * @param string|null $display_id
   *   The display id. If empty uses the preselected display.
   *
   * @return array|null
   *   The sitemap settings if the display is indexed, NULL otherwise.
   */
  public function getSitemapSettings(ViewExecutable $view, $display_id = NULL) {
    // Ensure the display was correctly set.
    if (!$view->setDisplay($display_id)) {
      return NULL;
    }
    // Get the list of extenders.
    $extenders = $view->display_handler->getExtenders();
    $extender = isset($extenders[self::PLUGIN_ID]) ? $extenders[self::PLUGIN_ID] : NULL;
    // Retrieve the sitemap settings from the extender.
    if ($extender instanceof SimpleSitemapDisplayExtender && $extender->hasSitemapSettings() && $extender->isIndexingEnabled()) {
      return $extender->getSitemapSettings();
    }
    return NULL;
  }

  /**
   * Get indexable arguments for view display.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   A view executable instance.
   * @param string|null $display_id
   *   The display id. If empty uses the preselected display.
   *
   * @return array
   *   Indexable arguments identifiers.
   */
  public function getIndexableArguments(ViewExecutable $view, $display_id = NULL) {
    $indexable_arguments = [];
    $settings = $this->getSitemapSettings($view, $display_id);
    if ($settings && !empty($settings['arguments']) && is_array($settings['arguments'])) {
      // Find indexable arguments.
      $arguments = array_keys($view->display_handler->getHandlers('argument'));
      foreach ($arguments as $argument_id) {
        if (empty($settings['arguments'][$argument_id])) {
          break;
        }
        $indexable_arguments[] = $argument_id;
      }
    }
    return $indexable_arguments;
  }

  /**
   * Adds view arguments to the index.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   A view executable instance.
   * @param array $args
   *   Array of arguments to add to the index.
   * @param string|null $display_id
   *   The display id. If empty uses the preselected display.
   *
   * @return bool
   *   TRUE if the arguments are added to the index, FALSE otherwise.
   */
  public function addArgumentsToIndex(ViewExecutable $view, array $args, $display_id = NULL) {
    // An array of arguments to be added to the index can not be empty.
    // Also ensure the display was correctly set.
    if (empty($args) || !$view->setDisplay($display_id)) {
      return FALSE;
    }
    // Check that indexing of at least one argument is enabled.
    $indexable_arguments = $this->getIndexableArguments($view);
    if (empty($indexable_arguments)) {
      return FALSE;
    }
    // Check that the number of identifiers is equal to the number of values.
    $args_ids = array_slice($indexable_arguments, 0, count($args));
    if (count($args_ids) != count($args)) {
      return FALSE;
    }
    // Check that the current number of rows in the index does not
    // exceed the specified number.
    $condition = new Condition('AND');
    $condition->condition('view_id', $view->id());
    $condition->condition('display_id', $view->current_display);
    $settings = $this->getSitemapSettings($view);
    $max_links = is_numeric($settings['max_links']) ? $settings['max_links'] : 0;
    if ($max_links > 0 && $this->getArgumentsFromIndexCount($condition) >= $max_links) {
      return FALSE;
    }
    // Convert the set of identifiers and a set of values to string.
    $args_ids = $this->convertArgumentsArrayToString($args_ids);
    $args_values = $this->convertArgumentsArrayToString($args);
    $condition->condition('arguments_ids', $args_ids);
    $condition->condition('arguments_values', $args_values);
    // Check that this set of arguments has not yet been indexed.
    if ($this->getArgumentsFromIndexCount($condition)) {
      return FALSE;
    }
    // Check that the view result is not empty for this set of arguments.
    $params = array_merge([$view->id(), $view->current_display], $args);
    $view_result = call_user_func_array('views_get_view_result', $params);
    if (empty($view_result)) {
      return FALSE;
    }
    // Add a set of arguments to the index.
    $options = ['return' => Database::RETURN_AFFECTED];
    $query = $this->database->insert('simple_sitemap_views', $options);
    $query->fields([
      'view_id' => $view->id(),
      'display_id' => $view->current_display,
      'arguments_ids' => $args_ids,
      'arguments_values' => $args_values,
    ]);
    return (bool) $query->execute();
  }

  /**
   * Get arguments from index.
   *
   * @param \Drupal\Core\Database\Query\ConditionInterface|null $condition
   *   The query conditions.
   * @param int|null $limit
   *   The number of records to return from the result set. If NULL, returns
   *   all records.
   * @param bool $convert
   *   Defaults to FALSE. If TRUE, the argument string will be converted
   *   to an array.
   *
   * @return array
   *   An array with information about the indexed arguments.
   */
  public function getArgumentsFromIndex(ConditionInterface $condition = NULL, $limit = NULL, $convert = FALSE) {
    // Select the rows from the index table.
    $query = $this->database->select('simple_sitemap_views', 'ssv');
    $query->addField('ssv', 'id');
    $query->addField('ssv', 'view_id');
    $query->addField('ssv', 'display_id');
    $query->addField('ssv', 'arguments_values', 'arguments');
    // Add conditions if necessary.
    if (!empty($condition)) {
      $query->condition($condition);
    }
    // Limit results if necessary.
    if (!empty($limit)) {
      $query->range(0, $limit);
    }
    $rows = $query->execute()->fetchAll();
    // Form the result.
    $arguments = [];
    foreach ($rows as $row) {
      $arguments[$row->id] = [
        'view_id' => $row->view_id,
        'display_id' => $row->display_id,
        'arguments' => $convert ? $this->convertArgumentsStringToArray($row->arguments) : $row->arguments,
      ];
    }
    return $arguments;
  }

  /**
   * Get the number of rows in the index.
   *
   * @param \Drupal\Core\Database\Query\ConditionInterface|null $condition
   *   The query conditions.
   *
   * @return int
   *   The number of rows.
   */
  public function getArgumentsFromIndexCount(ConditionInterface $condition = NULL) {
    $query = $this->database->select('simple_sitemap_views', 'ssv');
    // Add conditions if necessary.
    if (!empty($condition)) {
      $query->condition($condition);
    }
    // Get the number of rows from the index table.
    return $query->countQuery()->execute()->fetchField();
  }

  /**
   * Returns the ID of the record in the index for the specified position.
   *
   * @param int $position
   *   Position of the record.
   * @param \Drupal\Core\Database\Query\ConditionInterface|null $condition
   *   The query conditions.
   *
   * @return int|bool
   *   The ID of the record, or FALSE if there is no specified position.
   */
  public function getIndexIdByPosition($position, ConditionInterface $condition = NULL) {
    $query = $this->database->select('simple_sitemap_views', 'ssv');
    $query->addField('ssv', 'id');
    // Add conditions if necessary.
    if (!empty($condition)) {
      $query->condition($condition);
    }
    $query->orderBy('id', 'ASC');
    $query->range($position - 1, 1);
    return $query->execute()->fetchField();
  }

  /**
   * Remove arguments from index.
   *
   * @param \Drupal\Core\Database\Query\ConditionInterface|null $condition
   *   The query conditions.
   */
  public function removeArgumentsFromIndex(ConditionInterface $condition = NULL) {
    if (empty($condition)) {
      // If there are no conditions, use the TRUNCATE query.
      $query = $this->database->truncate('simple_sitemap_views');
    }
    else {
      // Otherwise, use the DELETE query.
      $query = $this->database->delete('simple_sitemap_views');
      $query->condition($condition);
    }
    $query->execute();
  }

  /**
   * Returns an array of view displays that use the route.
   *
   * @param \Drupal\views\ViewEntityInterface $view_entity
   *   The config entity in which the view is stored.
   *
   * @return array
   *   Array of display identifiers.
   */
  public function getRouterDisplayIds(ViewEntityInterface $view_entity) {
    $display_plugins = $this->getRouterDisplayPluginIds();
    $filter_callback = function (array $display) use ($display_plugins) {
      return !empty($display['display_plugin']) && in_array($display['display_plugin'], $display_plugins);
    };
    $displays = array_filter($view_entity->get('display'), $filter_callback);
    return array_keys($displays);
  }

  /**
   * Returns an array of executable views whose current display is indexable.
   *
   * @return \Drupal\views\ViewExecutable[]
   *   An array of ViewExecutable instances.
   */
  public function getIndexableViews() {
    // Check that views support is enabled.
    if (!$this->isEnabled()) {
      return [];
    }
    // Load views with display plugins that use the route.
    $query = $this->viewStorage->getQuery();
    $query->condition('status', TRUE);
    $query->condition("display.*.display_plugin", $this->getRouterDisplayPluginIds(), 'IN');
    $view_ids = $query->execute();
    // If there are no such views, then return an empty array.
    if (empty($view_ids)) {
      return [];
    }

    $indexable_views = [];
    /** @var \Drupal\views\ViewEntityInterface $view_entity */
    foreach ($this->viewStorage->loadMultiple($view_ids) as $view_entity) {
      foreach ($this->getRouterDisplayIds($view_entity) as $display_id) {
        $view = Views::executableFactory()->get($view_entity);
        // Ensure the display was correctly set.
        if (!$view->setDisplay($display_id)) {
          $view->destroy();
          continue;
        }

        // Check that the display is enabled and indexed.
        if ($view->display_handler->isEnabled() && $this->getSitemapSettings($view)) {
          $indexable_views[] = $view;
        }
      }
    }
    return $indexable_views;
  }

  /**
   * Creates tasks in the garbage collection queue.
   */
  public function executeGarbageCollection() {
    // The task queue of garbage collection in the arguments index.
    $queue = $this->queueFactory->get('simple_sitemap.views.garbage_collector');
    // Check that the queue is empty.
    if ($queue->numberOfItems()) {
      return;
    }
    // Get identifiers of indexed views.
    $query = $this->database->select('simple_sitemap_views', 'ssv');
    $query->addField('ssv', 'view_id');
    $query->distinct();
    $result = $query->execute()->fetchCol();
    // Create a garbage collection tasks.
    foreach ($result as $view_id) {
      $queue->createItem(['view_id' => $view_id]);
    }
  }

  /**
   * Get variations for string representation of arguments.
   *
   * @param array $args
   *   Array of arguments.
   *
   * @return array
   *   Array of variations of the string representation of arguments.
   */
  public function getArgumentsStringVariations(array $args) {
    $variations = [];
    for ($length = 1; $length <= count($args); $length++) {
      $args_slice = array_slice($args, 0, $length);
      $variations[] = $this->convertArgumentsArrayToString($args_slice);
    }
    return $variations;
  }

  /**
   * Converts an array of arguments to a string.
   *
   * @param array $args
   *   Array of arguments to convert.
   *
   * @return string
   *   A string representation of the arguments.
   */
  protected function convertArgumentsArrayToString(array $args) {
    return implode(self::ARGUMENT_SEPARATOR, $args);
  }

  /**
   * Converts a string with arguments to an array.
   *
   * @param string $args
   *   A string representation of the arguments to convert.
   *
   * @return array
   *   Array of arguments.
   */
  protected function convertArgumentsStringToArray($args) {
    return explode(self::ARGUMENT_SEPARATOR, $args);
  }

  /**
   * Get all display plugins that use the route.
   *
   * @return array
   *   An array with plugin identifiers.
   */
  protected function getRouterDisplayPluginIds() {
    static $plugin_ids = [];
    if (empty($plugin_ids)) {
      // Get all display plugins that use the route.
      $display_plugins = Views::pluginManager('display')->getDefinitions();
      foreach ($display_plugins as $plugin_id => $definition) {
        if (!empty($definition['uses_route'])) {
          $plugin_ids[$plugin_id] = $plugin_id;
        }
      }
    }
    return $plugin_ids;
  }

}