/**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     new Settings(array('hash_salt' => 'test'));
     // The mocked super user account, with the same roles as Account 2.
     $this->account1 = $this->getMockBuilder('Drupal\\user\\Entity\\User')->disableOriginalConstructor()->setMethods(array('getRoles', 'id'))->getMock();
     $this->account1->expects($this->any())->method('id')->willReturn(1);
     $this->account1->expects($this->never())->method('getRoles');
     // Account 2: 'administrator' and 'authenticated' roles.
     $roles_1 = array('administrator', 'authenticated');
     $this->account2 = $this->getMockBuilder('Drupal\\user\\Entity\\User')->disableOriginalConstructor()->setMethods(array('getRoles', 'id'))->getMock();
     $this->account2->expects($this->any())->method('getRoles')->will($this->returnValue($roles_1));
     $this->account2->expects($this->any())->method('id')->willReturn(2);
     // Account 3: 'authenticated' and 'administrator' roles (different order).
     $roles_3 = array('authenticated', 'administrator');
     $this->account3 = $this->getMockBuilder('Drupal\\user\\Entity\\User')->disableOriginalConstructor()->setMethods(array('getRoles', 'id'))->getMock();
     $this->account3->expects($this->any())->method('getRoles')->will($this->returnValue($roles_3));
     $this->account3->expects($this->any())->method('id')->willReturn(3);
     // Updated account 2: now also 'editor' role.
     $roles_2_updated = array('editor', 'administrator', 'authenticated');
     $this->account2Updated = $this->getMockBuilder('Drupal\\user\\Entity\\User')->disableOriginalConstructor()->setMethods(array('getRoles', 'id'))->getMock();
     $this->account2Updated->expects($this->any())->method('getRoles')->will($this->returnValue($roles_2_updated));
     $this->account2Updated->expects($this->any())->method('id')->willReturn(2);
     // Mocked private key + cache services.
     $random = Crypt::randomBytesBase64(55);
     $this->privateKey = $this->getMockBuilder('Drupal\\Core\\PrivateKey')->disableOriginalConstructor()->setMethods(array('get'))->getMock();
     $this->privateKey->expects($this->any())->method('get')->will($this->returnValue($random));
     $this->cache = $this->getMockBuilder('Drupal\\Core\\Cache\\CacheBackendInterface')->disableOriginalConstructor()->getMock();
     $this->staticCache = $this->getMockBuilder('Drupal\\Core\\Cache\\CacheBackendInterface')->disableOriginalConstructor()->getMock();
     $this->permissionsHash = new PermissionsHashGenerator($this->privateKey, $this->cache, $this->staticCache);
 }
 /**
  * Tests that fields are synchronized using the Subscriber form.
  */
 public function testSubscriberFormFieldSync()
 {
     // Create a subscriber for the user.
     $subscriber = Subscriber::create(array('uid' => $this->user->id(), 'mail' => '*****@*****.**'));
     $subscriber->save();
     // Edit subscriber field and assert user field is changed accordingly.
     $this->drupalLogin($this->user);
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertField('field_shared[0][value]');
     $this->assertRaw($this->user->field_shared->value);
     $new_value = $this->randomMachineName();
     $this->drupalPostForm(NULL, array('field_shared[0][value]' => $new_value), t('Save'));
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertRaw($new_value);
     $this->user = User::load($this->user->id());
     $this->assertEqual($this->user->field_shared->value, $new_value);
     // Unset the sync setting and assert field is not synced.
     $this->drupalPostForm('admin/config/people/simplenews/settings/subscriber', array('simplenews_sync_fields' => FALSE), t('Save configuration'));
     $unsynced_value = $this->randomMachineName();
     $this->drupalPostForm('admin/people/simplenews/edit/' . $subscriber->id(), array('field_shared[0][value]' => $unsynced_value), t('Save'));
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertRaw($unsynced_value);
     $this->user = User::load($this->user->id());
     $this->assertEqual($this->user->field_shared->value, $new_value);
     $this->assertNotEqual($this->user->field_shared->value, $unsynced_value);
 }
 /**
  * Creates an order for the specified user, and redirects to the edit page.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user to create the order for.
  */
 public function createForUser(UserInterface $user)
 {
     $order = Order::create(['uid' => $user->id(), 'order_status' => uc_order_state_default('post_checkout')]);
     $order->save();
     uc_order_comment_save($order->id(), \Drupal::currentUser()->id(), $this->t('Order created by the administration.'), 'admin');
     return $this->redirect('entity.uc_order.edit_form', ['uc_order' => $order->id()]);
 }
 /**
  * Tests tabs in profile UI.
  */
 public function testProfileTabs()
 {
     $types_data = ['profile_type_0' => ['label' => $this->randomMachineName()], 'profile_type_1' => ['label' => $this->randomMachineName()]];
     /** @var ProfileType[] $types */
     $types = [];
     foreach ($types_data as $id => $values) {
         $types[$id] = ProfileType::create(['id' => $id] + $values);
         $types[$id]->save();
     }
     $this->container->get('router.builder')->rebuild();
     $this->user1 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']);
     $this->user1->save();
     $this->user2 = User::create(['name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com']);
     $this->user2->save();
     // Create new profiles.
     $profile1 = Profile::create($expected = ['type' => $types['profile_type_0']->id(), 'uid' => $this->user1->id()]);
     $profile1->save();
     $profile2 = Profile::create($expected = ['type' => $types['profile_type_1']->id(), 'uid' => $this->user2->id()]);
     $profile2->save();
     $this->drupalLogin($this->adminUser);
     $this->drupalGet('admin/config');
     $this->clickLink('User profiles');
     $this->assertResponse(200);
     $this->assertUrl('admin/config/people/profiles');
     $this->assertLink($profile1->label());
     $this->assertLinkByHref($profile2->toUrl('canonical')->toString());
     $tasks = [['entity.profile.collection', []], ['entity.profile_type.collection', []]];
     $this->assertLocalTasks($tasks, 0);
 }
 /**
  * @param array $form
  * @param \Drupal\user\UserInterface $user
  * @return array
  */
 public static function addRoleDelegationElement(array $form, UserInterface $user)
 {
     $current_user = \Drupal::currentUser();
     $roles_current = $user->getRoles(TRUE);
     $roles_delegate = array();
     $roles = user_roles(TRUE);
     unset($roles[AccountInterface::AUTHENTICATED_ROLE]);
     unset($roles['administrator']);
     foreach ($roles as $rid => $role) {
         if ($current_user->hasPermission('assign all roles') || $current_user->hasPermission("assign {$role->get('id')} role")) {
             $roles_delegate[$rid] = isset($form['account']['roles']['#options'][$rid]) ? $form['account']['roles']['#options'][$rid] : $role->get('id');
         }
     }
     if (empty($roles_delegate)) {
         // No role can be assigned.
         return $form;
     }
     if (!isset($form['account'])) {
         $form['account'] = array('#type' => 'value', '#value' => $user);
     }
     $default_options = array();
     foreach ($roles_current as $role) {
         if (in_array($role, $roles_delegate)) {
             $default_options[$role] = $role;
         }
     }
     // Generate the form items.
     $form['account']['roles_change'] = array('#type' => 'checkboxes', '#title' => isset($form['account']['roles']['#title']) ? $form['account']['roles']['#title'] : t('Roles'), '#options' => $roles_delegate, '#default_value' => array_keys(array_intersect_key(array_flip($roles_current), $roles_delegate)), '#description' => isset($form['account']['roles']['#description']) ? $form['account']['roles']['#description'] : t('Change roles assigned to user.'));
     return $form;
 }
Example #6
0
 /**
  * @inheritdoc
  */
 public function save(UserInterface $account, $provider, $authname, $data = NULL)
 {
     if (!is_scalar($data)) {
         $data = serialize($data);
     }
     $this->connection->merge('authmap')->keys(array('uid' => $account->id(), 'provider' => $provider))->fields(array('authname' => $authname, 'data' => $data))->execute();
 }
 /**
  * Tests the node comment statistics.
  */
 function testCommentNodeCommentStatistics()
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     // Set comments to have subject and preview disabled.
     $this->drupalLogin($this->adminUser);
     $this->setCommentPreview(DRUPAL_DISABLED);
     $this->setCommentForm(TRUE);
     $this->setCommentSubject(FALSE);
     $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
     $this->drupalLogout();
     // Checks the initial values of node comment statistics with no comment.
     $node = $node_storage->load($this->node->id());
     $this->assertEqual($node->get('comment')->last_comment_timestamp, $this->node->getCreatedTime(), 'The initial value of node last_comment_timestamp is the node created date.');
     $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The initial value of node last_comment_name is NULL.');
     $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser->id(), 'The initial value of node last_comment_uid is the node uid.');
     $this->assertEqual($node->get('comment')->comment_count, 0, 'The initial value of node comment_count is zero.');
     // Post comment #1 as web_user2.
     $this->drupalLogin($this->webUser2);
     $comment_text = $this->randomMachineName();
     $this->postComment($this->node, $comment_text);
     // Checks the new values of node comment statistics with comment #1.
     // The node cache needs to be reset before reload.
     $node_storage->resetCache(array($this->node->id()));
     $node = $node_storage->load($this->node->id());
     $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is NULL.');
     $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is the comment #1 uid.');
     $this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is 1.');
     // Prepare for anonymous comment submission (comment approval enabled).
     $this->drupalLogin($this->adminUser);
     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => FALSE));
     // Ensure that the poster can leave some contact info.
     $this->setCommentAnonymous('1');
     $this->drupalLogout();
     // Post comment #2 as anonymous (comment approval enabled).
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
     $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', TRUE);
     // Checks the new values of node comment statistics with comment #2 and
     // ensure they haven't changed since the comment has not been moderated.
     // The node needs to be reloaded with the cache reset.
     $node_storage->resetCache(array($this->node->id()));
     $node = $node_storage->load($this->node->id());
     $this->assertEqual($node->get('comment')->last_comment_name, NULL, 'The value of node last_comment_name is still NULL.');
     $this->assertEqual($node->get('comment')->last_comment_uid, $this->webUser2->id(), 'The value of node last_comment_uid is still the comment #1 uid.');
     $this->assertEqual($node->get('comment')->comment_count, 1, 'The value of node comment_count is still 1.');
     // Prepare for anonymous comment submission (no approval required).
     $this->drupalLogin($this->adminUser);
     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access comments' => TRUE, 'post comments' => TRUE, 'skip comment approval' => TRUE));
     $this->drupalLogout();
     // Post comment #3 as anonymous.
     $this->drupalGet('comment/reply/node/' . $this->node->id() . '/comment');
     $anonymous_comment = $this->postComment($this->node, $this->randomMachineName(), '', array('name' => $this->randomMachineName()));
     $comment_loaded = Comment::load($anonymous_comment->id());
     // Checks the new values of node comment statistics with comment #3.
     // The node needs to be reloaded with the cache reset.
     $node_storage->resetCache(array($this->node->id()));
     $node = $node_storage->load($this->node->id());
     $this->assertEqual($node->get('comment')->last_comment_name, $comment_loaded->getAuthorName(), 'The value of node last_comment_name is the name of the anonymous user.');
     $this->assertEqual($node->get('comment')->last_comment_uid, 0, 'The value of node last_comment_uid is zero.');
     $this->assertEqual($node->get('comment')->comment_count, 2, 'The value of node comment_count is 2.');
 }
 /**
  * Test the Who's Online block.
  */
 function testWhosOnlineBlock()
 {
     $block = $this->drupalPlaceBlock('views_block:who_s_online-who_s_online_block');
     // Generate users.
     $user1 = $this->drupalCreateUser(array('access user profiles'));
     $user2 = $this->drupalCreateUser(array());
     $user3 = $this->drupalCreateUser(array());
     // Update access of two users to be within the active timespan.
     $this->updateAccess($user1->id());
     $this->updateAccess($user2->id(), REQUEST_TIME + 1);
     // Insert an inactive user who should not be seen in the block, and ensure
     // that the admin user used in setUp() does not appear.
     $inactive_time = REQUEST_TIME - 15 * 60 - 1;
     $this->updateAccess($user3->id(), $inactive_time);
     $this->updateAccess($this->adminUser->id(), $inactive_time);
     // Test block output.
     \Drupal::currentUser()->setAccount($user1);
     $content = entity_view($block, 'block');
     $this->drupalSetContent(render($content));
     $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).');
     $this->assertText($user1->getUsername(), 'Active user 1 found in online list.');
     $this->assertText($user2->getUsername(), 'Active user 2 found in online list.');
     $this->assertNoText($user3->getUsername(), 'Inactive user not found in online list.');
     $this->assertTrue(strpos($this->drupalGetContent(), $user1->getUsername()) > strpos($this->drupalGetContent(), $user2->getUsername()), 'Online users are ordered correctly.');
 }
Example #9
0
 /**
  * Test the username formatter.
  */
 public function testUsername()
 {
     $view_id = $this->randomMachineName();
     $view = View::create(['id' => $view_id, 'base_table' => 'comment_field_data', 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => ['name' => ['table' => 'comment_field_data', 'field' => 'name', 'id' => 'name', 'plugin_id' => 'field', 'type' => 'comment_username'], 'subject' => ['table' => 'comment_field_data', 'field' => 'subject', 'id' => 'subject', 'plugin_id' => 'field', 'type' => 'string', 'settings' => ['link_to_entity' => TRUE]]]]]]]);
     $view->save();
     /* @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
     $account_switcher = \Drupal::service('account_switcher');
     /* @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     $account_switcher->switchTo($this->adminUser);
     $executable = Views::getView($view_id);
     $build = $executable->preview();
     $this->setRawContent($renderer->renderRoot($build));
     $this->verbose($this->getRawContent());
     $this->assertLink('My comment title');
     $this->assertLink('Anonymous comment title');
     $this->assertLink($this->adminUser->label());
     $this->assertLink('barry (not verified)');
     $account_switcher->switchTo(new AnonymousUserSession());
     $executable = Views::getView($view_id);
     $executable->storage->invalidateCaches();
     $build = $executable->preview();
     $this->setRawContent($renderer->renderRoot($build));
     // No access to user-profiles, so shouldn't be able to see links.
     $this->assertNoLink($this->adminUser->label());
     // Note: External users aren't pointing to drupal user profiles.
     $this->assertLink('barry (not verified)');
     $this->verbose($this->getRawContent());
     $this->assertLink('My comment title');
     $this->assertLink('Anonymous comment title');
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installSchema('system', 'sequences');
     $this->installEntitySchema('user');
     $this->manager = $this->container->get('plugin.manager.condition');
     // Set up the authenticated and anonymous roles.
     Role::create(array('id' => RoleInterface::ANONYMOUS_ID, 'label' => 'Anonymous user'))->save();
     Role::create(array('id' => RoleInterface::AUTHENTICATED_ID, 'label' => 'Authenticated user'))->save();
     // Create new role.
     $rid = strtolower($this->randomMachineName(8));
     $label = $this->randomString(8);
     $role = Role::create(array('id' => $rid, 'label' => $label));
     $role->save();
     $this->role = $role;
     // Setup an anonymous user for our tests.
     $this->anonymous = User::create(array('name' => '', 'uid' => 0));
     $this->anonymous->save();
     // Loading the anonymous user adds the correct role.
     $this->anonymous = User::load($this->anonymous->id());
     // Setup an authenticated user for our tests.
     $this->authenticated = User::create(array('name' => $this->randomMachineName()));
     $this->authenticated->save();
     // Add the custom role.
     $this->authenticated->addRole($this->role->id());
 }
 /**
  * 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');
 }
Example #12
0
  public function userProfileForm(RouteMatchInterface $route_match, UserInterface $user, ProfileTypeInterface $profile_type) {
    $profile = $this->entityManager()->getStorage('profile')->create([
      'uid' => $user->id(),
      'type' => $profile_type->id(),
    ]);

    return $this->entityFormBuilder()->getForm($profile, 'add', ['uid' => $user->id(), 'created' => REQUEST_TIME]);
  }
 /**
  * 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');
 }
 /**
  * {@inheritdoc}
  */
 public function setAuthor(UserInterface $account)
 {
     if ($this->translation->hasField('content_translation_uid')) {
         $this->translation->set('content_translation_uid', $account->id());
     } else {
         $this->translation->setOwner($account);
     }
     return $this;
 }
Example #15
0
 /**
  * Unblock a user.
  *
  * @param \Drupal\user\UserInterface $user
  *   The user to unblock.
  */
 protected function doExecute(UserInterface $user)
 {
     // Do nothing if user is anonymous or isn't blocked.
     if ($user->isAuthenticated() && $user->isBlocked()) {
         $user->activate();
         // Set flag that indicates if the entity should be auto-saved later.
         $this->saveLater = TRUE;
     }
 }
Example #16
0
 public function flickr_photos_access(\Drupal\user\UserInterface $user, Drupal\Core\Session\AccountInterface $account)
 {
     $view_access = FALSE;
     if (!empty($user) && $user->id()) {
         if (isset($user->flickr['nsid'])) {
             $view_access = \Drupal::currentUser()->hasPermission('administer flickr') || $user->status && (\Drupal::currentUser()->hasPermission('view all flickr photos') || \Drupal::currentUser()->hasPermission('view own flickr photos') && \Drupal::currentUser()->uid == $user->id());
         }
     }
     return $view_access;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installSchema('system', 'sequences');
     $devel_role = Role::create(['id' => 'admin', 'permissions' => ['access devel information']]);
     $devel_role->save();
     $this->develUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$devel_role->id()]]);
     $this->develUser->save();
 }
Example #18
0
  public function testUserEntityClone() {
    $this->drupalPostForm('entity_clone/user/' . $this->adminUser->id(), [], t('Clone'));

    $users = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
        'name' => 'test_user_cloned',
      ]);
    $user = reset($users);
    $this->assertTrue($user, 'Test user cloned found in database.');
  }
 /**
  * Tests customer overview.
  */
 public function testCustomerAdminPages()
 {
     $this->drupalLogin($this->adminUser);
     $country = Country::load('US');
     Order::create(array('uid' => $this->customer->id(), 'billing_country' => $country->id(), 'billing_zone' => 'AK'))->save();
     $this->drupalGet('admin/store/customers/view');
     $this->assertResponse(200);
     $this->assertLinkByHref('user/' . $this->customer->id());
     $this->assertText($country->getZones()['AK']);
     $this->assertText($country->label());
 }
Example #20
0
 protected function setUp()
 {
     parent::setUp();
     // Create Basic page node type.
     if ($this->profile != 'standard') {
         $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
     }
     $this->privilegedUser = $this->drupalCreateUser(array('administer statistics', 'view post access counter', 'create page content'));
     $this->drupalLogin($this->privilegedUser);
     $this->testNode = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privilegedUser->id()));
     $this->client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]);
 }
Example #21
0
/**
 * Control access to masquerade as a certain target user.
 *
 * Modules may implement this hook to control whether a user is allowed to
 * masquerade as a certain target user account.
 *
 * @param \Drupal\user\UserInterface $user
 *   The currently logged-in user.
 * @param \Drupal\user\UserInterface $target_account
 *   The target user account to check for masquerade access.
 *
 * @return bool
 *   Either a Boolean or NULL:
 *   - FALSE to explicitly deny access. If a module denies access, no other
 *     module is able to grant access and access is denied.
 *   - TRUE to grant access. Access is only granted if at least one module
 *     grants access and no module denies access.
 *   - NULL or nothing to not affect the operation. If no module explicitly
 *     grants access, access is denied.
 */
function hook_masquerade_access(\Drupal\user\UserInterface $user, \Drupal\user\UserInterface $target_account)
{
    // Explicitly deny access for uid 1.
    if ($target_account->id() == 1) {
        return FALSE;
    }
    // Example: If the target username is 'demo', always grant access for everone.
    if ($target_account->label() == 'demo') {
        return TRUE;
    }
    // In other cases do not alter access.
}
Example #22
0
 protected function setUp()
 {
     parent::setUp();
     $this->enableViewsTestModule();
     ViewTestData::createTestViews(get_class($this), array('views_test_data'));
     $this->webUser = $this->drupalCreateUser();
     $normal_role = $this->drupalCreateRole(array());
     $this->normalUser = $this->drupalCreateUser(array('views_test_data test permission'));
     $this->normalUser->addRole($normal_role);
     // @todo when all the plugin information is cached make a reset function and
     // call it here.
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp($import_test_views = TRUE)
 {
     parent::setUp($import_test_views);
     $this->installEntitySchema('user');
     $role_with_access = Role::create(['id' => 'with_access', 'permissions' => ['view test entity field']]);
     $role_with_access->save();
     $role_without_access = Role::create(['id' => 'without_access', 'permissions' => []]);
     $role_without_access->save();
     $this->userWithAccess = User::create(['name' => $this->randomMachineName(), 'roles' => [$role_with_access->id()]]);
     $this->userWithAccess->save();
     $this->userWithoutAccess = User::create(['name' => $this->randomMachineName(), 'roles' => [$role_without_access->id()]]);
     $this->userWithoutAccess->save();
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->installEntitySchema('user');
     $this->installSchema('file', array('file_usage'));
     $this->installSchema('system', 'sequences');
     $this->user1 = User::create(['name' => 'user1', 'status' => 1]);
     $this->user1->save();
     $this->user2 = User::create(['name' => 'user2', 'status' => 1]);
     $this->user2->save();
     $this->file = File::create(array('uid' => $this->user1->id(), 'filename' => 'druplicon.txt', 'filemime' => 'text/plain'));
 }
 /**
  * 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.');
 }
Example #26
0
 /**
  * Evaluate if user has role(s).
  *
  * @param \Drupal\user\UserInterface $account
  *   The account to check.
  * @param \Drupal\user\RoleInterface[] $roles
  *   Array of user roles.
  * @param string $operation
  *   Either "AND": user has all of roles.
  *   Or "OR": user has at least one of all roles.
  *   Defaults to "AND".
  *
  * @return bool
  *   TRUE if the user has the role(s).
  */
 protected function doEvaluate(UserInterface $account, array $roles, $operation = 'AND')
 {
     $rids = array_map(function ($role) {
         return $role->id();
     }, $roles);
     switch ($operation) {
         case 'OR':
             return (bool) array_intersect($rids, $account->getRoles());
         case 'AND':
             return (bool) (!array_diff($rids, $account->getRoles()));
         default:
             throw new \InvalidArgumentException('Either use "AND" or "OR". Leave empty for default "AND" behavior.');
     }
 }
Example #27
0
 /**
  * Remove role from a user.
  *
  * @param \Drupal\user\UserInterface $account
  *   User object the roles should be removed from.
  * @param \Drupal\user\RoleInterface[] $roles
  *   Array of user roles.
  */
 protected function doExecute(UserInterface $account, array $roles)
 {
     foreach ($roles as $role) {
         // Check if user has role.
         if ($account->hasRole($role->id())) {
             // If you try to add anonymous or authenticated role to user, Drupal
             // will throw an \InvalidArgumentException. Anonymous or authenticated
             // role ID must not be assigned manually.
             $account->removeRole($role->id());
             // Set flag that indicates if the entity should be auto-saved later.
             $this->saveLater = TRUE;
         }
     }
 }
Example #28
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->drupalPlaceBlock('system_breadcrumb_block');
     $this->enableViewsTestModule();
     $this->webUser = $this->drupalCreateUser();
     $roles = $this->webUser->getRoles();
     $this->webRole = $roles[0];
     $this->normalRole = $this->drupalCreateRole(array());
     $this->normalUser = $this->drupalCreateUser(array('views_test_data test permission'));
     $this->normalUser->addRole($this->normalRole);
     $this->normalUser->save();
     // @todo when all the plugin information is cached make a reset function and
     // call it here.
 }
 /**
  * Tests loading default from storage handler.
  */
 public function testLoadDefaultProfile()
 {
     $profile_type = $this->createProfileType('test_defaults', 'test_defaults');
     // Create new profiles.
     $profile1 = Profile::create($expected = ['type' => $profile_type->id(), 'uid' => $this->user1->id()]);
     $profile1->setActive(TRUE);
     $profile1->save();
     $profile2 = Profile::create($expected = ['type' => $profile_type->id(), 'uid' => $this->user1->id()]);
     $profile2->setActive(TRUE);
     $profile2->setDefault(TRUE);
     $profile2->save();
     /** @var \Drupal\profile\ProfileStorageInterface $storage */
     $storage = \Drupal::entityTypeManager()->getStorage('profile');
     $default_profile = $storage->loadDefaultByUser($this->user1, $profile_type->id());
     $this->assertEqual($profile2->id(), $default_profile->id());
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $account = $this->currentUser();
     $account_is_user = $this->user->id() == $account->id();
     if ($form_state->getValue('set') == 'new') {
         // Save a new shortcut set with links copied from the user's default set.
         /* @var \Drupal\shortcut\Entity\ShortcutSet $set */
         $set = $this->shortcutSetStorage->create(array('id' => $form_state->getValue('id'), 'label' => $form_state->getValue('label')));
         $set->save();
         $replacements = array('%user' => $this->user->label(), '%set_name' => $set->label(), ':switch-url' => $this->url('<current>'));
         if ($account_is_user) {
             // Only administrators can create new shortcut sets, so we know they have
             // access to switch back.
             drupal_set_message($this->t('You are now using the new %set_name shortcut set. You can edit it from this page or <a href=":switch-url">switch back to a different one.</a>', $replacements));
         } else {
             drupal_set_message($this->t('%user is now using a new shortcut set called %set_name. You can edit it from this page.', $replacements));
         }
         $form_state->setRedirect('entity.shortcut_set.customize_form', array('shortcut_set' => $set->id()));
     } else {
         // Switch to a different shortcut set.
         /* @var \Drupal\shortcut\Entity\ShortcutSet $set */
         $set = $this->shortcutSetStorage->load($form_state->getValue('set'));
         $replacements = array('%user' => $this->user->getDisplayName(), '%set_name' => $set->label());
         drupal_set_message($account_is_user ? $this->t('You are now using the %set_name shortcut set.', $replacements) : $this->t('%user is now using the %set_name shortcut set.', $replacements));
     }
     // Assign the shortcut set to the provided user account.
     $this->shortcutSetStorage->assignUser($set, $this->user);
 }