You are here

class AjaxController in Private Message 8

Same name and namespace in other branches
  1. 8.2 src/Controller/AjaxController.php \Drupal\private_message\Controller\AjaxController

Controller to handle Ajax requests.

Hierarchy

Expanded class hierarchy of AjaxController

File

src/Controller/AjaxController.php, line 27

Namespace

Drupal\private_message\Controller
View source
class AjaxController extends ControllerBase implements AjaxControllerInterface {
  const AUTOCOMPLETE_COUNT = 10;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The entity manager service.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

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

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

  /**
   * The private message service.
   *
   * @var \Drupal\private_message\Service\PrivateMessageServiceInterface
   */
  protected $privateMessageService;

  /**
   * Constructs n AjaxController object.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entityManager
   *   The entity manager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The configuration factory.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   * @param \Drupal\private_message\Service\PrivateMessageServiceInterface $privateMessageService
   *   The private message service.
   */
  public function __construct(RendererInterface $renderer, RequestStack $requestStack, EntityManagerInterface $entityManager, ConfigFactoryInterface $configFactory, AccountProxyInterface $currentUser, PrivateMessageServiceInterface $privateMessageService) {
    $this->renderer = $renderer;
    $this->requestStack = $requestStack;
    $this->entityManager = $entityManager;
    $this->configFactory = $configFactory;
    $this->currentUser = $currentUser;
    $this->privateMessageService = $privateMessageService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('renderer'), $container
      ->get('request_stack'), $container
      ->get('entity.manager'), $container
      ->get('config.factory'), $container
      ->get('current_user'), $container
      ->get('private_message.service'));
  }

  /**
   * {@inheritdoc}
   */
  public function ajaxCallback($op) {
    $response = new AjaxResponse();
    if ($this->currentUser
      ->hasPermission('use private messaging system')) {
      switch ($op) {
        case 'get_new_messages':
          $this
            ->getNewPrivateMessages($response);
          break;
        case 'get_old_messages':
          $this
            ->getOldPrivateMessages($response);
          break;
        case 'get_old_inbox_threads':
          $this
            ->getOldInboxThreads($response);
          break;
        case 'get_new_inbox_threads':
          $this
            ->getNewInboxThreads($response);
          break;
        case 'validate_private_message_member_username':
          $this
            ->validatePrivateMessageMemberUsername($response);
          break;
        case 'get_new_unread_thread_count':
          $this
            ->getNewUnreadThreadCount($response);
          break;
        case 'load_thread':
          $this
            ->loadThread($response);
          break;
      }
    }
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function privateMessageMembersAutocomplete() {
    $response = new AjaxResponse();
    $username = $this->requestStack
      ->getCurrentRequest()
      ->get('username');
    $accounts = $this->privateMessageService
      ->getUsersFromString($username, self::AUTOCOMPLETE_COUNT);
    $user_info = [];
    foreach ($accounts as $account) {
      if ($account
        ->access('view', $this->currentUser)) {
        $user_info[] = [
          'uid' => $account
            ->id(),
          'username' => $account
            ->getDisplayName(),
        ];
      }
    }
    $response
      ->addCommand(new PrivateMessageMembersAutocompleteResponseCommand($username, $user_info));
    return $response;
  }

  /**
   * Creates an Ajax Command containing new private message.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function getNewPrivateMessages(AjaxResponse $response) {
    $thread_id = $this->requestStack
      ->getCurrentRequest()
      ->get('threadid');
    $message_id = $this->requestStack
      ->getCurrentRequest()
      ->get('messageid');
    if (is_numeric($thread_id) && is_numeric($message_id)) {
      $new_messages = $this->privateMessageService
        ->getNewMessages($thread_id, $message_id);
      if (count($new_messages)) {
        $messages = [];
        $view_builder = $this->entityManager
          ->getViewBuilder('private_message');
        foreach ($new_messages as $message) {
          if ($message
            ->access('view', $this->currentUser)) {
            $messages[] = $view_builder
              ->view($message);
          }
        }
        $response
          ->addCommand(new PrivateMessageInsertNewMessagesCommand($this->renderer
          ->renderRoot($messages)));
      }
    }
  }

  /**
   * Create an Ajax Command containing old private messages.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function getOldPrivateMessages(AjaxResponse $response) {
    $current_request = $this->requestStack
      ->getCurrentRequest();
    $thread_id = $current_request
      ->get('threadid');
    $message_id = $current_request
      ->get('messageid');
    if (is_numeric($thread_id) && is_numeric($message_id)) {
      $message_info = $this->privateMessageService
        ->getPreviousMessages($thread_id, $message_id);
      if (count($message_info)) {
        $messages = [];
        $view_builder = $this->entityManager
          ->getViewBuilder('private_message');
        foreach ($message_info as $message) {
          if ($message
            ->access('view', $this->currentUser)) {
            $messages[] = $view_builder
              ->view($message);
          }
        }
        $response
          ->addCommand(new PrivateMessageInsertPreviousMessagesCommand($this->renderer
          ->renderRoot($messages)));
      }
      else {
        $response
          ->addCommand(new PrivateMessageInsertPreviousMessagesCommand(''));
      }
    }
  }

  /**
   * Creates and Ajax Command containing old threads for the inbox.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function getOldInboxThreads(AjaxResponse $response) {
    $timestamp = $this->requestStack
      ->getCurrentRequest()
      ->get('timestamp');
    $thread_count = $this->requestStack
      ->getCurrentRequest()
      ->get('count');
    if (is_numeric($timestamp)) {
      $thread_info = $this->privateMessageService
        ->getThreadsForUser($thread_count, $timestamp);
      if (count($thread_info['threads'])) {
        $oldest_timestamp = FALSE;
        $view_builder = $this->entityManager
          ->getViewBuilder('private_message_thread');
        $threads = [];
        foreach ($thread_info['threads'] as $thread) {
          if ($thread
            ->access('view', $this->currentUser)) {
            if ($thread_info['next_exists']) {
              $oldest_timestamp = $thread
                ->get('updated')->value;
            }
            $threads[] = $view_builder
              ->view($thread, 'inbox');
          }
        }
        $response
          ->addCommand(new PrivateMessageInboxInsertThreadsCommand($this->renderer
          ->renderRoot($threads), $oldest_timestamp));
      }
      else {
        $response
          ->addCommand(new PrivateMessageInboxInsertThreadsCommand('', FALSE));
      }
    }
  }

  /**
   * Creates an Ajax Command with new threads for the private message inbox.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function getNewInboxThreads(AjaxResponse $response) {
    $info = $this->requestStack
      ->getCurrentRequest()
      ->get('ids');

    // Check to see if any thread IDs were POSTed.
    if (is_array($info) && count($info)) {

      // Get new inbox information based on the posted IDs.
      $inbox_threads = $this->privateMessageService
        ->getUpdatedInboxThreads($info);
    }
    else {

      // No IDs were posted, so the maximum possible number of threads to be
      // returned is retrieved from the block settings.
      $thread_count = $this->configFactory
        ->get('block.block.privatemessageinbox')
        ->get('settings.thread_count');
      $inbox_threads = $this->privateMessageService
        ->getUpdatedInboxThreads([], $thread_count);
    }

    // Only need to do something if any thread IDS were found.
    if (count($inbox_threads['thread_ids'])) {
      $view_builder = $this->entityManager
        ->getViewBuilder('private_message_thread');

      // Render any new threads as HTML to be sent to the browser.
      $rendered_threads = [];
      foreach (array_keys($inbox_threads['new_threads']) as $thread_id) {
        if ($inbox_threads['new_threads'][$thread_id]
          ->access('view', $this->currentUser)) {
          $renderable = $view_builder
            ->view($inbox_threads['new_threads'][$thread_id], 'inbox');
          $rendered_threads[$thread_id] = $this->renderer
            ->renderRoot($renderable);
        }
      }

      // Add the command that will tell the inbox which thread items to update.
      $response
        ->addCommand(new PrivateMessageInboxUpdateCommand($inbox_threads['thread_ids'], $rendered_threads));
    }
  }

  /**
   * Create Ajax Command determining whether a given username is valid.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function validatePrivateMessageMemberUsername(AjaxResponse $response) {
    $username = $this->requestStack
      ->getCurrentRequest()
      ->get('username');
    $valid = $this->privateMessageService
      ->validatePrivateMessageMemberUsername($username);
    $response
      ->addCommand(new PrivateMessageMemberUsernameValidatedCommand($username, $valid));
  }

  /**
   * Create Ajax Command returning the number of unread private message threads.
   *
   * Only messages created since the current user last visited the private
   * message page are shown.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function getNewUnreadThreadCount(AjaxResponse $response) {
    $unread_thread_count = $this->privateMessageService
      ->getUnreadThreadCount();
    $response
      ->addCommand(new PrivateMessageUpdateUnreadThreadCountCommand($unread_thread_count));
  }

  /**
   * Load a private message thread to be dynamically inserted into the page.
   *
   * @param Drupal\Core\Ajax\AjaxResponse $response
   *   The response to which any commands should be attached.
   */
  protected function loadThread(AjaxResponse $response) {
    $thread_id = $this->requestStack
      ->getCurrentRequest()
      ->get('id');
    if ($thread_id) {
      $thread = PrivateMessageThread::load($thread_id);
      if ($thread && $thread
        ->access('view', $this->currentUser)) {
        $this->privateMessageService
          ->updateLastCheckTime();
        $view_builder = $this->entityManager
          ->getViewBuilder('private_message_thread');
        $renderable = $view_builder
          ->view($thread);
        $rendered_thread = $this->renderer
          ->renderRoot($renderable);
        $index = array_search('private_message/private_message_thread', $renderable['#attached']['library']);
        unset($renderable['#attached']['library'][$index]);
        $response
          ->setAttachments($renderable['#attached']);
        $response
          ->addCommand(new PrivateMessageInsertThreadCommand($rendered_thread));
        $unread_thread_count = $this->privateMessageService
          ->getUnreadThreadCount();
        $response
          ->addCommand(new PrivateMessageUpdateUnreadThreadCountCommand($unread_thread_count));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxController::$configFactory protected property The configuration factory. Overrides ControllerBase::$configFactory
AjaxController::$currentUser protected property The current user. Overrides ControllerBase::$currentUser
AjaxController::$entityManager protected property The entity manager service. Overrides ControllerBase::$entityManager
AjaxController::$privateMessageService protected property The private message service.
AjaxController::$renderer protected property The renderer service.
AjaxController::$requestStack protected property The request stack.
AjaxController::ajaxCallback public function Create AJAX responses for JavaScript requests. Overrides AjaxControllerInterface::ajaxCallback
AjaxController::AUTOCOMPLETE_COUNT constant
AjaxController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
AjaxController::getNewInboxThreads protected function Creates an Ajax Command with new threads for the private message inbox.
AjaxController::getNewPrivateMessages protected function Creates an Ajax Command containing new private message.
AjaxController::getNewUnreadThreadCount protected function Create Ajax Command returning the number of unread private message threads.
AjaxController::getOldInboxThreads protected function Creates and Ajax Command containing old threads for the inbox.
AjaxController::getOldPrivateMessages protected function Create an Ajax Command containing old private messages.
AjaxController::loadThread protected function Load a private message thread to be dynamically inserted into the page.
AjaxController::privateMessageMembersAutocomplete public function Create AJAX response containing usernames for an autocomplete callback. Overrides AjaxControllerInterface::privateMessageMembersAutocomplete
AjaxController::validatePrivateMessageMemberUsername protected function Create Ajax Command determining whether a given username is valid.
AjaxController::__construct public function Constructs n AjaxController object.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.