Пример #1
0
 /**
  * Tests embedded users on node pages.
  */
 function testPictureOnNodeComment()
 {
     $this->drupalLogin($this->webUser);
     // Save a new picture.
     $image = current($this->drupalGetTestFiles('image'));
     $file = $this->saveUserPicture($image);
     $node = $this->drupalCreateNode(array('type' => 'article'));
     // Enable user pictures on nodes.
     $this->config('system.theme.global')->set('features.node_user_picture', TRUE)->save();
     $image_style_id = $this->config('core.entity_view_display.user.user.compact')->get('content.user_picture.settings.image_style');
     $style = ImageStyle::load($image_style_id);
     $image_url = $style->buildUrl($file->getfileUri());
     $alt_text = 'Profile picture for user ' . $this->webUser->getUsername();
     // Verify that the image is displayed on the node page.
     $this->drupalGet('node/' . $node->id());
     $elements = $this->cssSelect('.node__meta .field--name-user-picture img[alt="' . $alt_text . '"][src="' . $image_url . '"]');
     $this->assertEqual(count($elements), 1, 'User picture with alt text found on node page.');
     // Enable user pictures on comments, instead of nodes.
     $this->config('system.theme.global')->set('features.node_user_picture', FALSE)->set('features.comment_user_picture', TRUE)->save();
     $edit = array('comment_body[0][value]' => $this->randomString());
     $this->drupalPostForm('comment/reply/node/' . $node->id() . '/comment', $edit, t('Save'));
     $elements = $this->cssSelect('.comment__meta .field--name-user-picture img[alt="' . $alt_text . '"][src="' . $image_url . '"]');
     $this->assertEqual(count($elements), 1, 'User picture with alt text found on the comment.');
     // Disable user pictures on comments and nodes.
     $this->config('system.theme.global')->set('features.node_user_picture', FALSE)->set('features.comment_user_picture', FALSE)->save();
     $this->drupalGet('node/' . $node->id());
     $this->assertNoRaw(file_uri_target($file->getFileUri()), 'User picture not found on node and comment.');
 }
Пример #2
0
 /**
  * Tests that mails for contact messages are correctly sent.
  */
 function testSendPersonalContactMessage()
 {
     // Ensure that the web user's email needs escaping.
     $mail = $this->webUser->getUsername() . '&escaped@example.com';
     $this->webUser->setEmail($mail)->save();
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertEscaped($mail);
     $message = $this->submitPersonalContact($this->contactUser);
     $mails = $this->drupalGetMails();
     $this->assertEqual(1, count($mails));
     $mail = $mails[0];
     $this->assertEqual($mail['to'], $this->contactUser->getEmail());
     $this->assertEqual($mail['from'], $this->config('system.site')->get('mail'));
     $this->assertEqual($mail['reply-to'], $this->webUser->getEmail());
     $this->assertEqual($mail['key'], 'user_mail');
     $variables = array('@site-name' => $this->config('system.site')->get('name'), '@subject' => $message['subject[0][value]'], '@recipient-name' => $this->contactUser->getDisplayName());
     $subject = PlainTextOutput::renderFromHtml(t('[@site-name] @subject', $variables));
     $this->assertEqual($mail['subject'], $subject, 'Subject is in sent message.');
     $this->assertTrue(strpos($mail['body'], 'Hello ' . $variables['@recipient-name']) !== FALSE, 'Recipient name is in sent message.');
     $this->assertTrue(strpos($mail['body'], $this->webUser->getDisplayName()) !== FALSE, 'Sender name is in sent message.');
     $this->assertTrue(strpos($mail['body'], $message['message[0][value]']) !== FALSE, 'Message body is in sent message.');
     // Check there was no problems raised during sending.
     $this->drupalLogout();
     $this->drupalLogin($this->adminUser);
     // Verify that the correct watchdog message has been logged.
     $this->drupalGet('/admin/reports/dblog');
     $placeholders = array('@sender_name' => $this->webUser->username, '@sender_email' => $this->webUser->getEmail(), '@recipient_name' => $this->contactUser->getUsername());
     $this->assertRaw(SafeMarkup::format('@sender_name (@sender_email) sent @recipient_name an email.', $placeholders));
     // Ensure an unescaped version of the email does not exist anywhere.
     $this->assertNoRaw($this->webUser->getEmail());
 }
Пример #3
0
 /**
  * Tests for the presence of nodes on a user's tracker listing.
  */
 function testTrackerUser()
 {
     $this->drupalLogin($this->user);
     $unpublished = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 0));
     $my_published = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 1));
     $other_published_no_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $other_published_my_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $comment = array('subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName(20));
     $this->drupalPostForm('comment/reply/node/' . $other_published_my_comment->id() . '/comment', $comment, t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($unpublished->label(), "Unpublished nodes do not show up in the user's tracker listing.");
     $this->assertText($my_published->label(), "Published nodes show up in the user's tracker listing.");
     $this->assertNoText($other_published_no_comment->label(), "Another user's nodes do not show up in the user's tracker listing.");
     $this->assertText($other_published_my_comment->label(), "Nodes that the user has commented on appear in the user's tracker listing.");
     $this->assertLink($my_published->label());
     $this->assertNoLink($unpublished->label());
     // Verify that title and tab title have been set correctly.
     $this->assertText('Activity', 'The user activity tab has the name "Activity".');
     $this->assertTitle(t('@name | @site', array('@name' => $this->user->getUsername(), '@site' => $this->config('system.site')->get('name'))), 'The user tracker page has the correct page title.');
     // Verify that unpublished comments are removed from the tracker.
     $admin_user = $this->drupalCreateUser(array('post comments', 'administer comments', 'access user profiles'));
     $this->drupalLogin($admin_user);
     $this->drupalPostForm('comment/1/edit', array('status' => CommentInterface::NOT_PUBLISHED), t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($other_published_my_comment->label(), 'Unpublished comments are not counted on the tracker listing.');
 }
Пример #4
0
 /**
  * Test label callback.
  */
 function testLabelCallback()
 {
     $this->assertEqual($this->account->label(), $this->account->getUsername(), 'The username should be used as label');
     // Setup a random anonymous name to be sure the name is used.
     $name = $this->randomMachineName();
     $this->config('user.settings')->set('anonymous', $name)->save();
     $this->assertEqual($this->anonymous->label(), $name, 'The variable anonymous should be used for name of uid 0');
 }
Пример #5
0
 /**
  * Check that non-installed languages are not considered.
  */
 function testUrlRewritingEdgeCases()
 {
     // Check URL rewriting with a non-installed language.
     $non_existing = new Language(array('id' => $this->randomMachineName()));
     $this->checkUrl($non_existing, 'Path language is ignored if language is not installed.', 'URL language negotiation does not work with non-installed languages');
     // Check that URL rewriting is not applied to subrequests.
     $this->drupalGet('language_test/subrequest');
     $this->assertText($this->webUser->getUsername(), 'Page correctly retrieved');
 }
 /**
  * Tests password reset functionality.
  */
 function testUserPasswordReset()
 {
     // Try to reset the password for an invalid account.
     $this->drupalGet('user/password');
     $edit = array('name' => $this->randomMachineName(32));
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     $this->assertText(t('Sorry, @name is not recognized as a username or an email address.', array('@name' => $edit['name'])), 'Validation error message shown when trying to request password for invalid account.');
     $this->assertEqual(count($this->drupalGetMails(array('id' => 'user_password_reset'))), 0, 'No email was sent when requesting a password for an invalid account.');
     // Reset the password by username via the password reset page.
     $edit['name'] = $this->account->getUsername();
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     // Verify that the user was sent an email.
     $this->assertMail('to', $this->account->getEmail(), 'Password email sent to user.');
     $subject = t('Replacement login information for @username at @site', array('@username' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name')));
     $this->assertMail('subject', $subject, 'Password reset email subject is correct.');
     $resetURL = $this->getResetURL();
     $this->drupalGet($resetURL);
     // Check the one-time login page.
     $this->assertText($this->account->getUsername(), 'One-time login page contains the correct username.');
     $this->assertText(t('This login can be used only once.'), 'Found warning about one-time login.');
     // Check successful login.
     $this->drupalPostForm(NULL, NULL, t('Log in'));
     $this->assertLink(t('Log out'));
     $this->assertTitle(t('@name | @site', array('@name' => $this->account->getUsername(), '@site' => \Drupal::config('system.site')->get('name'))), 'Logged in using password reset link.');
     // Change the forgotten password.
     $password = user_password();
     $edit = array('pass[pass1]' => $password, 'pass[pass2]' => $password);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('The changes have been saved.'), 'Forgotten password changed.');
     // Verify that the password reset session has been destroyed.
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('Your current password is missing or incorrect; it\'s required to change the Password.'), 'Password needed to make profile changes.');
     // Log out, and try to log in again using the same one-time link.
     $this->drupalLogout();
     $this->drupalGet($resetURL);
     $this->assertText(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'One-time link is no longer valid.');
     // Request a new password again, this time using the email address.
     $this->drupalGet('user/password');
     // Count email messages before to compare with after.
     $before = count($this->drupalGetMails(array('id' => 'user_password_reset')));
     $edit = array('name' => $this->account->getEmail());
     $this->drupalPostForm(NULL, $edit, t('Email new password'));
     $this->assertTrue(count($this->drupalGetMails(array('id' => 'user_password_reset'))) === $before + 1, 'Email sent when requesting password reset using email address.');
     // Create a password reset link as if the request time was 60 seconds older than the allowed limit.
     $timeout = \Drupal::config('user.settings')->get('password_reset_timeout');
     $bogus_timestamp = REQUEST_TIME - $timeout - 60;
     $_uid = $this->account->id();
     $this->drupalGet("user/reset/{$_uid}/{$bogus_timestamp}/" . user_pass_rehash($this->account->getPassword(), $bogus_timestamp, $this->account->getLastLoginTime()));
     $this->assertText(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'Expired password reset request rejected.');
     // Create a user, block the account, and verify that a login link is denied.
     $timestamp = REQUEST_TIME - 1;
     $blocked_account = $this->drupalCreateUser()->block();
     $blocked_account->save();
     $this->drupalGet("user/reset/" . $blocked_account->id() . "/{$timestamp}/" . user_pass_rehash($blocked_account->getPassword(), $timestamp, $blocked_account->getLastLoginTime()));
     $this->assertResponse(403);
 }
Пример #7
0
 /**
  * Test label callback.
  */
 function testLabelCallback()
 {
     $this->assertEqual($this->account->label(), $this->account->getUsername(), 'The username should be used as label');
     // Setup a random anonymous name to be sure the name is used.
     $name = $this->randomMachineName();
     $this->config('user.settings')->set('anonymous', $name)->save();
     $this->assertEqual($this->anonymous->label(), $name, 'The variable anonymous should be used for name of uid 0');
     $this->assertEqual($this->anonymous->getDisplayName(), $name, 'The variable anonymous should be used for display name of uid 0');
     $this->assertEqual($this->anonymous->getUserName(), '', 'The raw anonymous user name should be empty string');
     // Set to test the altered username.
     \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
     $this->assertEqual($this->account->getDisplayName(), '<em>' . $this->account->id() . '</em>', 'The user display name should be altered.');
     $this->assertEqual($this->account->getUsername(), $this->account->name->value, 'The user name should not be altered.');
 }
Пример #8
0
 /**
  * Tests for the presence of nodes on a user's tracker listing.
  */
 function testTrackerUser()
 {
     $this->drupalLogin($this->user);
     $unpublished = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 0));
     $my_published = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 1));
     $other_published_no_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $other_published_my_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $comment = array('subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName(20));
     $this->drupalPostForm('comment/reply/node/' . $other_published_my_comment->id() . '/comment', $comment, t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($unpublished->label(), "Unpublished nodes do not show up in the user's tracker listing.");
     $this->assertText($my_published->label(), "Published nodes show up in the user's tracker listing.");
     $this->assertNoText($other_published_no_comment->label(), "Another user's nodes do not show up in the user's tracker listing.");
     $this->assertText($other_published_my_comment->label(), "Nodes that the user has commented on appear in the user's tracker listing.");
     // Assert cache contexts; the node grant context is not directly visible due
     // to it being implied by the user context.
     $this->assertCacheContexts(['languages:language_interface', 'theme', 'url.query_args.pagers:0', 'user']);
     // Assert cache tags for the visible nodes (including owners) and node list
     // cache tag.
     $tags = Cache::mergeTags($my_published->getCacheTags(), $my_published->getOwner()->getCacheTags(), $other_published_my_comment->getCacheTags(), $other_published_my_comment->getOwner()->getCacheTags(), ['node_list', 'rendered']);
     $this->assertCacheTags($tags);
     $this->assertLink($my_published->label());
     $this->assertNoLink($unpublished->label());
     // Verify that title and tab title have been set correctly.
     $this->assertText('Activity', 'The user activity tab has the name "Activity".');
     $this->assertTitle(t('@name | @site', array('@name' => $this->user->getUsername(), '@site' => $this->config('system.site')->get('name'))), 'The user tracker page has the correct page title.');
     // Verify that unpublished comments are removed from the tracker.
     $admin_user = $this->drupalCreateUser(array('post comments', 'administer comments', 'access user profiles'));
     $this->drupalLogin($admin_user);
     $this->drupalPostForm('comment/1/edit', array('status' => CommentInterface::NOT_PUBLISHED), t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($other_published_my_comment->label(), 'Unpublished comments are not counted on the tracker listing.');
 }
Пример #9
0
 /**
  * Tests output for comment properties on nodes in full page view mode.
  *
  * @param \EasyRdf_Graph $graph
  *   The EasyRDF graph object.
  */
 protected function assertRdfaNodeCommentProperties($graph)
 {
     // Relationship between node and comment.
     $expected_value = array('type' => 'uri', 'value' => $this->articleCommentUri);
     $this->assertTrue($graph->hasProperty($this->articleUri, 'http://schema.org/comment', $expected_value), 'Relationship between node and comment found (schema:comment).');
     // Comment type.
     $this->assertEqual($graph->type($this->articleCommentUri), 'schema:Comment', 'Comment type was found (schema:Comment).');
     // Comment title.
     $expected_value = array('type' => 'literal', 'value' => $this->articleComment->get('subject')->value, 'lang' => 'en');
     $this->assertTrue($graph->hasProperty($this->articleCommentUri, 'http://schema.org/name', $expected_value), 'Article comment title was found (schema:name).');
     // Comment created date.
     $expected_value = array('type' => 'literal', 'value' => format_date($this->articleComment->get('created')->value, 'custom', 'c', 'UTC'), 'lang' => 'en');
     $this->assertTrue($graph->hasProperty($this->articleCommentUri, 'http://schema.org/dateCreated', $expected_value), 'Article comment created date was found (schema:dateCreated).');
     // Comment body.
     $text = $this->articleComment->get('comment_body')->value;
     $expected_value = array('type' => 'literal', 'value' => "{$text}\n", 'lang' => 'en');
     $this->assertTrue($graph->hasProperty($this->articleCommentUri, 'http://schema.org/text', $expected_value), 'Article comment body was found (schema:text).');
     // Comment uid.
     $expected_value = array('type' => 'uri', 'value' => $this->commenterUri);
     $this->assertTrue($graph->hasProperty($this->articleCommentUri, 'http://schema.org/author', $expected_value), 'Article comment author was found (schema:author).');
     // Comment author type.
     $this->assertEqual($graph->type($this->commenterUri), 'schema:Person', 'Comment author type was found (schema:Person).');
     // Comment author name.
     $expected_value = array('type' => 'literal', 'value' => $this->webUser->getUsername());
     $this->assertTrue($graph->hasProperty($this->commenterUri, 'http://schema.org/name', $expected_value), 'Comment author name was found (schema:name).');
 }
Пример #10
0
 /**
  * Checks that the "authored by" works correctly with various values.
  *
  * @param \Drupal\node\NodeInterface $node
  *   A node object.
  * @param string $form_element_name
  *   The name of the form element to populate.
  */
 protected function checkVariousAuthoredByValues(NodeInterface $node, $form_element_name)
 {
     // Try to change the 'authored by' field to an invalid user name.
     $edit = array($form_element_name => 'invalid-name');
     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
     $this->assertRaw(t('There are no entities matching "%name".', array('%name' => 'invalid-name')));
     // Change the authored by field to an empty string, which should assign
     // authorship to the anonymous user (uid 0).
     $edit[$form_element_name] = '';
     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
     $this->nodeStorage->resetCache(array($node->id()));
     $node = $this->nodeStorage->load($node->id());
     $uid = $node->getOwnerId();
     // Most SQL database drivers stringify fetches but entities are not
     // necessarily stored in a SQL database. At the same time, NULL/FALSE/""
     // won't do.
     $this->assertTrue($uid === 0 || $uid === '0', 'Node authored by anonymous user.');
     // Change the authored by field to another user's name (that is not
     // logged in).
     $edit[$form_element_name] = $this->webUser->getUsername();
     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
     $this->nodeStorage->resetCache(array($node->id()));
     $node = $this->nodeStorage->load($node->id());
     $this->assertIdentical($node->getOwnerId(), $this->webUser->id(), 'Node authored by normal user.');
 }
Пример #11
0
 public function flickr_sets_photosets(\Drupal\user\UserInterface $account, $nsid = NULL)
 {
     global $pager_page_array, $pager_total, $pager_total_items, $user;
     // @FIXME
     // drupal_set_title() has been removed. There are now a few ways to set the title
     // dynamically, depending on the situation.
     //
     //
     // @see https://www.drupal.org/node/2067859
     // drupal_set_title(flickr_sets_page_title($user));
     $uid = $account->id();
     $nsid = $account->flickr['nsid'];
     // Set this to something else if you want multiple pagers.
     $element = 0;
     $pager_page_array[$element] = empty($_GET['page']) ? 0 : (int) $_GET['page'];
     $per_page = \Drupal::config('flickr_sets.settings')->get('flickr_sets_per_page');
     // First we need the complete list of sets just for the pager info.
     $set_response = flickr_photosets_getlist($nsid);
     $pager_total[$element] = ceil(count($set_response) / \Drupal::config('flickr_sets.settings')->get('flickr_sets_per_page'));
     $pager_total_items[$element] = count($set_response);
     // Now we only get the sets for the corresponding page.
     $set_response = flickr_photosets_getlist($nsid, $pager_page_array[$element] + 1);
     if ($set_response === FALSE) {
         drupal_set_message(t("Error retrieving %user's photosets from Flickr", ['%user' => $account->getUsername()]));
         return '';
     }
     if (!$set_response || empty($set_response)) {
         drupal_set_message(t('%user has no photosets', ['%user' => $account->getUsername()]));
         return '';
     }
     // @FIXME
     // theme() has been renamed to _theme() and should NEVER be called directly.
     // Calling _theme() directly can alter the expected output and potentially
     // introduce security issues (see https://www.drupal.org/node/2195739). You
     // should use renderable arrays instead.
     //
     //
     // @see https://www.drupal.org/node/2195739
     // return theme('flickr_sets_photosets', array(
     //     'uid' => $uid,
     //     'per_page' => $per_page,
     //     'nsid' => $nsid,
     //     'photosets' => $set_response,
     //   ));
 }
 /**
  * Verifies that you can disable individual search plugins.
  */
 function testSearchModuleDisabling()
 {
     // Array of search plugins to test: 'keys' are the keywords to search for,
     // and 'text' is the text to assert is on the results page.
     $plugin_info = array('node_search' => array('keys' => 'pizza', 'text' => $this->searchNode->label()), 'user_search' => array('keys' => $this->searchUser->getUsername(), 'text' => $this->searchUser->getEmail()), 'dummy_search_type' => array('keys' => 'foo', 'text' => 'Dummy search snippet to display'));
     $plugins = array_keys($plugin_info);
     /** @var $entities \Drupal\search\SearchPageInterface[] */
     $entities = entity_load_multiple('search_page');
     // Disable all of the search pages.
     foreach ($entities as $entity) {
         $entity->disable()->save();
     }
     // Test each plugin if it's enabled as the only search plugin.
     foreach ($entities as $entity_id => $entity) {
         // Set this as default.
         $this->drupalGet("admin/config/search/pages/manage/{$entity_id}/set-default");
         // Run a search from the correct search URL.
         $info = $plugin_info[$entity_id];
         $this->drupalGet('search/' . $entity->getPath(), array('query' => array('keys' => $info['keys'])));
         $this->assertResponse(200);
         $this->assertNoText('no results', $entity->label() . ' search found results');
         $this->assertText($info['text'], 'Correct search text found');
         // Verify that other plugin search tab labels are not visible.
         foreach ($plugins as $other) {
             if ($other != $entity_id) {
                 $label = $entities[$other]->label();
                 $this->assertNoText($label, $label . ' search tab is not shown');
             }
         }
         // Run a search from the search block on the node page. Verify you get
         // to this plugin's search results page.
         $terms = array('keys' => $info['keys']);
         $this->submitGetForm('node', $terms, t('Search'));
         $current = $this->getURL();
         $expected = \Drupal::url('search.view_' . $entity->id(), array(), array('query' => array('keys' => $info['keys']), 'absolute' => TRUE));
         $this->assertEqual($current, $expected, 'Block redirected to right search page');
         // Try an invalid search path, which should 404.
         $this->drupalGet('search/not_a_plugin_path');
         $this->assertResponse(404);
         $entity->disable()->save();
     }
     // Test with all search plugins enabled. When you go to the search
     // page or run search, all plugins should be shown.
     foreach ($entities as $entity) {
         $entity->enable()->save();
     }
     // Set the node search as default.
     $this->drupalGet('admin/config/search/pages/manage/node_search/set-default');
     $paths = array(array('path' => 'search/node', 'options' => array('query' => array('keys' => 'pizza'))), array('path' => 'search/node', 'options' => array()));
     foreach ($paths as $item) {
         $this->drupalGet($item['path'], $item['options']);
         foreach ($plugins as $entity_id) {
             $label = $entities[$entity_id]->label();
             $this->assertText($label, format_string('%label search tab is shown', array('%label' => $label)));
         }
     }
 }
Пример #13
0
 /**
  * Tests for the presence of nodes on a user's tracker listing.
  */
 function testTrackerUser()
 {
     $this->drupalLogin($this->user);
     $unpublished = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 0));
     $my_published = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->user->id(), 'status' => 1));
     $other_published_no_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $other_published_my_comment = $this->drupalCreateNode(array('title' => $this->randomMachineName(8), 'uid' => $this->otherUser->id(), 'status' => 1));
     $comment = array('subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName(20));
     $this->drupalPostForm('comment/reply/node/' . $other_published_my_comment->id() . '/comment', $comment, t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($unpublished->label(), "Unpublished nodes do not show up in the user's tracker listing.");
     $this->assertText($my_published->label(), "Published nodes show up in the user's tracker listing.");
     $this->assertNoText($other_published_no_comment->label(), "Another user's nodes do not show up in the user's tracker listing.");
     $this->assertText($other_published_my_comment->label(), "Nodes that the user has commented on appear in the user's tracker listing.");
     // Assert cache contexts.
     $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user', 'user.node_grants:view']);
     // Assert cache tags for the visible nodes (including owners) and node list
     // cache tag.
     $expected_tags = Cache::mergeTags($my_published->getCacheTags(), $my_published->getOwner()->getCacheTags());
     $expected_tags = Cache::mergeTags($expected_tags, $other_published_my_comment->getCacheTags());
     $expected_tags = Cache::mergeTags($expected_tags, $other_published_my_comment->getOwner()->getCacheTags());
     // Because the 'user.permissions' cache context is being optimized away.
     $role_tags = [];
     foreach ($this->user->getRoles() as $rid) {
         $role_tags[] = "config:user.role.{$rid}";
     }
     $expected_tags = Cache::mergeTags($expected_tags, $role_tags);
     $block_tags = ['block_view', 'config:block.block.page_actions_block', 'config:block.block.page_tabs_block', 'config:block_list'];
     $expected_tags = Cache::mergeTags($expected_tags, $block_tags);
     $additional_tags = ['node_list', 'rendered'];
     $expected_tags = Cache::mergeTags($expected_tags, $additional_tags);
     $this->assertCacheTags($expected_tags);
     $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user', 'user.node_grants:view']);
     $this->assertLink($my_published->label());
     $this->assertNoLink($unpublished->label());
     // Verify that title and tab title have been set correctly.
     $this->assertText('Activity', 'The user activity tab has the name "Activity".');
     $this->assertTitle(t('@name | @site', array('@name' => $this->user->getUsername(), '@site' => $this->config('system.site')->get('name'))), 'The user tracker page has the correct page title.');
     // Verify that unpublished comments are removed from the tracker.
     $admin_user = $this->drupalCreateUser(array('post comments', 'administer comments', 'access user profiles'));
     $this->drupalLogin($admin_user);
     $this->drupalPostForm('comment/1/edit', array('status' => CommentInterface::NOT_PUBLISHED), t('Save'));
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoText($other_published_my_comment->label(), 'Unpublished comments are not counted on the tracker listing.');
     // Test escaping of title on user's tracker tab.
     \Drupal::service('module_installer')->install(['user_hooks_test']);
     Cache::invalidateTags(['rendered']);
     \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertEscaped('<em>' . $this->user->id() . '</em>');
     \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
     Cache::invalidateTags(['rendered']);
     $this->drupalGet('user/' . $this->user->id() . '/activity');
     $this->assertNoEscaped('<em>' . $this->user->id() . '</em>');
     $this->assertRaw('<em>' . $this->user->id() . '</em>');
 }
Пример #14
0
 /**
  * Tests the presence of the expected cache tag in various situations.
  */
 function testSearchText()
 {
     $this->drupalLogin($this->searchingUser);
     // Initial page for searching nodes.
     $this->drupalGet('search/node');
     $this->assertCacheTag('config:search.page.node_search');
     $this->assertCacheTag('search_index:node_search');
     $this->assertCacheTag('node_list');
     // Node search results.
     $edit = array();
     $edit['keys'] = 'bike shed';
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertText('bike shed shop');
     $this->assertCacheTag('config:search.page.node_search');
     $this->assertCacheTag('search_index');
     $this->assertCacheTag('search_index:node_search');
     $this->assertCacheTag('node:1');
     $this->assertCacheTag('user:2');
     $this->assertCacheTag('rendered');
     $this->assertCacheTag('node_list');
     // Updating a node should invalidate the search plugin's index cache tag.
     $this->node->title = 'bike shop';
     $this->node->save();
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertText('bike shop');
     $this->assertCacheTag('config:search.page.node_search');
     $this->assertCacheTag('search_index');
     $this->assertCacheTag('search_index:node_search');
     $this->assertCacheTag('node:1');
     $this->assertCacheTag('user:2');
     $this->assertCacheTag('rendered');
     $this->assertCacheTag('node_list');
     // Deleting a node should invalidate the search plugin's index cache tag.
     $this->node->delete();
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertText('Your search yielded no results.');
     $this->assertCacheTag('config:search.page.node_search');
     $this->assertCacheTag('search_index');
     $this->assertCacheTag('search_index:node_search');
     $this->assertCacheTag('node_list');
     // Initial page for searching users.
     $this->drupalGet('search/user');
     $this->assertCacheTag('config:search.page.user_search');
     $this->assertCacheTag('user_list');
     $this->assertNoCacheTag('search_index');
     $this->assertNoCacheTag('search_index:user_search');
     // User search results.
     $edit['keys'] = $this->searchingUser->getUsername();
     $this->drupalPostForm('search/user', $edit, t('Search'));
     $this->assertCacheTag('config:search.page.user_search');
     $this->assertCacheTag('user_list');
     $this->assertCacheTag('user:2');
     $this->assertNoCacheTag('search_index');
     $this->assertNoCacheTag('search_index:user_search');
 }
 /**
  * Tests the presence of the expected cache tag in various situations.
  */
 function testSearchText()
 {
     $this->drupalLogin($this->searchingUser);
     // Initial page for searching nodes.
     $this->drupalGet('search/node');
     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     $this->assertTrue(in_array('config:search.page.node_search', $cache_tags));
     // Node search results.
     $edit = array();
     $edit['keys'] = 'bike shed';
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     $this->assertTrue(in_array('config:search.page.node_search', $cache_tags));
     // Initial page for searching users.
     $this->drupalGet('search/user');
     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     $this->assertTrue(in_array('config:search.page.user_search', $cache_tags));
     // User search results.
     $edit['keys'] = $this->searchingUser->getUsername();
     $this->drupalPostForm('search/user', $edit, t('Search'));
     $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     $this->assertTrue(in_array('config:search.page.user_search', $cache_tags));
 }
  /**
   * Test user password reset while logged in.
   */
  public function testUserPasswordResetLoggedIn() {
    $another_account = $this->drupalCreateUser();
    $this->drupalLogin($another_account);
    $this->drupalGet('user/password');
    $this->drupalPostForm(NULL, NULL, t('Submit'));

    // Click the reset URL while logged and change our password.
    $resetURL = $this->getResetURL();
    // Log in as a different user.
    $this->drupalLogin($this->account);
    $this->drupalGet($resetURL);
    $this->assertRaw(new FormattableMarkup(
      'Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href=":logout">log out</a> and try using the link again.',
      ['%other_user' => $this->account->getUsername(), '%resetting_user' => $another_account->getUsername(), ':logout' => Url::fromRoute('user.logout')->toString()]
    ));

    $another_account->delete();
    $this->drupalGet($resetURL);
    $this->assertText('The one-time login link you clicked is invalid.');

    // Log in.
    $this->drupalLogin($this->account);

    // Reset the password by username via the password reset page.
    $this->drupalGet('user/password');
    $this->drupalPostForm(NULL, NULL, t('Submit'));

    // Click the reset URL while logged and change our password.
    $resetURL = $this->getResetURL();
    $this->drupalGet($resetURL);
    $this->drupalPostForm(NULL, NULL, t('Log in'));

    // Change the password.
    $password = user_password();
    $edit = array('pass[pass1]' => $password, 'pass[pass2]' => $password);
    $this->drupalPostForm(NULL, $edit, t('Save'));
    $this->assertText(t('The changes have been saved.'), 'Password changed.');

    // Logged in users should not be able to access the user.reset.login or the
    // user.reset.form routes.
    $timestamp = REQUEST_TIME - 1;
    $this->drupalGet("user/reset/" . $this->account->id() . "/$timestamp/" . user_pass_rehash($this->account, $timestamp) . '/login');
    $this->assertResponse(403);
    $this->drupalGet("user/reset/" . $this->account->id());
    $this->assertResponse(403);
  }
 /**
  * Route title callback.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user account.
  *
  * @return string|array
  *   The user account name as a render array or an empty string if $user is
  *   NULL.
  */
 public function userTitle(UserInterface $user = NULL)
 {
     return $user ? ['#markup' => $user->getUsername(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
 }
 /**
  * Checks that workflows have the expected behaviors for the given user.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user to test the workflow behavior against.
  * @param array $expected_status
  *   The an associative array with the operation name as key and the expected
  *   status as value.
  */
 protected function assertWorkflows(UserInterface $user, $expected_status)
 {
     $default_langcode = $this->langcodes[0];
     $languages = $this->container->get('language_manager')->getLanguages();
     $args = array('@user_label' => $user->getUsername());
     $this->drupalLogin($user);
     // Check whether the user is allowed to access the entity form in edit mode.
     $edit_path = $this->entity->getSystemPath('edit-form');
     $options = array('language' => $languages[$default_langcode]);
     $this->drupalGet($edit_path, $options);
     $this->assertResponse($expected_status['edit'], format_string('The @user_label has the expected edit access.', $args));
     // Check whether the user is allowed to access the translation overview.
     $langcode = $this->langcodes[1];
     $translations_path = $this->entity->getSystemPath('drupal:content-translation-overview');
     $options = array('language' => $languages[$langcode]);
     $this->drupalGet($translations_path, $options);
     $this->assertResponse($expected_status['overview'], format_string('The @user_label has the expected translation overview access.', $args));
     // Check whether the user is allowed to create a translation.
     $add_translation_path = $translations_path . "/add/{$default_langcode}/{$langcode}";
     if ($expected_status['add_translation'] == 200) {
         $this->clickLink('Add');
         $this->assertUrl($add_translation_path, $options, 'The translation overview points to the translation form when creating translations.');
         // Check that the translation form does not contain shared elements for
         // translators.
         if ($expected_status['edit'] == 403) {
             $this->assertNoSharedElements();
         }
     } else {
         $this->drupalGet($add_translation_path, $options);
     }
     $this->assertResponse($expected_status['add_translation'], format_string('The @user_label has the expected translation creation access.', $args));
     // Check whether the user is allowed to edit a translation.
     $langcode = $this->langcodes[2];
     $edit_translation_path = $translations_path . "/edit/{$langcode}";
     $options = array('language' => $languages[$langcode]);
     if ($expected_status['edit_translation'] == 200) {
         $this->drupalGet($translations_path, $options);
         $editor = $expected_status['edit'] == 200;
         if ($editor) {
             $this->clickLink('Edit', 2);
             // An editor should be pointed to the entity form in multilingual mode.
             $this->assertUrl($edit_path, $options, 'The translation overview points to the edit form for editors when editing translations.');
         } else {
             $this->clickLink('Edit');
             // While a translator should be pointed to the translation form.
             $this->assertUrl($edit_translation_path, $options, 'The translation overview points to the translation form for translators when editing translations.');
             // Check that the translation form does not contain shared elements.
             $this->assertNoSharedElements();
         }
     } else {
         $this->drupalGet($edit_translation_path, $options);
     }
     $this->assertResponse($expected_status['edit_translation'], format_string('The @user_label has the expected translation creation access.', $args));
 }
Пример #19
0
 /**
  * Title callback for the tracker.user_tab route.
  */
 public function getTitle(UserInterface $user)
 {
     return $user->getUsername();
 }
Пример #20
0
 /**
  * Form constructor for the personal contact form.
  *
  * @param \Drupal\user\UserInterface $user
  *   The account for which a personal contact form should be generated.
  *
  * @return array
  *   The personal contact form as render array as expected by drupal_render().
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Exception is thrown when user tries to access a contact form for a
  *   user who does not have an e-mail address configured.
  */
 public function contactPersonalPage(UserInterface $user)
 {
     // Do not continue if the user does not have an e-mail address configured.
     if (!$user->getEmail()) {
         throw new NotFoundHttpException();
     }
     $message = $this->entityManager()->getStorage('contact_message')->create(array('contact_form' => 'personal', 'recipient' => $user->id()));
     $form = $this->entityFormBuilder()->getForm($message);
     $form['#title'] = $this->t('Contact @username', array('@username' => $user->getUsername()));
     $form['#cache']['contexts'][] = 'user.permissions';
     return $form;
 }
Пример #21
0
 /**
  * Tests breadcrumbs on node and administrative paths.
  */
 function testBreadCrumbs()
 {
     // Prepare common base breadcrumb elements.
     $home = array('' => 'Home');
     $admin = $home + array('admin' => t('Administration'));
     $config = $admin + array('admin/config' => t('Configuration'));
     $type = 'article';
     // Verify Taxonomy administration breadcrumbs.
     $trail = $admin + array('admin/structure' => t('Structure'));
     $this->assertBreadcrumb('admin/structure/taxonomy', $trail);
     $trail += array('admin/structure/taxonomy' => t('Taxonomy'));
     $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags', $trail);
     $trail += array('admin/structure/taxonomy/manage/tags' => t('Tags'));
     $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/overview', $trail);
     $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/add', $trail);
     // Verify Menu administration breadcrumbs.
     $trail = $admin + array('admin/structure' => t('Structure'));
     $this->assertBreadcrumb('admin/structure/menu', $trail);
     $trail += array('admin/structure/menu' => t('Menus'));
     $this->assertBreadcrumb('admin/structure/menu/manage/tools', $trail);
     $trail += array('admin/structure/menu/manage/tools' => t('Tools'));
     $this->assertBreadcrumb("admin/structure/menu/link/node.add_page/edit", $trail);
     $this->assertBreadcrumb('admin/structure/menu/manage/tools/add', $trail);
     // Verify Node administration breadcrumbs.
     $trail = $admin + array('admin/structure' => t('Structure'), 'admin/structure/types' => t('Content types'));
     $this->assertBreadcrumb('admin/structure/types/add', $trail);
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}", $trail);
     $trail += array("admin/structure/types/manage/{$type}" => t('Article'));
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}/fields", $trail);
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}/display", $trail);
     $trail_teaser = $trail + array("admin/structure/types/manage/{$type}/display" => t('Manage display'));
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}/display/teaser", $trail_teaser);
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}/delete", $trail);
     $trail += array("admin/structure/types/manage/{$type}/fields" => t('Manage fields'));
     $this->assertBreadcrumb("admin/structure/types/manage/{$type}/fields/node.{$type}.body", $trail);
     // Verify Filter text format administration breadcrumbs.
     $filter_formats = filter_formats();
     $format = reset($filter_formats);
     $format_id = $format->id();
     $trail = $config + array('admin/config/content' => t('Content authoring'));
     $this->assertBreadcrumb('admin/config/content/formats', $trail);
     $trail += array('admin/config/content/formats' => t('Text formats and editors'));
     $this->assertBreadcrumb('admin/config/content/formats/add', $trail);
     $this->assertBreadcrumb("admin/config/content/formats/manage/{$format_id}", $trail);
     // @todo Remove this part once we have a _title_callback, see
     //   https://www.drupal.org/node/2076085.
     $trail += array("admin/config/content/formats/manage/{$format_id}" => $format->label());
     $this->assertBreadcrumb("admin/config/content/formats/manage/{$format_id}/disable", $trail);
     // Verify node breadcrumbs (without menu link).
     $node1 = $this->drupalCreateNode();
     $nid1 = $node1->id();
     $trail = $home;
     $this->assertBreadcrumb("node/{$nid1}", $trail);
     // Also verify that the node does not appear elsewhere (e.g., menu trees).
     $this->assertNoLink($node1->getTitle());
     // Also verify that the node does not appear elsewhere (e.g., menu trees).
     $this->assertNoLink($node1->getTitle());
     $trail += array("node/{$nid1}" => $node1->getTitle());
     $this->assertBreadcrumb("node/{$nid1}/edit", $trail);
     // Verify that breadcrumb on node listing page contains "Home" only.
     $trail = array();
     $this->assertBreadcrumb('node', $trail);
     // Verify node breadcrumbs (in menu).
     // Do this separately for Main menu and Tools menu, since only the
     // latter is a preferred menu by default.
     // @todo Also test all themes? Manually testing led to the suspicion that
     //   breadcrumbs may differ, possibly due to theme overrides.
     $menus = array('main', 'tools');
     // Alter node type menu settings.
     $node_type = NodeType::load($type);
     $node_type->setThirdPartySetting('menu_ui', 'available_menus', $menus);
     $node_type->setThirdPartySetting('menu_ui', 'parent', 'tools:');
     $node_type->save();
     foreach ($menus as $menu) {
         // Create a parent node in the current menu.
         $title = $this->randomMachineName();
         $node2 = $this->drupalCreateNode(array('type' => $type, 'title' => $title, 'menu' => array('enabled' => 1, 'title' => 'Parent ' . $title, 'description' => '', 'menu_name' => $menu, 'parent' => '')));
         if ($menu == 'tools') {
             $parent = $node2;
         }
     }
     // Create a Tools menu link for 'node', move the last parent node menu
     // link below it, and verify a full breadcrumb for the last child node.
     $menu = 'tools';
     $edit = array('title[0][value]' => 'Root', 'link[0][uri]' => '/node');
     $this->drupalPostForm("admin/structure/menu/manage/{$menu}/add", $edit, t('Save'));
     $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => 'Root'));
     $link = reset($menu_links);
     $edit = array('menu[menu_parent]' => $link->getMenuName() . ':' . $link->getPluginId());
     $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published'));
     $expected = array("node" => $link->getTitle());
     $trail = $home + $expected;
     $tree = $expected + array('node/' . $parent->id() => $parent->menu['title']);
     $trail += array('node/' . $parent->id() => $parent->menu['title']);
     // Add a taxonomy term/tag to last node, and add a link for that term to the
     // Tools menu.
     $tags = array('Drupal' => array(), 'Breadcrumbs' => array());
     $edit = array('field_tags[target_id]' => implode(',', array_keys($tags)));
     $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published'));
     // Put both terms into a hierarchy Drupal » Breadcrumbs. Required for both
     // the menu links and the terms itself, since taxonomy_term_page() resets
     // the breadcrumb based on taxonomy term hierarchy.
     $parent_tid = 0;
     foreach ($tags as $name => $null) {
         $terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $name));
         $term = reset($terms);
         $tags[$name]['term'] = $term;
         if ($parent_tid) {
             $edit = array('parent[]' => array($parent_tid));
             $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save'));
         }
         $parent_tid = $term->id();
     }
     $parent_mlid = '';
     foreach ($tags as $name => $data) {
         $term = $data['term'];
         $edit = array('title[0][value]' => "{$name} link", 'link[0][uri]' => "/taxonomy/term/{$term->id()}", 'menu_parent' => "{$menu}:{$parent_mlid}", 'enabled[value]' => 1);
         $this->drupalPostForm("admin/structure/menu/manage/{$menu}/add", $edit, t('Save'));
         $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => $edit['title[0][value]'], 'link.uri' => 'internal:/taxonomy/term/' . $term->id()));
         $tags[$name]['link'] = reset($menu_links);
         $parent_mlid = $tags[$name]['link']->getPluginId();
     }
     // Verify expected breadcrumbs for menu links.
     $trail = $home;
     $tree = array();
     // Logout the user because we want to check the active class as well, which
     // is just rendered as anonymous user.
     $this->drupalLogout();
     foreach ($tags as $name => $data) {
         $term = $data['term'];
         /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */
         $link = $data['link'];
         $link_path = $link->getUrlObject()->getInternalPath();
         $tree += array($link_path => $link->getTitle());
         $this->assertBreadcrumb($link_path, $trail, $term->getName(), $tree);
         $this->assertEscaped($parent->getTitle(), 'Tagged node found.');
         // Additionally make sure that this link appears only once; i.e., the
         // untranslated menu links automatically generated from menu router items
         // ('taxonomy/term/%') should never be translated and appear in any menu
         // other than the breadcrumb trail.
         $elements = $this->xpath('//nav[@id=:menu]/descendant::a[@href=:href]', array(':menu' => 'block-bartik-tools', ':href' => Url::fromUri('base:' . $link_path)->toString()));
         $this->assertTrue(count($elements) == 1, "Link to {$link_path} appears only once.");
         // Next iteration should expect this tag as parent link.
         // Note: Term name, not link name, due to taxonomy_term_page().
         $trail += array($link_path => $term->getName());
     }
     // Verify breadcrumbs on user and user/%.
     // We need to log back in and out below, and cannot simply grant the
     // 'administer users' permission, since user_page() makes your head explode.
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access user profiles'));
     // Verify breadcrumb on front page.
     $this->assertBreadcrumb('<front>', array());
     // Verify breadcrumb on user pages (without menu link) for anonymous user.
     $trail = $home;
     $this->assertBreadcrumb('user', $trail, t('Log in'));
     $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());
     // Verify breadcrumb on user pages (without menu link) for registered users.
     $this->drupalLogin($this->adminUser);
     $trail = $home;
     $this->assertBreadcrumb('user', $trail, $this->adminUser->getUsername());
     $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());
     $trail += array('user/' . $this->adminUser->id() => $this->adminUser->getUsername());
     $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername());
     // Create a second user to verify breadcrumb on user pages again.
     $this->webUser = $this->drupalCreateUser(array('administer users', 'access user profiles'));
     $this->drupalLogin($this->webUser);
     // Verify correct breadcrumb and page title on another user's account pages.
     $trail = $home;
     $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());
     $trail += array('user/' . $this->adminUser->id() => $this->adminUser->getUsername());
     $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername());
     // Verify correct breadcrumb and page title when viewing own user account.
     $trail = $home;
     $this->assertBreadcrumb('user/' . $this->webUser->id(), $trail, $this->webUser->getUsername());
     $trail += array('user/' . $this->webUser->id() => $this->webUser->getUsername());
     $this->assertBreadcrumb('user/' . $this->webUser->id() . '/edit', $trail, $this->webUser->getUsername());
     // Create an only slightly privileged user being able to access site reports
     // but not administration pages.
     $this->webUser = $this->drupalCreateUser(array('access site reports'));
     $this->drupalLogin($this->webUser);
     // Verify that we can access recent log entries, there is a corresponding
     // page title, and that the breadcrumb is just the Home link (because the
     // user is not able to access "Administer".
     $trail = $home;
     $this->assertBreadcrumb('admin', $trail, t('Access denied'));
     $this->assertResponse(403);
     // Since the 'admin' path is not accessible, we still expect only the Home
     // link.
     $this->assertBreadcrumb('admin/reports', $trail, t('Reports'));
     $this->assertNoResponse(403);
     // Since the Reports page is accessible, that will show.
     $trail += array('admin/reports' => t('Reports'));
     $this->assertBreadcrumb('admin/reports/dblog', $trail, t('Recent log messages'));
     $this->assertNoResponse(403);
     // Ensure that the breadcrumb is safe against XSS.
     $this->drupalGet('menu-test/breadcrumb1/breadcrumb2/breadcrumb3');
     $this->assertRaw('<script>alert(12);</script>');
     $this->assertEscaped('<script>alert(123);</script>');
 }
Пример #22
0
 /**
  * {@inheritdoc}
  *
  * @param UserInterface $user
  *   User object
  *
  * @return String
  *   Title string
  */
 public function userBlogTitle(UserInterface $user)
 {
     return Xss::filter($user->getUsername()) . "'s blog";
 }
Пример #23
0
 /**
  * Tests the failed search text, and various other text on the search page.
  */
 function testSearchText()
 {
     $this->drupalLogin($this->searchingUser);
     $this->drupalGet('search/node');
     $this->assertText(t('Enter your keywords'));
     $this->assertText(t('Search'));
     $this->assertTitle(t('Search') . ' | Drupal', 'Search page title is correct');
     $edit = array();
     $search_terms = 'bike shed ' . $this->randomMachineName();
     $edit['keys'] = $search_terms;
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertText('search yielded no results');
     $this->assertText(t('Search'));
     $title_source = 'Search for @keywords | Drupal';
     $this->assertTitle(t($title_source, array('@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE))), 'Search page title is correct');
     $this->assertNoText('Node', 'Erroneous tab and breadcrumb text is not present');
     $this->assertNoText(t('Node'), 'Erroneous translated tab and breadcrumb text is not present');
     $this->assertText(t('Content'), 'Tab and breadcrumb text is present');
     $this->clickLink('Search help');
     $this->assertText('Search help', 'Correct title is on search help page');
     $this->assertText('Use upper-case OR to get more results', 'Correct text is on content search help page');
     // Search for a longer text, and see that it is in the title, truncated.
     $edit = array();
     $search_terms = 'Every word is like an unnecessary stain on silence and nothingness.';
     $edit['keys'] = $search_terms;
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertTitle(t($title_source, array('@keywords' => 'Every word is like an unnecessary stain on silence and…')), 'Search page title is correct');
     // Search for a string with a lot of special characters.
     $search_terms = 'Hear nothing > "see nothing" `feel' . " '1982.";
     $edit['keys'] = $search_terms;
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $actual_title = (string) current($this->xpath('//title'));
     $this->assertEqual($actual_title, String::decodeEntities(t($title_source, array('@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE)))), 'Search page title is correct');
     $edit['keys'] = $this->searchingUser->getUsername();
     $this->drupalPostForm('search/user', $edit, t('Search'));
     $this->assertText(t('Search'));
     $this->assertTitle(t($title_source, array('@keywords' => Unicode::truncate($this->searchingUser->getUsername(), 60, TRUE, TRUE))));
     $this->clickLink('Search help');
     $this->assertText('Search help', 'Correct title is on search help page');
     $this->assertText('user names and partial user names', 'Correct text is on user search help page');
     // Test that search keywords containing slashes are correctly loaded
     // from the GET params and displayed in the search form.
     $arg = $this->randomMachineName() . '/' . $this->randomMachineName();
     $this->drupalGet('search/node', array('query' => array('keys' => $arg)));
     $input = $this->xpath("//input[@id='edit-keys' and @value='{$arg}']");
     $this->assertFalse(empty($input), 'Search keys with a / are correctly set as the default value in the search box.');
     // Test a search input exceeding the limit of AND/OR combinations to test
     // the Denial-of-Service protection.
     $limit = $this->config('search.settings')->get('and_or_limit');
     $keys = array();
     for ($i = 0; $i < $limit + 1; $i++) {
         // Use a key of 4 characters to ensure we never generate 'AND' or 'OR'.
         $keys[] = $this->randomMachineName(4);
         if ($i % 2 == 0) {
             $keys[] = 'OR';
         }
     }
     $edit['keys'] = implode(' ', $keys);
     $this->drupalPostForm('search/node', $edit, t('Search'));
     $this->assertRaw(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => $limit)));
     // Test that a search on Node or User with no keywords entered generates
     // the "Please enter some keywords" message.
     $this->drupalPostForm('search/node', array(), t('Search'));
     $this->assertText(t('Please enter some keywords'), 'With no keywords entered, message is displayed on node page');
     $this->drupalPostForm('search/user', array(), t('Search'));
     $this->assertText(t('Please enter some keywords'), 'With no keywords entered, message is displayed on user page');
     // Make sure the "Please enter some keywords" message is NOT displayed if
     // you use "or" words or phrases in Advanced Search.
     $this->drupalPostForm('search/node', array('or' => $this->randomMachineName() . ' ' . $this->randomMachineName()), t('Advanced search'));
     $this->assertNoText(t('Please enter some keywords'), 'With advanced OR keywords entered, no keywords message is not displayed on node page');
     $this->drupalPostForm('search/node', array('phrase' => '"' . $this->randomMachineName() . '" "' . $this->randomMachineName() . '"'), t('Advanced search'));
     $this->assertNoText(t('Please enter some keywords'), 'With advanced phrase entered, no keywords message is not displayed on node page');
     // Verify that if you search for a too-short keyword, you get the right
     // message, and that if after that you search for a longer keyword, you
     // do not still see the message.
     $this->drupalPostForm('search/node', array('keys' => $this->randomMachineName(1)), t('Search'));
     $this->assertText('You must include at least one positive keyword', 'Keyword message is displayed when searching for short word');
     $this->assertNoText(t('Please enter some keywords'), 'With short word entered, no keywords message is not displayed');
     $this->drupalPostForm(NULL, array('keys' => $this->randomMachineName()), t('Search'));
     $this->assertNoText('You must include at least one positive keyword', 'Keyword message is not displayed when searching for long word after short word search');
     // Test that if you search for a URL with .. in it, you still end up at
     // the search page. See issue https://drupal.org/node/890058.
     $this->drupalPostForm('search/node', array('keys' => '../../admin'), t('Search'));
     $this->assertResponse(200, 'Searching for ../../admin with non-admin user does not lead to a 403 error');
     $this->assertText('no results', 'Searching for ../../admin with non-admin user gives you a no search results page');
     // Test that if you search for a URL starting with "./", you still end up
     // at the search page. See issue https://drupal.org/node/1421560.
     $this->drupalPostForm('search/node', array('keys' => '.something'), t('Search'));
     $this->assertResponse(200, 'Searching for .something does not lead to a 403 error');
     $this->assertText('no results', 'Searching for .something gives you a no search results page');
 }
Пример #24
0
 public function flickr_photos_page_title(\Drupal\user\UserInterface $user)
 {
     return 'Flickr photos - ' . $user->getUsername();
 }
Пример #25
0
 /**
  * Route title callback.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user account.
  *
  * @return string
  *   The user account name.
  */
 public function userTitle(UserInterface $user = NULL)
 {
     return $user ? Xss::filter($user->getUsername()) : '';
 }
Пример #26
0
 /**
  * Tests access to the personal contact form.
  */
 function testPersonalContactAccess()
 {
     // Test allowed access to admin user's contact form.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
     $this->assertResponse(200);
     // Check the page title is properly displayed.
     $this->assertRaw(t('Contact @username', array('@username' => $this->adminUser->getUsername())));
     // Test denied access to admin user's own contact form.
     $this->drupalLogout();
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
     $this->assertResponse(403);
     // Test allowed access to user with contact form enabled.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(200);
     // Test that there is no access to personal contact forms for users
     // without an email address configured.
     $original_email = $this->contactUser->getEmail();
     $this->contactUser->setEmail(FALSE)->save();
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(404, 'Not found (404) returned when visiting a personal contact form for a user with no email address');
     // Test that the 'contact tab' does not appear on the user profiles
     // for users without an email address configured.
     $this->drupalGet('user/' . $this->contactUser->id());
     $contact_link = '/user/' . $this->contactUser->id() . '/contact';
     $this->assertResponse(200);
     $this->assertNoLinkByHref($contact_link, 'The "contact" tab is hidden on profiles for users with no email address');
     // Restore original email address.
     $this->contactUser->setEmail($original_email)->save();
     // Test denied access to the user's own contact form.
     $this->drupalGet('user/' . $this->webUser->id() . '/contact');
     $this->assertResponse(403);
     // Test always denied access to the anonymous user contact form.
     $this->drupalGet('user/0/contact');
     $this->assertResponse(403);
     // Test that anonymous users can access the contact form.
     $this->drupalLogout();
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access user contact forms'));
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(200);
     // Test that anonymous users can access admin user's contact form.
     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
     $this->assertResponse(200);
     // Revoke the personal contact permission for the anonymous user.
     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access user contact forms'));
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(403);
     $this->drupalGet('user/' . $this->adminUser->id() . '/contact');
     $this->assertResponse(403);
     // Disable the personal contact form.
     $this->drupalLogin($this->adminUser);
     $edit = array('contact_default_status' => FALSE);
     $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
     $this->assertText(t('The configuration options have been saved.'), 'Setting successfully saved.');
     $this->drupalLogout();
     // Re-create our contacted user with personal contact forms disabled by
     // default.
     $this->contactUser = $this->drupalCreateUser();
     // Test denied access to a user with contact form disabled.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(403);
     // Test allowed access for admin user to a user with contact form disabled.
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(200);
     // Re-create our contacted user as a blocked user.
     $this->contactUser = $this->drupalCreateUser();
     $this->contactUser->block();
     $this->contactUser->save();
     // Test that blocked users can still be contacted by admin.
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(200);
     // Test that blocked users cannot be contacted by non-admins.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(403);
     // Test enabling and disabling the contact page through the user profile
     // form.
     $this->drupalGet('user/' . $this->webUser->id() . '/edit');
     $this->assertNoFieldChecked('edit-contact--2');
     $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form disabled');
     $this->drupalPostForm(NULL, array('contact' => TRUE), t('Save'));
     $this->assertFieldChecked('edit-contact--2');
     $this->assertTrue(\Drupal::service('user.data')->get('contact', $this->webUser->id(), 'enabled'), 'Personal contact form enabled');
     // Test with disabled global default contact form in combination with a user
     // that has the contact form enabled.
     $this->config('contact.settings')->set('user_default_enabled', FALSE)->save();
     $this->contactUser = $this->drupalCreateUser();
     \Drupal::service('user.data')->set('contact', $this->contactUser->id(), 'enabled', 1);
     $this->drupalGet('user/' . $this->contactUser->id() . '/contact');
     $this->assertResponse(200);
 }
Пример #27
0
 /**
  * Form constructor for the personal contact form.
  *
  * @param \Drupal\user\UserInterface $user
  *   The account for which a personal contact form should be generated.
  *
  * @return array
  *   The personal contact form as render array as expected by drupal_render().
  */
 public function contactPersonalPage(UserInterface $user)
 {
     // Check if flood control has been activated for sending emails.
     if (!$this->currentUser()->hasPermission('administer contact forms') && !$this->currentUser()->hasPermission('administer users')) {
         $this->contactFloodControl();
     }
     $message = $this->entityManager()->getStorage('contact_message')->create(array('category' => 'personal', 'recipient' => $user->id()));
     $form = $this->entityFormBuilder()->getForm($message);
     $form['#title'] = $this->t('Contact @username', array('@username' => $user->getUsername()));
     return $form;
 }
Пример #28
0
 /**
  * {@inheritdoc}
  */
 public function getUsername()
 {
     return $this->subject->getUsername();
 }
 /**
  * Checks that workflows have the expected behaviors for the given user.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user to test the workflow behavior against.
  * @param array $expected_status
  *   The an associative array with the operation name as key and the expected
  *   status as value.
  */
 protected function assertWorkflows(UserInterface $user, $expected_status)
 {
     $default_langcode = $this->langcodes[0];
     $languages = $this->container->get('language_manager')->getLanguages();
     $args = array('@user_label' => $user->getUsername());
     $this->drupalLogin($user);
     // Check whether the user is allowed to access the entity form in edit mode.
     $options = array('language' => $languages[$default_langcode], 'absolute' => TRUE);
     $edit_url = $this->entity->urlInfo('edit-form', $options);
     $this->drupalGet($edit_url, $options);
     $this->assertResponse($expected_status['edit'], format_string('The @user_label has the expected edit access.', $args));
     // Check whether the user is allowed to access the translation overview.
     $langcode = $this->langcodes[1];
     $options = array('language' => $languages[$langcode], 'absolute' => TRUE);
     $translations_url = $this->entity->url('drupal:content-translation-overview', $options);
     $this->drupalGet($translations_url);
     $this->assertResponse($expected_status['overview'], format_string('The @user_label has the expected translation overview access.', $args));
     // Check whether the user is allowed to create a translation.
     $add_translation_url = Url::fromRoute('content_translation.translation_add_' . $this->entityTypeId, [$this->entityTypeId => $this->entity->id(), 'source' => $default_langcode, 'target' => $langcode], $options);
     if ($expected_status['add_translation'] == 200) {
         $this->clickLink('Add');
         $this->assertUrl($add_translation_url->toString(), array(), 'The translation overview points to the translation form when creating translations.');
         // Check that the translation form does not contain shared elements for
         // translators.
         if ($expected_status['edit'] == 403) {
             $this->assertNoSharedElements();
         }
     } else {
         $this->drupalGet($add_translation_url);
     }
     $this->assertResponse($expected_status['add_translation'], format_string('The @user_label has the expected translation creation access.', $args));
     // Check whether the user is allowed to edit a translation.
     $langcode = $this->langcodes[2];
     $options['language'] = $languages[$langcode];
     $edit_translation_url = Url::fromRoute('content_translation.translation_edit_' . $this->entityTypeId, [$this->entityTypeId => $this->entity->id(), 'language' => $langcode], $options);
     $options = ['language' => $languages[$langcode], 'absolute' => TRUE];
     if ($expected_status['edit_translation'] == 200) {
         $this->drupalGet($translations_url);
         $editor = $expected_status['edit'] == 200;
         if ($editor) {
             $this->clickLink('Edit', 2);
             // An editor should be pointed to the entity form in multilingual mode.
             // We need a new expected edit path with a new language.
             $expected_edit_path = $this->entity->url('edit-form', $options);
             $this->assertUrl($expected_edit_path, [], 'The translation overview points to the edit form for editors when editing translations.');
         } else {
             $this->clickLink('Edit');
             // While a translator should be pointed to the translation form.
             $this->assertUrl($edit_translation_url->toString(), array(), 'The translation overview points to the translation form for translators when editing translations.');
             // Check that the translation form does not contain shared elements.
             $this->assertNoSharedElements();
         }
     } else {
         $this->drupalGet($edit_translation_url);
     }
     $this->assertResponse($expected_status['edit_translation'], format_string('The @user_label has the expected translation creation access.', $args));
 }
Пример #30
0
 /**
  * Title callback for the tracker.user_tab route.
  */
 public function getTitle(UserInterface $user)
 {
     return SafeMarkup::checkPlain($user->getUsername());
 }