knowledge-8.x-1.x-dev/src/Controller/KnowledgeController.php

src/Controller/KnowledgeController.php
<?php

namespace Drupal\knowledge\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\knowledge\KnowledgeInterface;
use Drupal\knowledge\KnowledgeManagerInterface;
use Drupal\knowledge\Plugin\Field\FieldType\KnowledgeItemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Controller for the knowledge entity.
 *
 * @see \Drupal\knowledge\Entity\Knowledge.
 */
class KnowledgeController extends ControllerBase {

  /**
   * The HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * The knowledge manager service.
   *
   * @var \Drupal\knowledge\KnowledgeManagerInterface
   */
  protected $knowledgeManager;

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

  /**
   * The entity repository.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * Constructs a KnowledgeController object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   HTTP kernel to handle requests.
   * @param \Drupal\knowledge\KnowledgeManagerInterface $knowledge_manager
   *   The knowledge manager service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   */
  public function __construct(HttpKernelInterface $http_kernel, KnowledgeManagerInterface $knowledge_manager, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, EntityRepositoryInterface $entity_repository) {
    $this->httpKernel = $http_kernel;
    $this->knowledgeManager = $knowledge_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->entityRepository = $entity_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('http_kernel'),
      $container->get('knowledge.manager'),
      $container->get('entity_type.manager'),
      $container->get('entity_field.manager'),
      $container->get('entity.repository')
    );
  }

  /**
   * Publishes the specified knowledge.
   *
   * @param \Drupal\knowledge\KnowledgeInterface $knowledge
   *   A knowledge entity.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirects the user to the knowledge link's permalink.
   */
  public function knowledgeApprove(KnowledgeInterface $knowledge) {
    $knowledge->setPublished();
    $knowledge->save();

    $this->messenger()->addStatus($this->t('Knowledge approved.'));
    $permalink_uri = $knowledge->permalink();
    $permalink_uri->setAbsolute();
    return new RedirectResponse($permalink_uri->toString());
  }

  /**
   * Redirects links to the correct page depending on knowledge settings.
   *
   * Since knowledge paged there is no way to guarantee which page a knowledge
   * appears on. Knowledge paging and threading settings may be changed at any
   * time. With threaded knowledge, an individual knowledge may move between
   * pages as knowledge can be added either before or after it in the overall
   * discussion. Therefore we use a central routing function for knowledge
   * links, which calculates the page number based on current knowledge settings
   * and returns the full knowledge view with the pager set dynamically.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   * @param \Drupal\knowledge\KnowledgeInterface $knowledge
   *   A knowledge entity.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The knowledge listing set to the page on which the knowledge appears.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   */
  public function knowledgePermalink(Request $request, KnowledgeInterface $knowledge) {
    if ($entity = $knowledge->getKnowledgeedEntity()) {
      // Check access permissions for the entity.
      if (!$entity->access('view')) {
        throw new AccessDeniedHttpException();
      }
      $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$knowledge->getFieldName()];

      // Find the current display page for this knowledge.
      /** @var \Drupal\knowledge\KnowledgeStorageInterface $knowledge_storage */
      $knowledge_storage = $this->entityTypeManager()->getStorage('knowledge');
      $page = $knowledge_storage->getDisplayOrdinal($knowledge, $field_definition->getSetting('default_mode'), $field_definition->getSetting('per_page'));
      // @todo Cleaner sub request handling.
      $subrequest_url = $entity->toUrl()->setOption('query', ['page' => $page])->toString(TRUE);
      $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all(), $request->cookies->all(), [], $request->server->all());
      // Carry over the session to the subrequest.
      if ($request->hasSession()) {
        $redirect_request->setSession($request->getSession());
      }
      $request->query->set('page', $page);
      $response = $this->httpKernel->handle($redirect_request, HttpKernelInterface::SUB_REQUEST);
      if ($response instanceof CacheableResponseInterface) {
        // @todo Once path aliases have cache tags (see
        //   https://www.drupal.org/node/2480077), add test coverage that
        //   the cache tag for a linked entity's path alias is added to the
        //   knowledge's permalink response, because there can be blocks or
        //   other content whose renderings depend on the subrequest's URL.
        $response->addCacheableDependency($subrequest_url);
      }
      return $response;
    }
    throw new NotFoundHttpException();
  }

  /**
   * The _title_callback for the page that renders the knowledge permalink.
   *
   * @param \Drupal\knowledge\KnowledgeInterface $knowledge
   *   The current knowledge.
   *
   * @return string
   *   The translated knowledge subject.
   */
  public function knowledgePermalinkTitle(KnowledgeInterface $knowledge) {
    return $this->entityRepository->getTranslationFromContext($knowledge)->label();
  }

  /**
   * Redirects legacy node links to the new path.
   *
   * @param \Drupal\Core\Entity\EntityInterface $node
   *   The node object identified by the legacy URL.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirects user to new url.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function redirectNode(EntityInterface $node) {
    $fields = $this->knowledgeManager->getFields('node');
    // Legacy nodes only had a single knowledge field, so use the first
    // knowledge field on the entity.
    if (!empty($fields) && ($field_names = array_keys($fields)) && ($field_name = reset($field_names))) {
      return $this->redirect('knowledge.reply', [
        'entity_type' => 'node',
        'entity' => $node->id(),
        'field_name' => $field_name,
      ]);
    }
    throw new NotFoundHttpException();
  }

  /**
   * Form constructor for the knowledge reply form.
   *
   * There are several cases that have to be handled, including:
   *   - replies to knowledge
   *   - replies to entities.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity this knowledge belongs to.
   * @param string $field_name
   *   The field_name to which the knowledge belongs.
   *
   * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
   *   An associative array containing:
   *   - An array for rendering the entity or parent knowledge.
   *     - knowledge_entity: If the knowledge is a reply to the entity.
   *   - knowledge_form: The knowledge form as a renderable array.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function getReplyForm(Request $request, EntityInterface $entity, $field_name) {
    $account = $this->currentUser();
    $build = [];

    // The user is not just previewing a knowledge.
    if ($request->request->get('op') != $this->t('Preview')) {

      // The knowledge is in response to an entity.
      if ($entity->access('view', $account)) {
        // We make sure the field value isn't set so we don't end up with a
        // redirect loop.
        $entity = clone $entity;
        $entity->{$field_name}->status = KnowledgeItemInterface::HIDDEN;
        // Render array of the entity full view mode.
        $build['linked_entity'] = $this->entityTypeManager()->getViewBuilder($entity->getEntityTypeId())->view($entity, 'full');
        unset($build['linked_entity']['#cache']);
      }
    }
    else {
      $build['#title'] = $this->t('Preview knowledge');
    }

    // Show the actual reply box.
    $knowledge = $this->entityTypeManager()->getStorage('knowledge')->create([
      'entity_id' => $entity->id(),
      'entity_type' => $entity->getEntityTypeId(),
      'field_name' => $field_name,
    ]);
    $build['knowledge_form'] = $this->entityFormBuilder()->getForm($knowledge);

    return $build;
  }

  /**
   * Access check for the reply form.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity this knowledge belongs to.
   * @param string $field_name
   *   The field_name to which the knowledge belongs.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   An access result
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function replyFormAccess(EntityInterface $entity, $field_name) {
    // Check if entity and field exists.
    $fields = $this->knowledgeManager->getFields($entity->getEntityTypeId());
    if (empty($fields[$field_name])) {
      throw new NotFoundHttpException();
    }

    $account = $this->currentUser();

    // Check if the user has the proper permissions.
    $access = AccessResult::allowedIfHasPermission($account, 'post knowledge');

    // If linking is open on the entity.
    $status = $entity->{$field_name}->status;
    $access = $access->andIf(AccessResult::allowedIf($status == KnowledgeItemInterface::OPEN)
      ->addCacheableDependency($entity))
      // And if user has access to the host entity.
      ->andIf(AccessResult::allowedIf($entity->access('view')));

    return $access;
  }

  /**
   * Returns a set of nodes' last read timestamps.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function renderNewKnowledgesNodeLinks(Request $request) {
    if ($this->currentUser()->isAnonymous()) {
      throw new AccessDeniedHttpException();
    }

    $nids = $request->request->get('node_ids');
    $field_name = $request->request->get('field_name');
    if (!isset($nids)) {
      throw new NotFoundHttpException();
    }
    // Only handle up to 100 nodes.
    $nids = array_slice($nids, 0, 100);

    $links = [];
    foreach ($nids as $nid) {
      $node = $this->entityTypeManager()->getStorage('node')->load($nid);
      $new = $this->knowledgeManager->getCountNewKnowledges($node);

      /** @var \Drupal\knowledge\KnowledgeStorageInterface $knowledge_storage */
      $knowledge_storage = $this->entityTypeManager()->getStorage('knowledge');
      $page_number = $knowledge_storage
        ->getNewKnowledgePageNumber($node->{$field_name}->total_count, $new, $node, $field_name);
      $query = $page_number ? ['page' => $page_number] : NULL;
      $links[$nid] = [
        'new_total_count' => (int) $new,
        'first_new_knowledge_link' => Url::fromRoute('entity.node.canonical', [
          'node' => $node->id(),
        ], ['query' => $query, 'fragment' => 'new'])->toString(),
      ];
    }

    return new JsonResponse($links);
  }

}

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

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