function testUserTokens() { // Add a user picture to the account. $image = current($this->drupalGetTestFiles('image')); $edit = array('files[user_picture_0]' => drupal_realpath($image->uri)); $this->drupalPostForm('user/' . $this->account->id() . '/edit', $edit, t('Save')); $storage = \Drupal::entityManager()->getStorage('user'); // Load actual user data from database. $storage->resetCache(); $this->account = $storage->load($this->account->id()); $this->assertTrue(!empty($this->account->user_picture->target_id), 'User picture uploaded.'); $picture = ['#theme' => 'user_picture', '#account' => $this->account]; /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $user_tokens = array('picture' => $renderer->render($picture), 'picture:fid' => $this->account->user_picture->target_id, 'picture:size-raw' => 125, 'ip-address' => NULL, 'roles' => implode(', ', $this->account->getRoles())); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // Remove the simpletest-created user role. $roles = $this->account->getRoles(); $this->account->removeRole(end($roles)); $this->account->save(); // Remove the user picture field and reload the user. FieldStorageConfig::loadByName('user', 'user_picture')->delete(); $storage->resetCache(); $this->account = $storage->load($this->account->id()); $user_tokens = array('picture' => NULL, 'picture:fid' => NULL, 'ip-address' => NULL, 'roles' => 'authenticated', 'roles:keys' => (string) DRUPAL_AUTHENTICATED_RID); $this->assertTokens('user', array('user' => $this->account), $user_tokens); // The ip address token should work for the current user token type. $tokens = array('ip-address' => \Drupal::request()->getClientIp()); $this->assertTokens('current-user', array(), $tokens); $anonymous = new AnonymousUserSession(); $tokens = array('roles' => 'anonymous', 'roles:keys' => (string) DRUPAL_ANONYMOUS_RID); $this->assertTokens('user', array('user' => $anonymous), $tokens); }
/** * {@inheritdoc} */ public function log($level, $message, array $context = array()) { // Merge in defaults. $context += array('channel' => $this->channel, 'link' => '', 'user' => NULL, 'uid' => 0, 'request_uri' => '', 'referer' => '', 'ip' => '', 'timestamp' => time()); // Some context values are only available when in a request context. if ($this->requestStack && ($request = $this->requestStack->getCurrentRequest())) { $context['request_uri'] = $request->getUri(); $context['referer'] = $request->headers->get('Referer', ''); $context['ip'] = $request->getClientIP(); try { if ($this->currentUser) { $context['user'] = $this->currentUser; $context['uid'] = $this->currentUser->id(); } } catch (\Exception $e) { // An exception might be thrown if the database connection is not // available or due to another unexpected reason. It is more important // to log the error that we already have so any additional exceptions // are ignored. } } if (is_string($level)) { // Convert to integer equivalent for consistency with RFC 5424. $level = $this->levelTranslation[$level]; } // Call all available loggers. foreach ($this->sortLoggers() as $logger) { $logger->log($level, $message, $context); } }
/** * User object. * * @return \Drupal\moodle\Sql\User */ public function user() { // Static cache of already retrieved user data. $data =& drupal_static(__METHOD__, array()); $user_cid = "moodle-user:{$this->user->id()}"; // If we do not have this user id in the static cache, check {cache_data}. if (!isset($data[$user_cid])) { $cache = $this->cacheBackend->get($user_cid); if ($cache && $cache->data && isset($cache->data[$user_cid])) { $data[$user_cid] = $cache->data[$user_cid]; } } // If nothing in the cache then retrieve it from the database. if (!isset($data[$user_cid])) { $user = new User(); $this->query(); $this->addFields(); $statement = $this->query->execute(); $statement->setFetchMode(\PDO::FETCH_INTO, $user); $data[$user_cid] = $statement->fetch(); // Store the results for a day. $this->cacheBackend->set($user_cid, $data, REQUEST_TIME + 86400); } return $data[$user_cid]; }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If the user is already logged in, redirect to their profile page. $event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()])); return; } if ($path == 'user/register') { // If the user is already registered, redirect to their edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * {@inheritdoc} */ public function onBlockActiveContext(BlockContextEvent $event) { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $event->setContext('user.current_user', $context); }
/** * Tests adding and editing values using metatag. */ public function testMetatag() { // Create a test entity. $edit = ['name[0][value]' => 'Barfoo', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'Barfoo']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); // Update the Global defaults and test them. $values = array('keywords' => 'Purple monkey dishwasher'); $this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save'); $this->assertText('Saved the Global Metatag defaults.'); $this->drupalGet('entity_test/' . $entity->id()); $elements = $this->cssSelect('meta[name=keywords]'); $this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $values['keywords'], 'Default keywords applied'); // Tests metatags with urls work. $edit = ['name[0][value]' => 'UrlTags', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')', 'field_metatag[0][open_graph][og_url]' => 'http://example.com/foo.html']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'UrlTags']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); $this->drupalGet('entity_test/' . $entity->id()); $elements = $this->cssSelect("meta[property='og:url']"); $this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $edit['field_metatag[0][open_graph][og_url]']); }
/** * Determine whether the page is configured to be offline. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ public function onKernelRequestMaintenance(GetResponseEvent $event) { $request = $event->getRequest(); $route_match = RouteMatch::createFromRequest($request); $path = $request->attributes->get('_system_path'); if ($this->maintenanceMode->applies($route_match)) { // If the site is offline, log out unprivileged users. if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) { user_logout(); // Redirect to homepage. $event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE]))); return; } if ($this->account->isAnonymous() && $path == 'user') { // Forward anonymous user to login page. $event->setResponse(new RedirectResponse($this->url('user.login', [], ['absolute' => TRUE]))); return; } } if ($this->account->isAuthenticated()) { if ($path == 'user/login') { // If user is logged in, redirect to 'user' instead of giving 403. $event->setResponse(new RedirectResponse($this->url('user.page', [], ['absolute' => TRUE]))); return; } if ($path == 'user/register') { // Authenticated user should be redirected to user edit page. $event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE]))); return; } } }
/** * {@inheritdoc} */ protected function determineBlockContext() { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $this->addContext('current_user', $context); }
/** * {@inheritdoc} */ public function executeMultiple(array $entities) { $info = []; /** @var \Drupal\tmgmt_local\LocalTaskInterface $task */ foreach ($entities as $task) { $info[$task->id()] = $task; } $this->tempStore->set($this->currentUser->id(), $info); }
/** * {@inheritdoc} */ public function executeMultiple(array $entities) { $info = []; /** @var \Drupal\support_ticket\SupportTicketInterface $support_ticket */ foreach ($entities as $support_ticket) { $langcode = $support_ticket->language()->getId(); $info[$support_ticket->id()][$langcode] = $langcode; } $this->tempStore->set($this->currentUser->id(), $info); }
/** * {@inheritdoc} */ public function executeMultiple(array $entities) { $info = []; /** @var \Drupal\node\NodeInterface $node */ foreach ($entities as $node) { $langcode = $node->language()->getId(); $info[$node->id()][$langcode] = $langcode; } $this->tempStore->set($this->currentUser->id(), $info); }
/** * {@inheritdoc} */ public function executeMultiple(array $entities) { /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */ $selection = []; foreach ($entities as $entity) { $langcode = $entity->language()->getId(); $selection[$entity->id()][$langcode] = $langcode; } $this->tempStore->set($this->currentUser->id(), $selection); }
/** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context->addCacheableDependency($cacheability); $result = ['current_user' => $context]; return $result; }
/** * Inform the node access system what permissions the user has. * * This hook is for implementation by node access modules. In this hook, * the module grants a user different "grant IDs" within one or more * "realms". In hook_node_access_records(), the realms and grant IDs are * associated with permission to view, edit, and delete individual nodes. * * The realms and grant IDs can be arbitrarily defined by your node access * module; it is common to use role IDs as grant IDs, but that is not required. * Your module could instead maintain its own list of users, where each list has * an ID. In that case, the return value of this hook would be an array of the * list IDs that this user is a member of. * * A node access module may implement as many realms as necessary to properly * define the access privileges for the nodes. Note that the system makes no * distinction between published and unpublished nodes. It is the module's * responsibility to provide appropriate realms to limit access to unpublished * content. * * Node access records are stored in the {node_access} table and define which * grants are required to access a node. There is a special case for the view * operation -- a record with node ID 0 corresponds to a "view all" grant for * the realm and grant ID of that record. If there are no node access modules * enabled, the core node module adds a node ID 0 record for realm 'all'. Node * access modules can also grant "view all" permission on their custom realms; * for example, a module could create a record in {node_access} with: * @code * $record = array( * 'nid' => 0, * 'gid' => 888, * 'realm' => 'example_realm', * 'grant_view' => 1, * 'grant_update' => 0, * 'grant_delete' => 0, * ); * db_insert('node_access')->fields($record)->execute(); * @endcode * And then in its hook_node_grants() implementation, it would need to return: * @code * if ($op == 'view') { * $grants['example_realm'] = array(888); * } * @endcode * If you decide to do this, be aware that the node_access_rebuild() function * will erase any node ID 0 entry when it is called, so you will need to make * sure to restore your {node_access} record after node_access_rebuild() is * called. * * For a detailed example, see node_access_example.module. * * @param \Drupal\Core\Session\AccountInterface $account * The account object whose grants are requested. * @param string $op * The node operation to be performed, such as 'view', 'update', or 'delete'. * * @return array * An array whose keys are "realms" of grants, and whose values are arrays of * the grant IDs within this realm that this user is being granted. * * @see node_access_view_all_nodes() * @see node_access_rebuild() * @ingroup node_access */ function hook_node_grants(\Drupal\Core\Session\AccountInterface $account, $op) { if ($account->hasPermission('access private content')) { $grants['example'] = array(1); } if ($account->id()) { $grants['example_author'] = array($account->id()); } return $grants; }
/** * {@inheritdoc} */ public function executeMultiple(array $entities) { $info = []; /** @var \Drupal\magic_cards\CardBaseInterface $card */ foreach ($entities as $card) { $langcode = $card->language()->getId(); $info[$card->id()][$langcode] = $langcode; } $this->tempStore->set($this->currentUser->id(), $info); }
/** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { $current_user = $this->userStorage->load($this->account->id()); $context1 = new Context(new ContextDefinition('entity:user', 'User 1'), $current_user); $context2 = new Context(new ContextDefinition('entity:user', 'User 2'), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context1->addCacheableDependency($cacheability); $context2->addCacheableDependency($cacheability); return ['user1' => $context1, 'user2' => $context2]; }
/** * {@inheritdoc} * * Cached by role, invalidated whenever permissions change. */ public function generate(AccountInterface $account) { // User 1 is the super user, and can always access all permissions. Use a // different, unique identifier for the hash. if ($account->id() == 1) { return $this->hash('is-super-user'); } $sorted_roles = $account->getRoles(); sort($sorted_roles); $role_list = implode(',', $sorted_roles); $cid = "user_permissions_hash:{$role_list}"; if ($static_cache = $this->static->get($cid)) { return $static_cache->data; } else { $tags = Cache::buildTags('config:user.role', $sorted_roles, '.'); if ($cache = $this->cache->get($cid)) { $permissions_hash = $cache->data; } else { $permissions_hash = $this->doGenerate($sorted_roles); $this->cache->set($cid, $permissions_hash, Cache::PERMANENT, $tags); } $this->static->set($cid, $permissions_hash, Cache::PERMANENT, $tags); } return $permissions_hash; }
/** * Checks access to the given user's contact page. * * @param \Drupal\user\UserInterface $user * The user being contacted. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return string * A \Drupal\Core\Access\AccessInterface constant value. */ public function access(UserInterface $user, AccountInterface $account) { $contact_account = $user; // Anonymous users cannot have contact forms. if ($contact_account->isAnonymous()) { return static::DENY; } // Users may not contact themselves. if ($account->id() == $contact_account->id()) { return static::DENY; } // User administrators should always have access to personal contact forms. if ($account->hasPermission('administer users')) { return static::ALLOW; } // If requested user has been blocked, do not allow users to contact them. if ($contact_account->isBlocked()) { return static::DENY; } // If the requested user has disabled their contact form, do not allow users // to contact them. $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled'); if (isset($account_data) && empty($account_data)) { return static::DENY; } else { if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) { return static::DENY; } } return $account->hasPermission('access user contact forms') ? static::ALLOW : static::DENY; }
public function access(AccountInterface $account) { if (!$account->id() == 1) { return AccessResult::forbidden(); } return AccessResult::allowed(); }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $config = $this->configFactory->get('payment_reference.payment_type'); $payment = $this->paymentFactory->createPayment($this->fieldDefinition); $element['target_id'] = array('#default_value' => isset($items[$delta]) ? (int) $items[$delta]->target_id : NULL, '#limit_allowed_plugin_ids' => $config->get('limit_allowed_plugins') ? $config->get('allowed_plugin_ids') : NULL, '#plugin_selector_id' => $config->get('plugin_selector_id'), '#prototype_payment' => $payment, '#queue_category_id' => $items->getEntity()->getEntityTypeId() . '.' . $items->getEntity()->bundle() . '.' . $this->fieldDefinition->getName(), '#queue_owner_id' => (int) $this->currentUser->id(), '#required' => $this->fieldDefinition->isRequired(), '#type' => 'payment_reference'); return $element; }
/** * {@inheritdoc} */ public function userBlogPosts(UserInterface $user) { $build = array(); $query = db_select('node_field_data', 'n'); $query->addTag('node_access'); $query->condition('type', 'blog'); $query->condition('status', 1); $query->condition('uid', $user->id()); $count_query = clone $query; $count_query->addExpression('Count(n.nid)'); $paged_query = $query->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender'); $paged_query->limit($this->configFactory->get('node.settings')->get('items_per_page')); $paged_query->setCountQuery($count_query); $nids = $paged_query->fields('n', array('nid', 'sticky', 'created'))->condition('type', 'blog')->orderBy('sticky', 'DESC')->orderBy('created', 'DESC')->execute()->fetchCol(); if (!empty($nids)) { $nodes = node_load_multiple($nids); $build['nodes'] = node_view_multiple($nodes); $build['pager'] = array('#theme' => 'pager', '#weight' => 5); $build['#attached']['feed'][] = array('/blog/' . $user->id() . '/feed', t('RSS - !title', array('!title' => $user->getUsername() . t("'s blog")))); } else { if ($this->account->id() == $user->id()) { drupal_set_message(t('You have not created any blog entries.')); } else { drupal_set_message(t('!author has not created any blog entries.', array('!author' => $user->getUsername()))); } } return $build; }
/** * Grants access only to UID 1. * * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(AccountInterface $account) { if ($account->id() == 1) { return AccessResult::allowed()->addCacheContexts(['user']); } return AccessResult::forbidden()->addCacheContexts(['user']); }
protected function checkAccess(ContentEntityInterface $entity, AccountInterface $account, $operation = 'view') { $entity_type = $entity->getEntityType(); $entity_type_id = $entity->getEntityTypeId(); $entity_access = $this->entityTypeManager->getAccessControlHandler($entity_type_id); /** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */ $entity_storage = $this->entityTypeManager->getStorage($entity_type_id); $map = ['view' => "view all {$entity_type_id} revisions", 'update' => "revert all {$entity_type_id} revisions", 'delete' => "delete all {$entity_type_id} revisions"]; $bundle = $entity->bundle(); $type_map = ['view' => "view {$entity_type_id} {$bundle} revisions", 'update' => "revert {$entity_type_id} {$bundle} revisions", 'delete' => "delete {$entity_type_id} {$bundle} revisions"]; if (!$entity || !isset($map[$operation]) || !isset($type_map[$operation])) { // If there was no node to check against, or the $op was not one of the // supported ones, we return access denied. return FALSE; } // Statically cache access by revision ID, language code, user account ID, // and operation. $langcode = $entity->language()->getId(); $cid = $entity->getRevisionId() . ':' . $langcode . ':' . $account->id() . ':' . $operation; if (!isset($this->accessCache[$cid])) { // Perform basic permission checks first. if (!$account->hasPermission($map[$operation]) && !$account->hasPermission($type_map[$operation]) && !$account->hasPermission('administer nodes')) { $this->accessCache[$cid] = FALSE; return FALSE; } if (($admin_permission = $entity_type->getAdminPermission()) && $account->hasPermission($admin_permission)) { $this->accessCache[$cid] = TRUE; } else { // First check the access to the default revision and finally, if the // node passed in is not the default revision then access to that, too. $this->accessCache[$cid] = $entity_access->access($entity_storage->load($entity->id()), $operation, $account) && ($entity->isDefaultRevision() || $entity_access->access($entity, $operation, $account)); } } return $this->accessCache[$cid]; }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { if ($entity->getOwnerId() == $account->id()) { return AccessResult::allowedIfHasPermission($account, $operation . ' own ' . $entity->bundle() . ' entity'); } return AccessResult::allowedIfHasPermission($account, $operation . ' any ' . $entity->bundle() . ' entity'); }
/** * Checks access to the given user's contact page. * * @param \Drupal\user\UserInterface $user * The user being contacted. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ 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. if ($account->id() == $contact_account->id()) { return AccessResult::forbidden()->cachePerUser(); } // User administrators should always have access to personal contact forms. $access = AccessResult::neutral()->cachePerRole(); $permission_access = AccessResult::allowedIfHasPermission($account, 'administer users'); if ($permission_access->isAllowed()) { return $access->orIf($permission_access); } // If requested user has been blocked, do not allow users to contact them. $access->cacheUntilEntityChanges($contact_account); if ($contact_account->isBlocked()) { return $access; } // If the requested user has disabled their contact form, do not allow users // to contact them. $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled'); if (isset($account_data) && empty($account_data)) { return $access; } else { if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) { return $access; } } return $access->orIf(AccessResult::allowedIfHasPermission($account, 'access user contact forms')); }
/** * {@inheritdoc} */ public function validateArgument($argument) { if (!parent::validateArgument($argument)) { return FALSE; } // Extract the IDs from the argument. See parent::validateArgument(). if ($this->multipleCapable && $this->options['multiple']) { $user_ids = array_filter(preg_split('/[,+ ]/', $argument)); } else { $user_ids = [$argument]; } // Allow access when the current user has access to view all payments, or // when the current user only tries to view their own payments and has // permission to do so. return [$this->currentUser->id()] == $user_ids && $this->currentUser->hasPermission('payment.payment.view.own') || $this->currentUser->hasPermission('payment.payment.view.any'); }
/** * {@inheritdoc} */ public function update(CommentInterface $comment) { // Allow bulk updates and inserts to temporarily disable the maintenance of // the {comment_entity_statistics} table. if (!$this->state->get('comment.maintain_entity_statistics')) { return; } $query = $this->database->select('comment_field_data', 'c'); $query->addExpression('COUNT(cid)'); $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->execute()->fetchField(); if ($count > 0) { // Comments exist. $last_reply = $this->database->select('comment_field_data', 'c')->fields('c', array('cid', 'name', 'changed', 'uid'))->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->orderBy('c.created', 'DESC')->range(0, 1)->execute()->fetchObject(); // Use merge here because entity could be created before comment field. $this->database->merge('comment_entity_statistics')->fields(array('cid' => $last_reply->cid, 'comment_count' => $count, 'last_comment_timestamp' => $last_reply->changed, 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name, 'last_comment_uid' => $last_reply->uid))->keys(array('entity_id' => $comment->getCommentedEntityId(), 'entity_type' => $comment->getCommentedEntityTypeId(), 'field_name' => $comment->getFieldName()))->execute(); } else { // Comments do not exist. $entity = $comment->getCommentedEntity(); // Get the user ID from the entity if it's set, or default to the // currently logged in user. if ($entity instanceof EntityOwnerInterface) { $last_comment_uid = $entity->getOwnerId(); } if (!isset($last_comment_uid)) { // Default to current user when entity does not implement // EntityOwnerInterface or author is not set. $last_comment_uid = $this->currentUser->id(); } $this->database->update('comment_entity_statistics')->fields(array('cid' => 0, 'comment_count' => 0, 'last_comment_timestamp' => $entity instanceof EntityChangedInterface ? $entity->getChangedTime() : REQUEST_TIME, 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid))->condition('entity_id', $comment->getCommentedEntityId())->condition('entity_type', $comment->getCommentedEntityTypeId())->condition('field_name', $comment->getFieldName())->execute(); } // Reset the cache of the commented entity so that when the entity is loaded // the next time, the statistics will be loaded again. $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId())); }
/** * {@inheritdoc} */ public function loadMultipleByUser(AccountInterface $account, $profile_type) { return $this->loadByProperties([ 'uid' => $account->id(), 'type' => $profile_type, 'status' => PROFILE_ACTIVE, ]); }
/** * Tests adding and editing values using metatag. */ public function testMetatag() { // Create a test entity. $edit = ['name[0][value]' => 'Barfoo', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')', 'field_metatag[0][basic][metatag_test]' => 'Kilimanjaro']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'Barfoo']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); // Make sure tags that have a field value but no default value still show // up. $this->drupalGet('entity_test/' . $entity->id()); $this->assertResponse(200); $elements = $this->cssSelect('meta[name=metatag_test]'); $this->assertTrue(count($elements) === 1, 'Found keywords metatag_test from defaults'); $this->assertEqual((string) $elements[0]['content'], 'Kilimanjaro', 'Field value for metatag_test found when no default set.'); // @TODO: This should not be required, but metatags does not invalidate // cache upon setting globals. Cache::invalidateTags(array('entity_test:' . $entity->id())); // Update the Global defaults and test them. $values = array('keywords' => 'Purple monkey dishwasher'); $this->drupalPostForm('admin/config/search/metatag/global', $values, 'Save'); $this->assertText('Saved the Global Metatag defaults.'); $this->drupalGet('entity_test/' . $entity->id()); $this->assertResponse(200); $elements = $this->cssSelect('meta[name=keywords]'); $this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $values['keywords'], 'Default keywords applied'); // Tests metatags with URLs work. $edit = ['name[0][value]' => 'UrlTags', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')', 'field_metatag[0][advanced][original_source]' => 'http://example.com/foo.html']; $this->drupalPostForm('entity_test/add', $edit, t('Save')); $entities = entity_load_multiple_by_properties('entity_test', ['name' => 'UrlTags']); $this->assertEqual(1, count($entities), 'Entity was saved'); $entity = reset($entities); $this->drupalGet('entity_test/' . $entity->id()); $this->assertResponse(200); $elements = $this->cssSelect("meta[name='original-source']"); $this->assertTrue(count($elements) === 1, 'Found original source metatag from defaults'); $this->assertEqual((string) $elements[0]['content'], $edit['field_metatag[0][advanced][original_source]']); // Test a route where the entity for that route does not implement // ContentEntityInterface. $controller = \Drupal::entityTypeManager()->getStorage('contact_form'); $controller->create(array('id' => 'test_contact_form'))->save(); $account = $this->drupalCreateUser(array('access site-wide contact form')); $this->drupalLogin($account); $this->drupalGet('contact/test_contact_form'); $this->assertResponse(200); }
/** * {@inheritdoc} */ protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { if ($account->hasPermission('administer media')) { return AccessResult::allowed()->cachePerPermissions(); } $is_owner = $account->id() && $account->id() == $entity->getPublisherId() ? TRUE : FALSE; switch ($operation) { case 'view': return AccessResult::allowedIfHasPermission($account, 'view media'); case 'update': return AccessResult::allowedIf($account->hasPermission('update media') && $is_owner || $account->hasPermission('update any media'))->cachePerPermissions()->cachePerUser()->cacheUntilEntityChanges($entity); case 'delete': return AccessResult::allowedIf($account->hasPermission('delete media') && $is_owner || $account->hasPermission('delete any media'))->cachePerPermissions()->cachePerUser()->cacheUntilEntityChanges($entity); } // No opinion. return AccessResult::neutral()->cachePerPermissions(); }