knowledge-8.x-1.x-dev/src/KnowledgeStatistics.php

src/KnowledgeStatistics.php
<?php

namespace Drupal\knowledge;

use Drupal\Component\Datetime\Time;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager;
use Drupal\user\EntityOwnerInterface;

/**
 * Calculates statistics for knowledge links.
 */
class KnowledgeStatistics implements KnowledgeStatisticsInterface {

  use StringTranslationTrait;

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

  /**
   * The replica database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $databaseReplica;

  /**
   * The current logged in user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * The system time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The search API content tracking service.
   *
   * @var \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager|null
   */
  protected $trackingManager;

  /**
   * The knowledge workflow.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $workflow;

  /**
   * The knowledge settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $settings;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs the KnowledgeStatistics service.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The active database connection.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current logged in user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   * @param \Drupal\Component\Datetime\Time $time
   *   Provides system time.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\Core\Database\Connection|null $database_replica
   *   (Optional) the replica database connection.
   * @param \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager|null $tracking_manager
   *   (Optional) The search api tracking manager.
   */
  public function __construct(
    Connection $database,
    AccountInterface $current_user,
    EntityTypeManagerInterface $entity_type_manager,
    StateInterface $state,
    Time $time,
    EntityFieldManagerInterface $entity_field_manager,
    ModuleHandlerInterface $module_handler,
    ConfigFactoryInterface $config_factory,
    MessengerInterface $messenger,
    ?Connection $database_replica = NULL,
    ?ContentEntityTrackingManager $tracking_manager = NULL,
  ) {
    $this->database = $database;
    $this->databaseReplica = $database_replica ?: $database;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->state = $state;
    $this->time = $time;
    $this->entityFieldManager = $entity_field_manager;
    $this->moduleHandler = $module_handler;
    $this->trackingManager = $tracking_manager;
    $this->settings = $config_factory->get('knowledge.settings');
    $this->workflow = $config_factory->get('workflows.workflow.knowledge');
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public function read($entities, $entity_type, $accurate = TRUE) {
    $connection = $accurate ? $this->database : $this->databaseReplica;
    $stats = $connection->select('knowledge_entity_statistics', 'ces')
      ->fields('ces')
      ->condition('ces.entity_id', array_keys($entities), 'IN')
      ->condition('ces.entity_type', $entity_type)
      ->execute();

    $statistics_records = [];
    while ($entry = $stats->fetchObject()) {
      $statistics_records[] = $entry;
    }
    return $statistics_records;
  }

  /**
   * {@inheritdoc}
   */
  public function delete(EntityInterface $entity) {
    $this->database->delete('knowledge_entity_statistics')
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->getEntityTypeId())
      ->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function create(FieldableEntityInterface $entity, $fields) {
    $query = $this->database->insert('knowledge_entity_statistics')
      ->fields([
        'entity_id',
        'entity_type',
        'field_name',
        'first_knowledge',
        'first_knowledge_timestamp',
        'first_knowledge_uid',
        'last_knowledge',
        'last_knowledge_timestamp',
        'last_knowledge_uid',
        'total_count',
        'long_count',
        'medium_count',
        'short_count',
        'state_count',
        'state_citation',
        'total_citation',
        'long_citation',
        'medium_citation',
        'short_citation',
      ]);
    foreach ($fields as $field_name => $detail) {
      // Skip fields that entity does not have.
      if (!$entity->hasField($field_name)) {
        continue;
      }
      // Get the user ID from the entity if it's set, or default to the
      // currently logged in user.
      $last_knowledge_uid = 0;
      if ($entity instanceof EntityOwnerInterface) {
        $last_knowledge_uid = $entity->getOwnerId();
      }
      if (!isset($last_knowledge_uid)) {
        // Default to current user when entity does not implement
        // EntityOwnerInterface or author is not set.
        $last_knowledge_uid = $this->currentUser->id();
      }
      // Default to $this->time->getRequestTime() when entity does not have
      // a changed property.
      $last_knowledge_timestamp = $this->time->getRequestTime();
      // @todo Make knowledge statistics language aware and add some tests. See
      //   https://www.drupal.org/node/2318875
      if ($entity instanceof EntityChangedInterface) {
        $last_knowledge_timestamp = $entity->getChangedTimeAcrossTranslations();
      }
      $query->values([
        'entity_id' => $entity->id(),
        'entity_type' => $entity->getEntityTypeId(),
        'field_name' => $field_name,
        'first_knowledge' => 0,
        'first_knowledge_timestamp' => $last_knowledge_timestamp,
        'first_knowledge_uid' => $last_knowledge_uid,
        'last_knowledge' => 0,
        'last_knowledge_timestamp' => $last_knowledge_timestamp,
        'last_knowledge_uid' => $last_knowledge_uid,
        'total_count' => 0,
        'long_count' => 0,
        'medium_count' => 0,
        'short_count' => 0,
        'state_count' => 0,
        'state_citation' => 0,
        'total_citation' => 0,
        'long_citation' => 0,
        'medium_citation' => 0,
        'short_citation' => 0,
      ]);
    }
    $query->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function getMaximumCount($entity_type) {
    return $this->database->query('
    SELECT MAX([total_count])
    FROM {knowledge_entity_statistics}
    WHERE [entity_type] = :entity_type',
    [':entity_type' => $entity_type])->fetchField();
  }

  /**
   * {@inheritdoc}
   */
  public function getRankingInfo() {
    return [
      'knowledge' => [
        'title' => $this->t('Number of knowledge'),
        'join' => [
          'type' => 'LEFT',
          'table' => 'knowledge_entity_statistics',
          'alias' => 'ces',
          // Default to knowledge field as this is the most common use case for
          // nodes.
          'on' => "ces.entity_id = i.sid AND ces.entity_type = 'node' AND ces.field_name = 'knowledge'",
        ],
        // Inverse law that maps the highest view count on the site to 1 and 0
        // to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite
        // in order to ensure that the :knowledge_scale argument is treated as
        // a numeric type, because the PostgreSQL PDO driver sometimes puts
        // values in as strings instead of numbers in complex expressions like
        // this.
        'score' => '2.0 - 2.0 / (1.0 + ces.total_count * (ROUND(:knowledge_scale, 4)))',
        'arguments' => [':knowledge_scale' => $this->state->get('knowledge.node_knowledge_statistics_scale', 0)],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function update(KnowledgeInterface $knowledge) {
    // Allow bulk updates and inserts to temporarily disable the maintenance of
    // the {knowledge_entity_statistics} table.
    if (!$this->state->get('knowledge.maintain_entity_statistics')) {
      return;
    }

    $entity = $knowledge->getKnowledgeedEntity();
    $entity_type = $knowledge->getKnowledgeedEntityTypeId();
    $entity_id = $knowledge->getKnowledgeedEntityId();
    $field_name = $knowledge->getFieldName();

    [$count, $citation] = $this->getPeriod($entity_type, $entity_id, $field_name);
    [$state_count, $state_citation] = $this->getStateCount($entity_type, $entity_id, $field_name);

    if ($count > 0) {
      // Knowledge exist.
      $storage = $this->entityFieldManager
        ->getFieldStorageDefinitions($entity_type);
      $field_storage = $storage[$field_name];
      if (is_null($field_storage)) {
        return NULL;
      }
      $today = strtotime('today');
      $short_period = $today - $field_storage->getSetting('short_period') * KnowledgeStatisticsInterface::HOURS_24;
      $medium_period = $today - $field_storage->getSetting('medium_period') * KnowledgeStatisticsInterface::HOURS_24;
      $long_period = $today - $field_storage->getSetting('long_period') * KnowledgeStatisticsInterface::HOURS_24;

      [$short_count, $short_citation] = $this->getPeriod($entity_type, $entity_id, $field_name, $short_period);

      [$medium_count, $medium_citation] = $this->getPeriod($entity_type, $entity_id, $field_name, $medium_period);

      [$long_count, $long_citation] = $this->getPeriod($entity_type, $entity_id, $field_name, $long_period);

      $last_reply = $this->database->select('knowledge', 'c')
        ->fields('c', ['kid', 'changed', 'uid'])
        ->condition('c.entity_id', $entity_id)
        ->condition('c.entity_type', $entity_type)
        ->condition('c.field_name', $field_name)
        ->condition('c.status', KnowledgeInterface::PUBLISHED)
        ->orderBy('c.created', 'DESC')
        ->range(0, 1)
        ->execute()
        ->fetchObject();

      $fields = [
        'total_count' => $count,
        'long_count' => $long_count,
        'medium_count' => $medium_count,
        'short_count' => $short_count,
        'state_count' => $state_count,

        'total_citation' => $citation ?? 0,
        'long_citation' => $long_citation ?? 0,
        'medium_citation' => $medium_citation ?? 0,
        'short_citation' => $short_citation ?? 0,
        'state_citation' => $state_citation ?? 0,

        'last_knowledge' => $last_reply->kid,
        'last_knowledge_timestamp' => $last_reply->changed,
        'last_knowledge_uid' => $last_reply->uid,
      ];

      if ($count == 1) {
        $fields['first_knowledge'] = $last_reply->kid;
        $fields['first_knowledge_timestamp'] = $last_reply->changed;
        $fields['first_knowledge_uid'] = $last_reply->uid;
      }
      // Use merge here because entity could be created before knowledge field.
      $this->database->merge('knowledge_entity_statistics')
        ->fields($fields)
        ->keys([
          'entity_id' => $entity_id,
          'entity_type' => $entity_type,
          'field_name' => $field_name,
        ])
        ->execute();
    }
    else {
      // Get the user ID from the entity if it's set, or default to the
      // currently logged in user.
      if ($entity instanceof EntityOwnerInterface) {
        $last_knowledge_uid = $entity->getOwnerId();
      }
      if (!isset($last_knowledge_uid)) {
        // Default to current user when entity does not implement
        // EntityOwnerInterface or author is not set.
        $last_knowledge_uid = $this->currentUser->id();
      }
      $this->database->update('knowledge_entity_statistics')
        ->fields([
          'total_count' => 0,
          'long_count' => 0,
          'medium_count' => 0,
          'short_count' => 0,
          'state_count' => 0,
          'state_citation' => 0,
          'total_citation' => 0,
          'long_citation' => 0,
          'medium_citation' => 0,
          'short_citation' => 0,
          'last_knowledge' => 0,
          'last_knowledge_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : $this->time->getRequestTime(),
          'last_knowledge_uid' => $last_knowledge_uid,
          'first_knowledge' => 0,
          'first_knowledge_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : $this->time->getRequestTime(),
          'first_knowledge_uid' => $last_knowledge_uid,
        ])
        ->condition('entity_id', $entity_id)
        ->condition('entity_type', $entity_type)
        ->condition('field_name', $field_name)
        ->execute();
    }

    // Reset the cache of the knowledge link entity so that when the entity is
    // loaded the next time, the statistics will be loaded again.
    $this->entityTypeManager
      ->getStorage($entity_type)
      ->resetCache([$entity_id]);
    if ($this->moduleHandler->moduleExists('search_api')) {
      $this->trackingManager->entityUpdate($entity);
    }

    $this->doStateCountAction($state_count, $state_citation, $entity);
  }

  /**
   * Perform an action in relatien to the state count.
   */
  protected function doStateCountAction($count, $citation, $entity) {
    $confidence = $entity->get('moderation_state')->value;
    $transition = $this->getNextState($confidence);
    $next_state = $transition['to'] ?? NULL;
    if (is_null($next_state)) {
      return;
    }
    $c = 'actions.' . $confidence . '__' . $next_state;

    $config = $this->settings->get($c);

    if (is_null($config)) {
      return;
    }
    $action = $config['action'] ?? 'none';
    if ($action == 'none') {
      return;
    }

    $config_count = $config['count'];
    if ($count < $config_count) {
      return;
    }
    if ($config['frequency'] == 'every' && ($count % $config_count) != 0) {
      return;
    }

    switch ($action) {
      case 'message':
        if ($entity->access('edit', $this->currentUser)) {
          $this->messenger->addWarning($config['message']);
        }
        break;

      case 'promote':
        $entity->set('moderation_state', $next_state);
        $entity->save();
        break;

    }

  }

  /**
   * Returns the next Moderation satate.
   */
  protected function getNextState($current_state) {
    $states = $this->workflow->get('type_settings.states');
    unset($states['published']);
    foreach ($states as $name => $state) {
      if ($state['published'] == FALSE) {
        unset($states[$name]);
      }
    }
    uasort($states, [$this, 'sort']);

    $st_key = array_keys($states);

    $transitions = $this->workflow->get('type_settings.transitions');

    uasort($transitions, [$this, 'sort']);

    $cs_index = array_search($current_state, $st_key);

    $next_index = $cs_index + 1;

    $next_state = $st_key[$next_index] ?? NULL;

    foreach ($transitions as $name => $transition) {
      if ($transition['to'] == $next_state && in_array($current_state, $transition['from'])) {
        return $transition;
      }
    }
  }

  /**
   * A usort function by weight.
   */
  public function sort($a, $b) {
    if ($a['weight'] == $b['weight']) {
      return 0;
    }

    return ($a['weight'] < $b['weight']) ? -1 : 1;
  }

  /**
   * Return link counts for a period.
   */
  protected function getPeriod($entity_type, $entity_id, $field_name, $period = NULL) {
    $query = $this->database->select('knowledge', 'c');
    $query->addExpression('COUNT([kid])', 'count');
    $query->addExpression('SUM([citation])', 'citation');
    $query->condition('c.entity_id', $entity_id)
      ->condition('c.entity_type', $entity_type)
      ->condition('c.field_name', $field_name)
      ->condition('c.status', KnowledgeInterface::PUBLISHED);

    if (!is_null($period)) {
      $query->condition('c.created', $period, '>');
    }

    $result = $query->execute()->fetchAll();

    $count = $result[0]->count;
    $citation = $result[0]->citation;

    return [$count, $citation];
  }

  /**
   * Returns the link count in the current state.
   */
  protected function getStateCount($entity_type, $entity_id, $field_name) {
    $query = $this->database->select('content_moderation_state_field_data', 'c')->fields('c', ['id', 'moderation_state']);
    $content_moderation_state = $query->condition('c.content_entity_id', $entity_id)
      ->condition('c.content_entity_type_id', $entity_type)
      ->execute()
      ->fetchAll();

    $content_moderation_state_id = $content_moderation_state[0]->id;
    $moderation_state = $content_moderation_state[0]->moderation_state;

    $query = $this->database
      ->select('content_moderation_state_field_revision', 'c')
      ->fields('c', ['moderation_state', 'content_entity_revision_id']);
    $content_moderation_state_revision = $query->condition('c.id', $content_moderation_state_id)
      ->orderBy('content_entity_revision_id', 'DESC')
      ->execute()
      ->fetchAll();

    $revision_ids = [];
    foreach ($content_moderation_state_revision as $revision) {
      if ($revision->moderation_state != $moderation_state) {
        break;
      }
      $revision_ids[] = $revision->content_entity_revision_id;
    }

    $query = $this->database->select('knowledge', 'c');
    $query->addExpression('COUNT([kid])', 'count');
    $query->addExpression('SUM([citation])', 'citation');
    $query->condition('c.entity_id', $entity_id)
      ->condition('c.entity_type', $entity_type)
      ->condition('c.field_name', $field_name)
      ->condition('c.status', KnowledgeInterface::PUBLISHED)
      ->condition('c.entity_revision', $revision_ids, 'IN');
    $result = $query->execute()->fetchAll();

    $count = $result[0]->count;
    $citation = $result[0]->citation;

    return [$count, $citation];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc