You are here

function opigno_messaging_views_query_alter in Opigno messaging 8

Implements hook_views_query_alter().

File

./opigno_messaging.module, line 640
Contains opigno_messaging.module.

Code

function opigno_messaging_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view
    ->id() == 'private_message') {
    static $threads;
    if (!isset($threads)) {

      // Get all message treads of current user.
      $uid = \Drupal::currentUser()
        ->id();
      $threads = OpignoMessageThread::getUserThreads($uid);
      if ($threads) {

        // Get threads delete/access time
        // for whenever deleted threads of current user.
        $db_connection = \Drupal::service('database');
        $query_thread = $db_connection
          ->select('pm_thread_delete_time', 'tdt');
        $query_thread
          ->join('private_message_thread__last_delete_time', 'ldt', 'ldt.last_delete_time_target_id = tdt.id');
        $query_thread
          ->join('private_message_thread__last_access_time', 'tlat', 'tlat.entity_id = ldt.entity_id');
        $query_thread
          ->join('pm_thread_access_time', 'tat', 'tat.id = tlat.last_access_time_target_id AND tat.owner = :uid', [
          ':uid' => $uid,
        ]);
        $query_thread
          ->fields('ldt', [
          'entity_id',
        ])
          ->condition('tdt.owner', $uid)
          ->condition('tdt.delete_time', 0, '>')
          ->condition('tdt.delete_time', 'tat.access_time', '>');
        $deleted_threads = $query_thread
          ->execute()
          ->fetchCol();
        if ($deleted_threads) {

          // Remove deleted threads from threads array.
          $threads = array_diff($threads, $deleted_threads);
        }
      }
    }
    if ($threads) {

      // Add allowed threads to query.
      $query
        ->addWhere('', 'private_message_threads.id', $threads, 'IN');
    }
    else {
      $query
        ->addWhere('', 'private_message_threads.id', [
        0,
      ], 'IN');
    }
  }
}