Beispiel #1
0
 protected function setUp()
 {
     parent::setUp();
     // Remove the "view own unpublished content" permission which is set
     // by default for authenticated users so we can test this permission
     // correctly.
     user_role_revoke_permissions(RoleInterface::AUTHENTICATED_ID, array('view own unpublished content'));
     $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'access content overview', 'administer nodes', 'bypass node access'));
     $this->baseUser1 = $this->drupalCreateUser(['access content overview']);
     $this->baseUser2 = $this->drupalCreateUser(['access content overview', 'view own unpublished content']);
     $this->baseUser3 = $this->drupalCreateUser(['access content overview', 'bypass node access']);
 }
 protected function setUp()
 {
     parent::setUp();
     // Remove access content permission from registered users.
     user_role_revoke_permissions(DRUPAL_AUTHENTICATED_RID, array('access content'));
     $this->vocabulary = $this->createVocabulary();
     // Add a field to the vocabulary.
     $entity_type = 'taxonomy_term';
     $name = 'field_test';
     entity_create('field_storage_config', array('field_name' => $name, 'entity_type' => $entity_type, 'type' => 'image', 'settings' => array('uri_scheme' => 'private')))->save();
     entity_create('field_config', array('field_name' => $name, 'entity_type' => $entity_type, 'bundle' => $this->vocabulary->id(), 'settings' => array()))->save();
     entity_get_display($entity_type, $this->vocabulary->id(), 'default')->setComponent($name, array('type' => 'image', 'settings' => array()))->save();
     entity_get_form_display($entity_type, $this->vocabulary->id(), 'default')->setComponent($name, array('type' => 'image_image', 'settings' => array()))->save();
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // We revoke the access content permission because we use that to test our
     // permissions around entity view.
     user_role_revoke_permissions(AccountInterface::ANONYMOUS_ROLE, ['access content']);
     user_role_revoke_permissions(AccountInterface::AUTHENTICATED_ROLE, ['access content']);
     // Create a content type and a dummy node.
     $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Page'));
     $this->node = $this->drupalCreateNode();
     // Install our custom theme.
     $theme = 'entity_print_test_theme';
     \Drupal::service('theme_handler')->install([$theme]);
     $this->config('system.theme')->set('default', $theme)->save();
 }
Beispiel #4
0
 /**
  * Tests the recent comments block.
  */
 function testRecentCommentBlock()
 {
     $this->drupalLogin($this->adminUser);
     $block = $this->drupalPlaceBlock('views_block:comments_recent-block_1');
     // Add some test comments, with and without subjects. Because the 10 newest
     // comments should be shown by the block, we create 11 to test that behavior
     // below.
     $timestamp = REQUEST_TIME;
     for ($i = 0; $i < 11; ++$i) {
         $subject = $i % 2 ? $this->randomMachineName() : '';
         $comments[$i] = $this->postComment($this->node, $this->randomMachineName(), $subject);
         $comments[$i]->created->value = $timestamp--;
         $comments[$i]->save();
     }
     // Test that a user without the 'access comments' permission cannot see the
     // block.
     $this->drupalLogout();
     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
     $this->drupalGet('');
     $this->assertNoText(t('Recent comments'));
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
     // Test that a user with the 'access comments' permission can see the
     // block.
     $this->drupalLogin($this->webUser);
     $this->drupalGet('');
     $this->assertText(t('Recent comments'));
     // Test the only the 10 latest comments are shown and in the proper order.
     $this->assertNoText($comments[10]->getSubject(), 'Comment 11 not found in block.');
     for ($i = 0; $i < 10; $i++) {
         $this->assertText($comments[$i]->getSubject(), SafeMarkup::format('Comment @number found in block.', array('@number' => 10 - $i)));
         if ($i > 1) {
             $previous_position = $position;
             $position = strpos($this->getRawContent(), $comments[$i]->getSubject());
             $this->assertTrue($position > $previous_position, SafeMarkup::format('Comment @a appears after comment @b', array('@a' => 10 - $i, '@b' => 11 - $i)));
         }
         $position = strpos($this->getRawContent(), $comments[$i]->getSubject());
     }
     // Test that links to comments work when comments are across pages.
     $this->setCommentsPerPage(1);
     for ($i = 0; $i < 10; $i++) {
         $this->clickLink($comments[$i]->getSubject());
         $this->assertText($comments[$i]->getSubject(), 'Comment link goes to correct page.');
         $this->assertRaw('<link rel="canonical"', 'Canonical URL was found in the HTML head');
     }
 }
/**
 * Configure permissions.
 *
 * @todo this is here because I cannot add it inside module due to SQL error:
 * SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot
 * be null.
 *
 * {@inheritdoc}
 */
function osha_configure_permissions()
{
    if ($role = user_role_load_by_name('administrator')) {
        $vocabularies = array('activity', 'article_types', 'esener', 'nace_codes', 'section', 'thesaurus', 'wiki_categories', 'workflow_status', 'publication_types', 'newsletter_sections');
        $permissions = array();
        foreach ($vocabularies as $voc_name) {
            if ($voc = taxonomy_vocabulary_machine_name_load($voc_name)) {
                $permissions[] = 'add terms in ' . $voc_name;
                $permissions[] = 'edit terms in ' . $voc->vid;
                $permissions[] = 'delete terms in ' . $voc->vid;
            }
        }
        $permissions[] = 'access workbench access by role';
        $permissions[] = 'translate taxonomy_term entities';
        $permissions[] = 'edit any content in rejected';
        $permissions[] = 'edit any content in approved';
        $permissions[] = 'edit any content in final_draft';
        $permissions[] = 'edit any content in to_be_approved';
        // Workbench access permissions.
        $moderated_types = workbench_moderation_moderate_node_types();
        $transitions = workbench_moderation_transitions();
        foreach ($transitions as $transition) {
            $permissions[] = "moderate content from {$transition->from_name} to {$transition->to_name}";
            foreach ($moderated_types as $node_type) {
                //@todo: $permissions[] = "moderate $node_type state from {$transition->from_name} to {$transition->to_name}";
            }
        }
        $permissions[] = 'create moderators_group entity collections';
        $permissions[] = 'edit moderators_group entity collections';
        $permissions[] = 'view moderators_group entity collections';
        $permissions[] = 'delete moderators_group entity collections';
        $permissions[] = 'add content to moderators_group entity collections';
        $permissions[] = 'manage content in moderators_group entity collections';
        user_role_grant_permissions($role->rid, $permissions);
        user_role_revoke_permissions($role->rid, array('use workbench_moderation needs review tab'));
    }
    $roles = array(OSHA_WORKFLOW_ROLE_TRANSLATION_MANAGER, OSHA_WORKFLOW_ROLE_TRANSLATION_LIAISON, OSHA_WORKFLOW_ROLE_LAYOUT_VALIDATOR, OSHA_WORKFLOW_ROLE_CONTENT_VALIDATOR);
    foreach ($roles as $role_name) {
        if ($role = user_role_load_by_name($role_name)) {
            user_role_grant_permissions($role->rid, array('access workbench'));
        }
    }
}
 /**
  * Tests the handling of aliased requests.
  */
 function testDomainAliasNegotiator()
 {
     // No domains should exist.
     $this->domainTableIsEmpty();
     // Create two new domains programmatically.
     $this->domainCreateTestDomains(2);
     // Since we cannot read the service request, we place a block
     // which shows the current domain information.
     $this->drupalPlaceBlock('domain_server_block');
     // To get around block access, let the anon user view the block.
     user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('administer domains'));
     // Test the response of the default home page.
     foreach (\Drupal::service('domain.loader')->loadMultiple() as $domain) {
         if (!isset($alias_domain)) {
             $alias_domain = $domain;
         }
         $this->drupalGet($domain->getPath());
         $this->assertRaw($domain->label(), 'Loaded the proper domain.');
         $this->assertRaw('Exact match', 'Direct domain match.');
     }
     // Now, test an alias.
     $this->domainAliasCreateTestAlias($alias_domain);
     $pattern = '*.' . $alias_domain->getHostname();
     $alias = \Drupal::service('domain_alias.loader')->loadByPattern($pattern);
     $alias_domain->set('hostname', 'two.' . $alias_domain->getHostname());
     $alias_domain->setPath();
     $url = $alias_domain->getPath();
     $this->drupalGet($url);
     $this->assertRaw($alias_domain->label(), 'Loaded the proper domain.');
     $this->assertRaw('ALIAS:', 'No direct domain match.');
     $this->assertRaw($alias->getPattern(), 'Alias match.');
     // Test redirections.
     // @TODO: This could be much more elegant: the redirects break assertRaw()
     $alias->set('redirect', 301);
     $alias->save();
     $this->drupalGet($url);
     $alias->set('redirect', 302);
     $alias->save();
     $this->drupalGet($url);
     // Revoke the permission change
     user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('administer domains'));
 }
Beispiel #7
0
 /**
  * Tests the handling of an inbound request.
  */
 function testDomainNegotiator()
 {
     // No domains should exist.
     $this->domainTableIsEmpty();
     // Create four new domains programmatically.
     $this->domainCreateTestDomains(4);
     // Since we cannot read the service request, we place a block
     // which shows the current domain information.
     $this->drupalPlaceBlock('domain_server_block');
     // To get around block access, let the anon user view the block.
     user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('view domain information'));
     // Test the response of the default home page.
     foreach (\Drupal::service('domain.loader')->loadMultiple() as $domain) {
         $this->drupalGet($domain->getPath());
         $this->assertRaw($domain->label(), 'Loaded the proper domain.');
     }
     // Revoke the permission change
     user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('view domain information'));
     // @TODO: Any other testing needed here?
 }
 /**
  * Tests configuration options and the site-wide contact form.
  */
 function testSiteWideContact()
 {
     // Create and login administrative user.
     $admin_user = $this->drupalCreateUser(array('access site-wide contact form', 'administer contact forms', 'administer users', 'administer account settings', 'administer contact_message fields'));
     $this->drupalLogin($admin_user);
     // Check the presence of expected cache tags.
     $this->drupalGet('contact');
     $this->assertCacheTag('config:contact.settings');
     $flood_limit = 3;
     $this->config('contact.settings')->set('flood.limit', $flood_limit)->set('flood.interval', 600)->save();
     // Set settings.
     $edit = array();
     $edit['contact_default_status'] = TRUE;
     $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
     $this->assertText(t('The configuration options have been saved.'));
     $this->drupalGet('admin/structure/contact');
     // Default form exists.
     $this->assertLinkByHref('admin/structure/contact/manage/feedback/delete');
     // User form could not be changed or deleted.
     // Cannot use ::assertNoLinkByHref as it does partial url matching and with
     // field_ui enabled admin/structure/contact/manage/personal/fields exists.
     // @todo: See https://www.drupal.org/node/2031223 for the above.
     $edit_link = $this->xpath('//a[@href=:href]', array(':href' => \Drupal::url('entity.contact_form.edit_form', array('contact_form' => 'personal'))));
     $this->assertTrue(empty($edit_link), format_string('No link containing href %href found.', array('%href' => 'admin/structure/contact/manage/personal')));
     $this->assertNoLinkByHref('admin/structure/contact/manage/personal/delete');
     $this->drupalGet('admin/structure/contact/manage/personal');
     $this->assertResponse(403);
     // Delete old forms to ensure that new forms are used.
     $this->deleteContactForms();
     $this->drupalGet('admin/structure/contact');
     $this->assertText('Personal', 'Personal form was not deleted');
     $this->assertNoLinkByHref('admin/structure/contact/manage/feedback');
     // Ensure that the contact form won't be shown without forms.
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
     $this->drupalLogout();
     $this->drupalGet('contact');
     $this->assertResponse(404);
     $this->drupalLogin($admin_user);
     $this->drupalGet('contact');
     $this->assertResponse(200);
     $this->assertText(t('The contact form has not been configured.'));
     // Test access personal form via site-wide contact page.
     $this->drupalGet('contact/personal');
     $this->assertResponse(403);
     // Add forms.
     // Test invalid recipients.
     $invalid_recipients = array('invalid', 'invalid@', 'invalid@site.', '@site.', '@site.com');
     foreach ($invalid_recipients as $invalid_recipient) {
         $this->addContactForm($this->randomMachineName(16), $this->randomMachineName(16), $invalid_recipient, '', FALSE);
         $this->assertRaw(t('%recipient is an invalid email address.', array('%recipient' => $invalid_recipient)));
     }
     // Test validation of empty form and recipients fields.
     $this->addContactForm('', '', '', '', TRUE);
     $this->assertText(t('Label field is required.'));
     $this->assertText(t('Machine-readable name field is required.'));
     $this->assertText(t('Recipients field is required.'));
     // Test validation of max_length machine name.
     $recipients = array('simpletest&@example.com', '*****@*****.**', '*****@*****.**');
     $max_length = EntityTypeInterface::BUNDLE_MAX_LENGTH;
     $max_length_exceeded = $max_length + 1;
     $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length_exceeded)), $label = $this->randomMachineName($max_length_exceeded), implode(',', array($recipients[0])), '', TRUE);
     $this->assertText(format_string('Machine-readable name cannot be longer than @max characters but is currently @exceeded characters long.', array('@max' => $max_length, '@exceeded' => $max_length_exceeded)));
     $this->addContactForm($id = Unicode::strtolower($this->randomMachineName($max_length)), $label = $this->randomMachineName($max_length), implode(',', array($recipients[0])), '', TRUE);
     $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
     // Create first valid form.
     $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0])), '', TRUE);
     $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
     // Check that the form was created in site default language.
     $langcode = $this->config('contact.form.' . $id)->get('langcode');
     $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
     $this->assertEqual($langcode, $default_langcode);
     // Make sure the newly created form is included in the list of forms.
     $this->assertNoUniqueText($label, 'New form included in forms list.');
     // Ensure that the recipient email is escaped on the listing.
     $this->drupalGet('admin/structure/contact');
     $this->assertEscaped($recipients[0]);
     // Test update contact form.
     $this->updateContactForm($id, $label = $this->randomMachineName(16), $recipients_str = implode(',', array($recipients[0], $recipients[1])), $reply = $this->randomMachineName(30), FALSE);
     $config = $this->config('contact.form.' . $id)->get();
     $this->assertEqual($config['label'], $label);
     $this->assertEqual($config['recipients'], array($recipients[0], $recipients[1]));
     $this->assertEqual($config['reply'], $reply);
     $this->assertNotEqual($id, $this->config('contact.settings')->get('default_form'));
     $this->assertRaw(t('Contact form %label has been updated.', array('%label' => $label)));
     // Ensure the label is displayed on the contact page for this form.
     $this->drupalGet('contact/' . $id);
     $this->assertText($label);
     // Reset the form back to be the default form.
     $this->config('contact.settings')->set('default_form', $id)->save();
     // Ensure that the contact form is shown without a form selection input.
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
     $this->drupalLogout();
     $this->drupalGet('contact');
     $this->assertText(t('Your email address'));
     $this->assertNoText(t('Form'));
     $this->drupalLogin($admin_user);
     // Add more forms.
     $this->addContactForm(Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1])), '', FALSE);
     $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
     $this->addContactForm($name = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($recipients[0], $recipients[1], $recipients[2])), '', FALSE);
     $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label)));
     // Try adding a form that already exists.
     $this->addContactForm($name, $label, '', '', FALSE);
     $this->assertNoRaw(t('Contact form %label has been added.', array('%label' => $label)));
     $this->assertRaw(t('The machine-readable name is already in use. It must be unique.'));
     // Clear flood table in preparation for flood test and allow other checks to complete.
     db_delete('flood')->execute();
     $num_records_after = db_query("SELECT COUNT(*) FROM {flood}")->fetchField();
     $this->assertIdentical($num_records_after, '0', 'Flood table emptied.');
     $this->drupalLogout();
     // Check to see that anonymous user cannot see contact page without permission.
     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
     $this->drupalGet('contact');
     $this->assertResponse(403);
     // Give anonymous user permission and see that page is viewable.
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form'));
     $this->drupalGet('contact');
     $this->assertResponse(200);
     // Submit contact form with invalid values.
     $this->submitContact('', $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
     $this->assertText(t('Your name field is required.'));
     $this->submitContact($this->randomMachineName(16), '', $this->randomMachineName(16), $id, $this->randomMachineName(64));
     $this->assertText(t('Your email address field is required.'));
     $this->submitContact($this->randomMachineName(16), $invalid_recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
     $this->assertRaw(t('The email address %mail is not valid.', array('%mail' => 'invalid')));
     $this->submitContact($this->randomMachineName(16), $recipients[0], '', $id, $this->randomMachineName(64));
     $this->assertText(t('Subject field is required.'));
     $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, '');
     $this->assertText(t('Message field is required.'));
     // Test contact form with no default form selected.
     $this->config('contact.settings')->set('default_form', '')->save();
     $this->drupalGet('contact');
     $this->assertResponse(404);
     // Try to access contact form with non-existing form IDs.
     $this->drupalGet('contact/0');
     $this->assertResponse(404);
     $this->drupalGet('contact/' . $this->randomMachineName());
     $this->assertResponse(404);
     // Submit contact form with correct values and check flood interval.
     for ($i = 0; $i < $flood_limit; $i++) {
         $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
         $this->assertText(t('Your message has been sent.'));
     }
     // Submit contact form one over limit.
     $this->submitContact($this->randomMachineName(16), $recipients[0], $this->randomMachineName(16), $id, $this->randomMachineName(64));
     $this->assertRaw(t('You cannot send more than %number messages in 10 min. Try again later.', array('%number' => $this->config('contact.settings')->get('flood.limit'))));
     // Test listing controller.
     $this->drupalLogin($admin_user);
     $this->deleteContactForms();
     $label = $this->randomMachineName(16);
     $recipients = implode(',', array($recipients[0], $recipients[1], $recipients[2]));
     $contact_form = Unicode::strtolower($this->randomMachineName(16));
     $this->addContactForm($contact_form, $label, $recipients, '', FALSE);
     $this->drupalGet('admin/structure/contact');
     $this->clickLink(t('Edit'));
     $this->assertResponse(200);
     $this->assertFieldByName('label', $label);
     // Test field UI and field integration.
     $this->drupalGet('admin/structure/contact');
     $view_link = $this->xpath('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [':href' => \Drupal::url('entity.contact_form.canonical', ['contact_form' => $contact_form]), ':text' => $label]);
     $this->assertTrue(!empty($view_link), 'Contact listing links to contact form.');
     // Find out in which row the form we want to add a field to is.
     $i = 0;
     foreach ($this->xpath('//table/tbody/tr') as $row) {
         if ((string) $row->td[0]->a == $label) {
             break;
         }
         $i++;
     }
     $this->clickLink(t('Manage fields'), $i);
     $this->assertResponse(200);
     $this->clickLink(t('Add field'));
     $this->assertResponse(200);
     // Create a simple textfield.
     $field_name = Unicode::strtolower($this->randomMachineName());
     $field_label = $this->randomMachineName();
     $this->fieldUIAddNewField(NULL, $field_name, $field_label, 'text');
     $field_name = 'field_' . $field_name;
     // Check that the field is displayed.
     $this->drupalGet('contact/' . $contact_form);
     $this->assertText($field_label);
     // Submit the contact form and verify the content.
     $edit = array('subject[0][value]' => $this->randomMachineName(), 'message[0][value]' => $this->randomMachineName(), $field_name . '[0][value]' => $this->randomMachineName());
     $this->drupalPostForm(NULL, $edit, t('Send message'));
     $mails = $this->drupalGetMails();
     $mail = array_pop($mails);
     $this->assertEqual($mail['subject'], t('[@label] @subject', array('@label' => $label, '@subject' => $edit['subject[0][value]'])));
     $this->assertTrue(strpos($mail['body'], $field_label));
     $this->assertTrue(strpos($mail['body'], $edit[$field_name . '[0][value]']));
 }
 /**
  * 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->getDisplayName())));
     // 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);
     $this->assertCacheContext('user');
     // 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->assertCacheContext('user');
     $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);
 }
Beispiel #10
0
 /**
  * Find any users/roles/security-principals with the given permission
  * and replace it with one or more permissions.
  *
  * @param $oldPerm string
  * @param $newPerms array, strings
  *
  * @return void
  */
 function replacePermission($oldPerm, $newPerms)
 {
     $roles = user_roles(FALSE, $oldPerm);
     if (!empty($roles)) {
         foreach (array_keys($roles) as $rid) {
             user_role_revoke_permissions($rid, array($oldPerm));
             user_role_grant_permissions($rid, $newPerms);
         }
     }
 }
Beispiel #11
0
 /**
  * Revoke permissions to a specific role, if it exists.
  *
  * @param string $role
  *    Role machine name.
  * @param string $permission
  *    Permission machine name.
  *
  * @return bool
  *    TRUE if operation was successful, FALSE otherwise.
  */
 public function revokePermission($role, $permission)
 {
     $role_object = user_role_load_by_name($role);
     if ($role_object) {
         user_role_revoke_permissions($role_object->rid, array($permission));
         return TRUE;
     } else {
         return FALSE;
     }
 }
 /**
  * Tests that download restrictions on private files work on comments.
  */
 function testPrivateFileComment()
 {
     $user = $this->drupalCreateUser(array('access comments'));
     // Grant the admin user required comment permissions.
     $roles = $this->adminUser->getRoles();
     user_role_grant_permissions($roles[1], array('administer comment fields', 'administer comments'));
     // Revoke access comments permission from anon user, grant post to
     // authenticated.
     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
     user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array('post comments', 'skip comment approval'));
     // Create a new field.
     $this->addDefaultCommentField('node', 'article');
     $name = strtolower($this->randomMachineName());
     $label = $this->randomMachineName();
     $storage_edit = array('settings[uri_scheme]' => 'private');
     $this->fieldUIAddNewField('admin/structure/comment/manage/comment', $name, $label, 'file', $storage_edit);
     // Manually clear cache on the tester side.
     \Drupal::entityManager()->clearCachedFieldDefinitions();
     // Create node.
     $edit = array('title[0][value]' => $this->randomMachineName());
     $this->drupalPostForm('node/add/article', $edit, t('Save and publish'));
     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
     // Add a comment with a file.
     $text_file = $this->getTestFile('text');
     $edit = array('files[field_' . $name . '_' . 0 . ']' => drupal_realpath($text_file->getFileUri()), 'comment_body[0][value]' => $comment_body = $this->randomMachineName());
     $this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
     // Get the comment ID.
     preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
     $cid = $matches[1];
     // Log in as normal user.
     $this->drupalLogin($user);
     $comment = Comment::load($cid);
     $comment_file = $comment->{'field_' . $name}->entity;
     $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
     // Test authenticated file download.
     $url = file_create_url($comment_file->getFileUri());
     $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
     $this->drupalGet(file_create_url($comment_file->getFileUri()));
     $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
     // Test anonymous file download.
     $this->drupalLogout();
     $this->drupalGet(file_create_url($comment_file->getFileUri()));
     $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
     // Unpublishes node.
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save and unpublish'));
     // Ensures normal user can no longer download the file.
     $this->drupalLogin($user);
     $this->drupalGet(file_create_url($comment_file->getFileUri()));
     $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
 }
 /**
  * Tests anonymous comment functionality.
  */
 function testAnonymous()
 {
     $this->drupalLogin($this->adminUser);
     $this->setCommentAnonymous(COMMENT_ANONYMOUS_MAYNOT_CONTACT);
     $this->drupalLogout();
     // Preview comments (with `skip comment approval` permission).
     $edit = [];
     $title = 'comment title with skip comment approval';
     $body = 'comment body with skip comment approval';
     $edit['subject[0][value]'] = $title;
     $edit['comment_body[0][value]'] = $body;
     $this->drupalPostForm($this->node->urlInfo(), $edit, t('Preview'));
     // Cannot use assertRaw here since both title and body are in the form.
     $preview = (string) $this->cssSelect('.preview')[0]->asXML();
     $this->assertTrue(strpos($preview, $title) !== FALSE, 'Anonymous user can preview comment title.');
     $this->assertTrue(strpos($preview, $body) !== FALSE, 'Anonymous user can preview comment body.');
     // Preview comments (without `skip comment approval` permission).
     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['skip comment approval']);
     $edit = [];
     $title = 'comment title without skip comment approval';
     $body = 'comment body without skip comment approval';
     $edit['subject[0][value]'] = $title;
     $edit['comment_body[0][value]'] = $body;
     $this->drupalPostForm($this->node->urlInfo(), $edit, t('Preview'));
     // Cannot use assertRaw here since both title and body are in the form.
     $preview = (string) $this->cssSelect('.preview')[0]->asXML();
     $this->assertTrue(strpos($preview, $title) !== FALSE, 'Anonymous user can preview comment title.');
     $this->assertTrue(strpos($preview, $body) !== FALSE, 'Anonymous user can preview comment body.');
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['skip comment approval']);
     // Post anonymous comment without contact info.
     $anonymous_comment1 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
     $this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.');
     // Allow contact info.
     $this->drupalLogin($this->adminUser);
     $this->setCommentAnonymous(COMMENT_ANONYMOUS_MAY_CONTACT);
     // Attempt to edit anonymous comment.
     $this->drupalGet('comment/' . $anonymous_comment1->id() . '/edit');
     $edited_comment = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName());
     $this->assertTrue($this->commentExists($edited_comment, FALSE), 'Modified reply found.');
     $this->drupalLogout();
     // Post anonymous comment with contact info (optional).
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
     $this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
     // Check the presence of expected cache tags.
     $this->assertCacheTag('config:field.field.node.article.comment');
     $this->assertCacheTag('config:user.settings');
     $anonymous_comment2 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
     $this->assertTrue($this->commentExists($anonymous_comment2), 'Anonymous comment with contact info (optional) found.');
     // Ensure anonymous users cannot post in the name of registered users.
     $edit = array('name' => $this->adminUser->getUsername(), 'mail' => $this->randomMachineName() . '@example.com', 'subject[0][value]' => $this->randomMachineName(), 'comment_body[0][value]' => $this->randomMachineName());
     $this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit, t('Save'));
     $this->assertRaw(t('The name you used (%name) belongs to a registered user.', ['%name' => $this->adminUser->getUsername()]));
     // Require contact info.
     $this->drupalLogin($this->adminUser);
     $this->setCommentAnonymous(COMMENT_ANONYMOUS_MUST_CONTACT);
     $this->drupalLogout();
     // Try to post comment with contact info (required).
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
     $this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
     $anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), TRUE);
     // Name should have 'Anonymous' for value by default.
     $this->assertText(t('Email field is required.'), 'Email required.');
     $this->assertFalse($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) not found.');
     // Post comment with contact info (required).
     $author_name = $this->randomMachineName();
     $author_mail = $this->randomMachineName() . '@example.com';
     $anonymous_comment3 = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName(), array('name' => $author_name, 'mail' => $author_mail));
     $this->assertTrue($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) found.');
     // Make sure the user data appears correctly when editing the comment.
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('comment/' . $anonymous_comment3->id() . '/edit');
     $this->assertRaw($author_name, "The anonymous user's name is correct when editing the comment.");
     $this->assertFieldByName('uid', '', 'The author field is empty (i.e. anonymous) when editing the comment.');
     $this->assertRaw($author_mail, "The anonymous user's email address is correct when editing the comment.");
     // Unpublish comment.
     $this->performCommentOperation($anonymous_comment3, 'unpublish');
     $this->drupalGet('admin/content/comment/approval');
     $this->assertRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was unpublished.');
     // Publish comment.
     $this->performCommentOperation($anonymous_comment3, 'publish', TRUE);
     $this->drupalGet('admin/content/comment');
     $this->assertRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was published.');
     // Delete comment.
     $this->performCommentOperation($anonymous_comment3, 'delete');
     $this->drupalGet('admin/content/comment');
     $this->assertNoRaw('comments[' . $anonymous_comment3->id() . ']', 'Comment was deleted.');
     $this->drupalLogout();
     // Comment 3 was deleted.
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $anonymous_comment3->id());
     $this->assertResponse(403);
     // Reset.
     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => FALSE, 'post comments' => FALSE, 'skip comment approval' => FALSE));
     // Attempt to view comments while disallowed.
     // NOTE: if authenticated user has permission to post comments, then a
     // "Login or register to post comments" type link may be shown.
     $this->drupalGet('node/' . $this->node->id());
     $this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
     $this->assertNoLink('Add new comment', 'Link to add comment was found.');
     // Attempt to view node-comment form while disallowed.
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
     $this->assertResponse(403);
     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => TRUE, 'post comments' => FALSE, 'skip comment approval' => FALSE));
     $this->drupalGet('node/' . $this->node->id());
     $this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
     $this->assertLink('Log in', 1, 'Link to log in was found.');
     $this->assertLink('register', 1, 'Link to register was found.');
     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => FALSE, 'post comments' => TRUE, 'skip comment approval' => TRUE));
     $this->drupalGet('node/' . $this->node->id());
     $this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
     $this->assertFieldByName('subject[0][value]', '', 'Subject field found.');
     $this->assertFieldByName('comment_body[0][value]', '', 'Comment field found.');
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment/' . $anonymous_comment2->id());
     $this->assertResponse(403);
 }
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $flag = $this->entity;

    $flag->getFlagTypePlugin()->submitConfigurationForm($form, $form_state);
    $flag->getLinkTypePlugin()->submitConfigurationForm($form, $form_state);

    $flag->enable();
    $status = $flag->save();
    $url = $flag->urlInfo();
    if ($status == SAVED_UPDATED) {
      drupal_set_message(t('Flag %label has been updated.', ['%label' => $flag->label()]));
      $this->logger('flag')->notice('Flag %label has been updated.', ['%label' => $flag->label(), 'link' => $this->l($this->t('Edit'), $url)]);
    }
    else {
      drupal_set_message(t('Flag %label has been added.', ['%label' => $flag->label()]));
      $this->logger('flag')->notice('Flag %label has been added.', ['%label' => $flag->label(), 'link' => $this->l($this->t('Edit'), $url)]);
    }

    // We clear caches more vigorously if the flag was new.
    // _flag_clear_cache($flag->entity_type, !empty($flag->is_new));

    // Save permissions.
    // This needs to be done after the flag cache has been cleared, so that
    // the new permissions are picked up by hook_permission().
    // This may need to move to the flag class when we implement extra
    // permissions for different flag types: http://drupal.org/node/879988

    // If the flag ID has changed, clean up all the obsolete permissions.
    if ($flag->id != $form['#flag_name']) {
      $old_name = $form['#flag_name'];
      $permissions = ["flag $old_name", "unflag $old_name"];
      foreach (array_keys(user_roles()) as $rid) {
        user_role_revoke_permissions($rid, $permissions);
      }
    }
    /*
        foreach (array_keys(user_roles(!\Drupal::moduleHandler()->moduleExists('session_api'))) as $rid) {
          // Create an array of permissions.
          $permissions = array(
            "flag $flag->name" => $flag->roles['flag'][$rid],
            "unflag $flag->name" => $flag->roles['unflag'][$rid],
          );
          user_role_change_permissions($rid, $permissions);
        }
    */
    // @todo: when we add database caching for flags we'll have to clear the
    // cache again here.

    $form_state->setRedirect('entity.flag.collection');
  }
 /**
  * Tests access to the personal contact form.
  */
 function testPersonalContactAccess()
 {
     // Test allowed access to admin user's contact form.
     $this->drupalLogin($this->web_user);
     $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
     $this->assertResponse(200);
     // Check the page title is properly displayed.
     $this->assertRaw(t('Contact @username', array('@username' => $this->admin_user->getUsername())));
     // Test denied access to admin user's own contact form.
     $this->drupalLogout();
     $this->drupalLogin($this->admin_user);
     $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
     $this->assertResponse(403);
     // Test allowed access to user with contact form enabled.
     $this->drupalLogin($this->web_user);
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(200);
     // Test denied access to the user's own contact form.
     $this->drupalGet('user/' . $this->web_user->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(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(200);
     // Test that anonymous users can access admin user's contact form.
     $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
     $this->assertResponse(200);
     // Revoke the personal contact permission for the anonymous user.
     user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(403);
     $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
     $this->assertResponse(403);
     // Disable the personal contact form.
     $this->drupalLogin($this->admin_user);
     $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->contact_user = $this->drupalCreateUser();
     // Test denied access to a user with contact form disabled.
     $this->drupalLogin($this->web_user);
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(403);
     // Test allowed access for admin user to a user with contact form disabled.
     $this->drupalLogin($this->admin_user);
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(200);
     // Re-create our contacted user as a blocked user.
     $this->contact_user = $this->drupalCreateUser();
     $this->contact_user->block();
     $this->contact_user->save();
     // Test that blocked users can still be contacted by admin.
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(200);
     // Test that blocked users cannot be contacted by non-admins.
     $this->drupalLogin($this->web_user);
     $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
     $this->assertResponse(403);
     // Test enabling and disabling the contact page through the user profile
     // form.
     $this->drupalGet('user/' . $this->web_user->id() . '/edit');
     $this->assertNoFieldChecked('edit-contact--2');
     $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->web_user->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->web_user->id(), 'enabled'), 'Personal contact form enabled');
 }
 /**
  * Grant/revoke permissions.
  *
  * @param array $options
  *   The permissions settings.
  */
 private function execPermissions(array $options)
 {
     $roles = array_flip(user_roles());
     foreach ($options as $role => $perm_settings) {
         // Get the role id based on the role name.
         if (isset($roles[$role])) {
             $rid = $roles[$role];
         } else {
             drush_set_error('DRUSH_DRUPAL_ERROR_MESSAGE', dt("Role '!role' does not exist.", ['!role' => $role]));
             continue;
         }
         // Group the grants and revokes.
         $perms = ['grant' => [], 'revoke' => []];
         foreach ($perm_settings as $perm => $status) {
             if ($status === 1 || strtolower($status) === 'grant') {
                 $perms['grant'][] = $perm;
             } else {
                 $perms['revoke'][] = $perm;
             }
         }
         if (!empty($perms['grant'])) {
             user_role_grant_permissions($rid, $perms['grant']);
             drush_print(dt("Granted to '!role': !permissions", ['!role' => $role, '!permissions' => implode(', ', $perms['grant'])]));
         }
         if (!empty($perms['revoke'])) {
             user_role_revoke_permissions($rid, $perms['revoke']);
             drush_print(dt("Revoked from '!role': !permissions", ['!role' => $role, '!permissions' => implode(', ', $perms['revoke'])]));
         }
     }
 }
Beispiel #17
0
 /**
  * Tests the views wizards provided by the media module.
  */
 public function testMediaViewsWizard()
 {
     $data = ['name' => $this->randomMachineName(), 'bundle' => $this->testBundle->id(), 'type' => 'Unknown', 'uid' => $this->adminUser->id(), 'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), 'status' => Media::PUBLISHED];
     $media = Media::create($data);
     $media->save();
     // Test the Media wizard.
     $this->drupalPostForm('admin/structure/views/add', ['label' => 'media view', 'id' => 'media_test', 'show[wizard_key]' => 'media', 'page[create]' => 1, 'page[title]' => 'media_test', 'page[path]' => 'media_test'], t('Save and edit'));
     $this->drupalGet('media_test');
     $this->assertText($data['name']);
     user_role_revoke_permissions('anonymous', ['access content']);
     $this->drupalLogout();
     $this->drupalGet('media_test');
     $this->assertResponse(403);
     $this->drupalLogin($this->adminUser);
     // Test the MediaRevision wizard.
     $this->drupalPostForm('admin/structure/views/add', ['label' => 'media revision view', 'id' => 'media_revision', 'show[wizard_key]' => 'media_revision', 'page[create]' => 1, 'page[title]' => 'media_revision', 'page[path]' => 'media_revision'], t('Save and edit'));
     $this->drupalGet('media_revision');
     // Check only for the label of the changed field as we want to only test
     // if the field is present and not its value.
     $this->assertText($data['name']);
     user_role_revoke_permissions('anonymous', ['view revisions']);
     $this->drupalLogout();
     $this->drupalGet('media_revision');
     $this->assertResponse(403);
 }