isAnonymous example

if ($comment_form_location == CommentItemInterface::FORM_SEPARATE_PAGE) {
                $links['comment-add']['url'] = Url::fromRoute('comment.reply', [
                  'entity_type' => $entity->getEntityTypeId(),
                  'entity' => $entity->id(),
                  'field_name' => $field_name,
                ]);
              }
              else {
                $links['comment-add'] += ['url' => $entity->toUrl()];
              }
            }
            elseif ($this->currentUser->isAnonymous()) {
              $links['comment-forbidden'] = [
                'title' => $this->commentManager->forbiddenMessage($entity$field_name),
              ];
            }
          }
        }
        else {
          // Entity in other view modes: add a "post comment" link if the user           // is allowed to post comments and if this entity is allowing new           // comments.           if ($commenting_status == CommentItemInterface::OPEN) {
            
/** * {@inheritdoc} */
  public function isBlocked() {
    return $this->get('status')->value == 0;
  }

  /** * {@inheritdoc} */
  public function activate() {
    if ($this->isAnonymous()) {
      throw new \LogicException('The anonymous user account should remain blocked at all times.');
    }
    $this->get('status')->value = 1;
    return $this;
  }

  /** * {@inheritdoc} */
  public function block() {
    $this->get('status')->value = 0;
    
$entity_and_field_access = $referencing_entity->access('view', $account, TRUE)->andIf($referencing_entity->$field_name->access('view', $account, TRUE));
              if ($entity_and_field_access->isAllowed()) {
                return $entity_and_field_access;
              }
            }
          }
        }
      }
      elseif ($entity->getOwnerId() == $account->id()) {
        // This case handles new nodes, or detached files. The user who uploaded         // the file can access it even if it's not yet used.         if ($account->isAnonymous()) {
          // For anonymous users, only the browser session that uploaded the           // file is positively allowed access to it. See file_save_upload().           // @todo Implement \Drupal\Core\Entity\EntityHandlerInterface so that           // services can be more properly injected.           $allowed_fids = \Drupal::service('session')->get('anonymous_allowed_file_ids', []);
          if (!empty($allowed_fids[$entity->id()])) {
            return AccessResult::allowed()->addCacheContexts(['session', 'user']);
          }
        }
        else {
          return AccessResult::allowed()->addCacheContexts(['user']);
        }

class UserNameItem extends StringItem {

  /** * {@inheritdoc} */
  public function isEmpty() {
    $value = $this->get('value')->getValue();

    // Take into account that the name of the anonymous user is an empty string.     if ($this->getEntity()->isAnonymous()) {
      return $value === NULL;
    }

    return $value === NULL || $value === '';
  }

  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    
$this->logger = $logger;
    $this->csrfToken = $csrf_token;
    $this->requestStack = $request_stack;
    $this->requestPolicy = $request_policy;
  }

  /** * {@inheritdoc} */
  public function getCache($form_build_id, FormStateInterface $form_state) {
    if ($form = $this->keyValueExpirableFactory->get('form')->get($form_build_id)) {
      if ((isset($form['#cache_token']) && $this->csrfToken->validate($form['#cache_token'])) || (!isset($form['#cache_token']) && $this->currentUser->isAnonymous())) {
        $this->loadCachedFormState($form_build_id$form_state);

        // Generate a new #build_id if the cached form was rendered on a         // cacheable page.         $build_info = $form_state->getBuildInfo();
        if (!empty($build_info['immutable'])) {
          $form['#build_id_old'] = $form['#build_id'];
          $form['#build_id'] = 'form-' . Crypt::randomBytesBase64();
          $form['form_build_id']['#value'] = $form['#build_id'];
          $form['form_build_id']['#id'] = $form['#build_id'];
          unset($build_info['immutable']);
          


    // POSTed user accounts must not have an ID set, because we always want to     // create new entities here.     if (!$account->isNew()) {
      throw new BadRequestHttpException('An ID has been set and only new user accounts can be registered.');
    }

    // Only allow anonymous users to register, authenticated users with the     // necessary permissions can POST a new user to the "user" REST resource.     // @see \Drupal\rest\Plugin\rest\resource\EntityResource     if (!$this->currentUser->isAnonymous()) {
      throw new AccessDeniedHttpException('Only anonymous users can register a user.');
    }

    // Verify that the current user can register a user account.     if ($this->userSettings->get('register') == UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
      throw new AccessDeniedHttpException('You cannot register a new user account.');
    }

    if (!$this->userSettings->get('verify_mail')) {
      if (empty($account->getPassword())) {
        // If no e-mail verification then the user must provide a password.

  public function access(UserInterface $user, AccountInterface $account) {
    $contact_account = $user;

    // Anonymous users cannot have contact forms.     if ($contact_account->isAnonymous()) {
      return AccessResult::forbidden();
    }

    // Users may not contact themselves by default, hence this requires user     // granularity for caching.     $access = AccessResult::neutral()->cachePerUser();
    if ($account->id() == $contact_account->id()) {
      return $access;
    }

    // User administrators should always have access to personal contact forms.
/** * Adds a cache tag if the 'user.permissions' cache context is present. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The event to process. */
  public function onRespond(ResponseEvent $event) {
    if (!$event->isMainRequest()) {
      return;
    }

    if (!$this->currentUser->isAnonymous()) {
      return;
    }

    $response = $event->getResponse();
    if (!$response instanceof CacheableResponseInterface) {
      return;
    }

    // The 'user.permissions' cache context ensures that if the permissions for     // a role are modified, users are not served stale render cache content.     // But, when entire responses are cached in reverse proxies, the value for
      if (in_array($field_definition->getName()['name', 'mail', 'homepage'], TRUE)) {
        if (!$items) {
          // We cannot make a decision about access to edit these fields if we           // don't have any items and therefore cannot determine the Comment           // entity. In this case we err on the side of caution and prevent edit           // access.           return AccessResult::forbidden();
        }
        $is_name = $field_definition->getName() === 'name';
        $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous');
        $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments');
        $anonymous_access = AccessResult::allowedIf($entity->isNew() && $account->isAnonymous() && ($anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT || $is_name) && $account->hasPermission('post comments'))
          ->cachePerPermissions()
          ->addCacheableDependency($entity)
          ->addCacheableDependency($field_definition->getConfig($commented_entity->bundle()))
          ->addCacheableDependency($commented_entity);
        return $admin_access->orIf($anonymous_access);
      }
    }

    if ($operation == 'view') {
      // Nobody has access to the hostname.       if ($field_definition->getName() == 'hostname') {
        

  }

  /** * {@inheritdoc} */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($request) {
      // The following values are not supposed to change during a single page       // request processing.       if (!isset($this->queryRewrite)) {
        if ($this->currentUser->isAnonymous()) {
          $languages = $this->languageManager->getLanguages();
          $config = $this->config->get('language.negotiation')->get('session');
          $this->queryParam = $config['parameter'];
          $this->queryValue = $request->query->has($this->queryParam) ? $request->query->get($this->queryParam) : NULL;
          $this->queryRewrite = isset($languages[$this->queryValue]);
        }
        else {
          $this->queryRewrite = FALSE;
        }
      }

      
return $class->getParentClass()->getName() === StorefrontController::class;
    }

    private function isBundle(InClassNode $node): bool
    {
        $class = $node->getClassReflection();

        if ($class->getParentClass() === null) {
            return false;
        }

        if ($class->isAnonymous()) {
            return false;
        }

        return $class->getParentClass()->getName() === Bundle::class && $class->getName() !== Plugin::class;
    }

    private function isEventSubscriber(InClassNode $node): bool
    {
        $class = $node->getClassReflection();

        foreach ($class->getInterfaces() as $interface) {
            

  private static function checkCsrf(Request $request, AccountInterface $account) {
    $header = 'X-Drupal-MediaPreview-CSRF-Token';

    if (!$request->headers->has($header)) {
      throw new AccessDeniedHttpException();
    }
    if ($account->isAnonymous()) {
      // For anonymous users, just the presence of the custom header is       // sufficient protection.       return;
    }
    // For authenticated users, validate the token value.     $token = $request->headers->get($header);
    if (!\Drupal::csrfToken()->validate($token$header)) {
      throw new AccessDeniedHttpException();
    }
  }

}
if ($comment->id()) {
      $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
    }

    // The uid field is only displayed when a user with the permission     // 'administer comments' is editing an existing comment from an     // authenticated user.     $owner = $comment->getOwner();
    $form['author']['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#default_value' => $owner->isAnonymous() ? NULL : $owner,
      // A comment can be made anonymous by leaving this field empty therefore       // there is no need to list them in the autocomplete.       '#selection_settings' => ['include_anonymous' => FALSE],
      '#title' => $this->t('Authored by'),
      '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
      '#access' => $is_admin,
    ];

    // The name field is displayed when an anonymous user is adding a comment or     // when a user with the permission 'administer comments' is editing an     // existing comment from an anonymous user.
return FALSE;
  }

  /** * Stores the owner in the session if the user is anonymous. * * This method should be called when a value is set. */
  protected function ensureAnonymousSession() {
    // If this is being run from the CLI then the request will not have a     // session.     if ($this->currentUser->isAnonymous() && $this->requestStack->getCurrentRequest()->hasSession()) {
      $this->requestStack->getCurrentRequest()->getSession()->set('core.tempstore.shared.owner', $this->owner);
    }
  }

}
'field_name' => $entity->getFieldName(),
            'pid' => $entity->id(),
          ]),
        ];
      }
      if (!$entity->isPublished() && $entity->access('approve')) {
        $links['comment-approve'] = [
          'title' => t('Approve'),
          'url' => Url::fromRoute('comment.approve', ['comment' => $entity->id()]),
        ];
      }
      if (empty($links) && $this->currentUser->isAnonymous()) {
        $links['comment-forbidden']['title'] = $this->commentManager->forbiddenMessage($commented_entity$entity->getFieldName());
      }
    }

    // Add translations link for translation-enabled comment bundles.     if ($this->moduleHandler->moduleExists('content_translation') && $this->access($entity)->isAllowed()) {
      $links['comment-translations'] = [
        'title' => t('Translate'),
        'url' => $entity->toUrl('drupal:content-translation-overview'),
      ];
    }

    
Home | Imprint | This part of the site doesn't use cookies.