/**
  * {@inheritdoc}
  *
  * When the $operation is 'add' then the $entity is of type 'profile_type',
  * otherwise $entity is of type 'profile'.
  */
 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account)
 {
     $account = $this->prepareUser($account);
     $user_page = \Drupal::request()->attributes->get('user');
     // Some times, operation edit is called update.
     // Use edit in any case.
     if ($operation == 'update') {
         $operation = 'edit';
     }
     // Check that if profile type has require roles, the user the profile is
     // being added to has any of the required roles.
     if ($entity->getEntityTypeId() == 'profile') {
         $profile_roles = ProfileType::load($entity->bundle())->getRoles();
         $user_roles = $entity->getOwner()->getRoles(TRUE);
         if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
             return AccessResult::forbidden();
         }
     } elseif ($entity->getEntityTypeId() == 'profile_type') {
         $profile_roles = $entity->getRoles();
         $user_roles = User::load($user_page->id())->getRoles(TRUE);
         if (!empty(array_filter($profile_roles)) && !array_intersect($user_roles, $profile_roles)) {
             return AccessResult::forbidden();
         }
     }
     if ($account->hasPermission('bypass profile access')) {
         return AccessResult::allowed()->cachePerPermissions();
     } elseif ($operation == 'add' && ($user_page->id() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->id() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->id() . ' profile')) || $operation != 'add' && ($entity->getOwnerId() == $account->id() && $account->hasPermission($operation . ' own ' . $entity->getType() . ' profile') || $account->hasPermission($operation . ' any ' . $entity->getType() . ' profile'))) {
         return AccessResult::allowed()->cachePerPermissions();
     } else {
         return AccessResult::forbidden()->cachePerPermissions();
     }
 }
 public function content()
 {
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $userId = $user->get('uid')->value;
     $data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => ''));
     $appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll();
     if ($appliedJobs) {
         $x = 0;
         foreach ($appliedJobs as $appliedJob) {
             $jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id);
             $jobTitle = $jobNode->getTitle();
             $jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id);
             $companyNodeEntity = $jobNode->get('field_company');
             $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
             $companyName = $companyNode->getTitle();
             $data[$x]['job_title'] = $jobTitle;
             $data[$x]['job_path'] = $jobPathAlias;
             $data[$x]['company_name'] = $companyName;
             $data[$x]['application_date'] = $appliedJob->date;
             $x++;
         }
     }
     $markUp = $this->createMarkUp($data);
     return array('#type' => 'markup', '#markup' => $markUp);
 }
示例#3
0
 /**
  * {@inheritdoc}
  */
 public function create(array $values = array())
 {
     $store_config = \Drupal::config('uc_store.settings');
     // Set the primary email address.
     if (empty($values['primary_email']) && !empty($values['uid'])) {
         if ($account = User::load($values['uid'])) {
             $values['primary_email'] = $account->mail;
         }
     }
     // Set the default order status.
     if (empty($values['order_status'])) {
         $values['order_status'] = uc_order_state_default('in_checkout');
     }
     // Set the default currency.
     if (empty($values['currency'])) {
         $values['currency'] = $store_config->get('currency.code');
     }
     // Set the default country codes.
     if (empty($values['billing_country'])) {
         $values['billing_country'] = $store_config->get('address.country');
     }
     if (empty($values['delivery_country'])) {
         $values['delivery_country'] = $store_config->get('address.country');
     }
     // Set the created time to now.
     if (empty($values['created'])) {
         $values['created'] = REQUEST_TIME;
     }
     return parent::create($values);
 }
 /**
  * Tests exportContentWithReferences().
  */
 public function testExportWithReferences()
 {
     \Drupal::service('module_installer')->install(['node', 'default_content']);
     \Drupal::service('router.builder')->rebuild();
     $this->defaultContentManager = \Drupal::service('default_content.manager');
     $user = User::create(['name' => 'my username']);
     $user->save();
     // Reload the user to get the proper casted values from the DB.
     $user = User::load($user->id());
     $node_type = NodeType::create(['type' => 'test']);
     $node_type->save();
     $node = Node::create(['type' => $node_type->id(), 'title' => 'test node', 'uid' => $user->id()]);
     $node->save();
     // Reload the node to get the proper casted values from the DB.
     $node = Node::load($node->id());
     /** @var \Symfony\Component\Serializer\Serializer $serializer */
     $serializer = \Drupal::service('serializer');
     \Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN);
     $expected_node = $serializer->serialize($node, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $expected_user = $serializer->serialize($user, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $exported_by_entity_type = $this->defaultContentManager->exportContentWithReferences('node', $node->id());
     // Ensure that the node type is not tryed to be exported.
     $this->assertEqual(array_keys($exported_by_entity_type), ['node', 'user']);
     // Ensure the right UUIDs are exported.
     $this->assertEqual([$node->uuid()], array_keys($exported_by_entity_type['node']));
     $this->assertEqual([$user->uuid()], array_keys($exported_by_entity_type['user']));
     // Compare the actual serialized data.
     $this->assertEqual(reset($exported_by_entity_type['node']), $expected_node);
     $this->assertEqual(reset($exported_by_entity_type['user']), $expected_user);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     //TODO v2 Send Email via Cron not on Submit
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $username = $user->get('name')->value;
     $userId = $user->get('uid')->value;
     $mailManager = \Drupal::service('plugin.manager.mail');
     $jobNode = \Drupal::routeMatch()->getParameter('node');
     $jobNodeTitle = $jobNode->getTitle();
     $companyNodeEntity = $jobNode->get('field_company');
     $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
     $companyEmail = $companyNode->field_email->value;
     $resumeFileId = $form_state->getValue('resume');
     $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
     $atttachment = array('filepath' => $resumeFile);
     $module = 'job_mailer';
     $key = 'apply_job';
     $params['job_title'] = $jobNodeTitle;
     $params['message'] = "<html>\n           <p>Please see attached resume for user: {$username}\n           </html>";
     $params['attachment'] = $atttachment;
     $langcode = \Drupal::currentUser()->getPreferredLangcode();
     $send = true;
     $reply = \Drupal::config('system.site')->get('mail');
     $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
     db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
     drupal_set_message('Your application has been sent.');
 }
 /**
  * Sets the test up.
  */
 protected function setUp()
 {
     parent::setUp();
     /** @var UserInterface $user */
     $user = User::load(1);
     // Create initial block.
     $block = $this->createBlockContent('initial');
     $blocks = array();
     $logs = array();
     // Get original block.
     $blocks[] = $block->getRevisionId();
     $logs[] = '';
     // Create three revisions.
     $revision_count = 3;
     for ($i = 0; $i < $revision_count; $i++) {
         $block->setNewRevision(TRUE);
         $block->setRevisionLogMessage($this->randomMachineName(32));
         $block->setRevisionUser($this->adminUser);
         $block->setRevisionCreationTime(REQUEST_TIME);
         $logs[] = $block->getRevisionLogMessage();
         $block->save();
         $blocks[] = $block->getRevisionId();
     }
     $this->blocks = $blocks;
     $this->revisionLogs = $logs;
 }
 public static function deleteAllUsers($roles = NULL)
 {
     $count = 0;
     $db_connection = Database::getConnection();
     if (!$roles) {
         $result = $db_connection->query('SELECT uid FROM {users} WHERE uid > 1')->fetchAllAssoc('uid');
         foreach ($result as $data) {
             $user = User::load($data->uid);
             $user->delete();
             $count++;
         }
         // Delete the URL aliases
         $db_connection->query("DELETE FROM {url_alias} WHERE source LIKE 'user/%%'");
     } else {
         if (is_array($roles)) {
             $result = array();
             foreach ($roles as $role) {
                 $result = array_merge($result, db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $role, '=')->execute()->fetchCol('entity_id'));
             }
         } else {
             $result = db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $roles, '=')->execute()->fetchCol('entity_id');
         }
         foreach ($result as $data) {
             $user = User::load($data);
             $user->delete();
             $count++;
         }
         // @TODO Delete individual aliases
     }
     return $count;
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user');
     $user = User::load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
         return 1;
     }
     $password = $input->getArgument('password');
     if (!$password) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
         return 1;
     }
     try {
         $user->setPassword($password);
         $user->save();
         $schema = $this->database->schema();
         $flood = $schema->findTables('flood');
         if ($flood) {
             $this - $this->chainQueue->addCommand('user:login:clear:attempts', ['uid' => $uid]);
         }
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return 1;
     }
     $io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
 }
 /**
  * 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);
 }
示例#10
0
 /**
  * Tests contact link.
  */
 public function testContactLink()
 {
     $accounts = array();
     $accounts['root'] = User::load(1);
     // Create an account with access to all contact pages.
     $admin_account = $this->drupalCreateUser(array('administer users'));
     $accounts['admin'] = $admin_account;
     // Create an account with no access to contact pages.
     $no_contact_account = $this->drupalCreateUser();
     $accounts['no_contact'] = $no_contact_account;
     // Create an account with access to contact pages.
     $contact_account = $this->drupalCreateUser(array('access user contact forms'));
     $accounts['contact'] = $contact_account;
     $this->drupalLogin($admin_account);
     $this->drupalGet('test-contact-link');
     // The admin user has access to all contact links beside his own.
     $this->assertContactLinks($accounts, array('root', 'no_contact', 'contact'));
     $this->drupalLogin($no_contact_account);
     $this->drupalGet('test-contact-link');
     // Ensure that the user without the permission doesn't see any link.
     $this->assertContactLinks($accounts, array());
     $this->drupalLogin($contact_account);
     $this->drupalGet('test-contact-link');
     $this->assertContactLinks($accounts, array('root', 'admin', 'no_contact'));
     // Disable contact link for no_contact.
     $this->userData->set('contact', $no_contact_account->id(), 'enabled', FALSE);
     // @todo Remove cache invalidation in https://www.drupal.org/node/2477903.
     Cache::invalidateTags($no_contact_account->getCacheTagsToInvalidate());
     $this->drupalGet('test-contact-link');
     $this->assertContactLinks($accounts, array('root', 'admin'));
 }
示例#11
0
 function _insertPurchasedProduct($data)
 {
     $product_id = $data['id'];
     $quantity = $data['quantity'];
     $price = $data['price'];
     $customer_id = $data['customer_id'];
     $note = $data['body'];
     $status_id = $data['status_id'];
     $total_price = $price * $quantity;
     $user_storage = \Drupal::entityManager()->getStorage('user');
     $customer = \Drupal\user\Entity\User::load($customer_id);
     // update user
     if ($status_id != 3) {
         if (!isset($customer->field_total_money->value)) {
             $customer->field_total_money->value = $total_price;
         } else {
             $customer->field_total_money->value += $total_price;
         }
         $customer->field_debt->value = $customer->field_total_money->value - $customer->field_payment_money->value;
         $customer->field_last_purchased_date->value = format_date(REQUEST_TIME, 'custom', 'Y-m-d\\TH:i:s');
         $user_storage->save($customer);
     }
     // insert new row
     $fields = array('product_id' => $product_id, 'user_id' => $customer_id, 'quantity' => $quantity, 'price' => $price, 'total_price' => $total_price, 'status' => $status_id, 'note' => $note, 'date' => REQUEST_TIME);
     db_insert('product_user_relationship')->fields($fields)->execute();
 }
示例#12
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());
 }
示例#13
0
 public function testUserHooks()
 {
     FieldStorageConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user'))->save();
     FieldConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user', 'bundle' => 'user'))->save();
     $this->assertIdentical('', \Drupal::config('name.settings')->get('user_preferred'));
     FieldStorageConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user'))->save();
     FieldStorageConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user'))->save();
     $field = FieldConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field->save();
     $field2 = FieldConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field2->save();
     $this->assertEqual($field->getName(), \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field2->getName())->save();
     $field2->delete();
     $this->assertEqual('', \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field->getName())->save();
     $account = User::create(array('name' => 'test'));
     $account->field_name_test[0] = array('given' => 'Max', 'family' => 'Mustermann');
     $account->save();
     $account = User::load($account->id());
     $this->assertEqual('Max Mustermann', $account->realname);
     $this->assertEqual('Max Mustermann', user_format_name($account));
     $this->assertEqual('test', $account->getUsername());
     $this->assertEqual('Max Mustermann', $account->getDisplayName());
 }
示例#14
0
 /**
  * Tests removal of role references on role entity delete.
  *
  * @see user_user_role_delete()
  */
 public function testRoleDeleteUserRoleReferenceDelete()
 {
     // Create two test roles.
     $role_storage = $this->container->get('entity.manager')->getStorage('user_role');
     $role_storage->create(array('id' => 'test_role_one'))->save();
     $role_storage->create(array('id' => 'test_role_two'))->save();
     // Create user and assign both test roles.
     $values = array('uid' => 1, 'name' => $this->randomString(), 'roles' => array('test_role_one', 'test_role_two'));
     $user = User::create($values);
     $user->save();
     // Check that user has both roles.
     $this->assertTrue($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     // Delete test role one.
     $test_role_one = $role_storage->load('test_role_one');
     $test_role_one->delete();
     // Load user again from the database.
     $user = User::load($user->id());
     // Check that user does not have role one anymore, still has role two.
     $this->assertFalse($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
     // Create new role with same name.
     $role_storage->create(array('id' => 'test_role_one'))->save();
     // Load user again from the database.
     $user = User::load($user->id());
     // Check that user does not have role one.
     $this->assertFalse($user->hasRole('test_role_one'));
     $this->assertTrue($user->hasRole('test_role_two'));
 }
    /**
     * Tests Drupal 6 profile values to Drupal 8 migration.
     */
    public function testUserProfileValues()
    {
        $user = User::load(2);
        $this->assertFalse(is_null($user));
        $this->assertIdentical('red', $user->profile_color->value);
        $expected = <<<EOT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nulla sapien, congue nec risus ut, adipiscing aliquet felis. Maecenas quis justo vel nulla varius euismod. Quisque metus metus, cursus sit amet sem non, bibendum vehicula elit. Cras dui nisl, eleifend at iaculis vitae, lacinia ut felis. Nullam aliquam ligula volutpat nulla consectetur accumsan. Maecenas tincidunt molestie diam, a accumsan enim fringilla sit amet. Morbi a tincidunt tellus. Donec imperdiet scelerisque porta. Sed quis sem bibendum eros congue sodales. Vivamus vel fermentum est, at rutrum orci. Nunc consectetur purus ut dolor pulvinar, ut volutpat felis congue. Cras tincidunt odio sed neque sollicitudin, vehicula tempor metus scelerisque.
EOT;
        $this->assertIdentical($expected, $user->profile_biography->value);
        $this->assertIdentical('1', $user->profile_sell_address->value);
        $this->assertIdentical('Back\\slash', $user->profile_sold_to->value);
        $this->assertIdentical('AC/DC', $user->profile_bands[0]->value);
        $this->assertIdentical('Eagles', $user->profile_bands[1]->value);
        $this->assertIdentical('Elton John', $user->profile_bands[2]->value);
        $this->assertIdentical('Lemonheads', $user->profile_bands[3]->value);
        $this->assertIdentical('Rolling Stones', $user->profile_bands[4]->value);
        $this->assertIdentical('Queen', $user->profile_bands[5]->value);
        $this->assertIdentical('The White Stripes', $user->profile_bands[6]->value);
        $this->assertIdentical('1974-06-02', $user->profile_birthdate->value);
        $this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
        $this->assertNull($user->profile_blog->title);
        $this->assertIdentical([], $user->profile_blog->options);
        $this->assertIdentical('http://example.com/blog', $user->profile_blog->uri);
        $this->assertNull($user->profile_love_migrations->value);
        $user = User::load(8);
        $this->assertIdentical('Forward/slash', $user->profile_sold_to->value);
        $user = User::load(15);
        $this->assertIdentical('Dot.in.the.middle', $user->profile_sold_to->value);
    }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user');
     $user = User::load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
         return;
     }
     $password = $input->getArgument('password');
     if (!$password) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
         return;
     }
     try {
         $user->setPassword($password);
         $user->save();
         // Clear all failed login attempts after setup new password to user account.
         $this->getChain()->addCommand('user:login:clear:attempts', ['uid' => $uid]);
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return;
     }
     $io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('uid');
     $account = User::load($uid);
     if (!$account) {
         // Error loading User entity.
         $io->error(sprintf($this->trans('commands.user.login.clear.attempts.errors.invalid-user'), $uid));
         return 1;
     }
     // Define event name and identifier.
     $event = 'user.failed_login_user';
     // Identifier is created by uid and IP address,
     // Then we defined a generic identifier.
     $identifier = "{$account->id()}-";
     // Retrieve current database connection.
     $database = $this->getDrupalService('database');
     $schema = $database->schema();
     $flood = $schema->findTables('flood');
     if (!$flood) {
         $io->error($this->trans('commands.user.login.clear.attempts.errors.no-flood'));
         return 1;
     }
     // Clear login attempts.
     $database->delete('flood')->condition('event', $event)->condition('identifier', $database->escapeLike($identifier) . '%', 'LIKE')->execute();
     // Command executed successful.
     $io->success(sprintf($this->trans('commands.user.login.clear.attempts.messages.successful'), $uid));
 }
 /**
  * A route returning a CacheableResponse object.
  *
  * @return \Drupal\Core\Cache\CacheableResponseInterface
  *   A CacheableResponseInterface object.
  */
 public function cacheableResponse()
 {
     $user = User::load(1);
     $response = new CacheableResponse($user->label());
     $response->addCacheableDependency($user);
     return $response;
 }
 /**
  * Test the shortcut set migration.
  */
 public function testShortcutSetUsersMigration() {
   // Check if migrated user has correct migrated shortcut set assigned.
   $account = User::load(2);
   $shortcut_set = shortcut_current_displayed_set($account);
   /** @var \Drupal\shortcut\ShortcutSetInterface $shortcut_set */
   $this->assertIdentical('shortcut_set_2', $shortcut_set->id());
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!($account = User::load($form_state->getValue('userid')))) {
         $form_state->setErrorByName('userid', $this->t('Username not found'));
     } else {
         $form_state->setValue('username', $account->getAccountName());
     }
 }
 /**
  * Executes all steps of migrations upgrade.
  */
 protected function testMigrateUpgrade()
 {
     parent::testMigrateUpgrade();
     // Ensure migrated users can log in.
     $user = User::load(2);
     $user->pass_raw = 'a password';
     $this->drupalLogin($user);
 }
示例#22
0
 protected function setUp()
 {
     parent::setUp();
     ViewTestData::createTestViews(get_class($this), array('user_test_views'));
     $this->users[] = $this->drupalCreateUser();
     $this->users[] = User::load(1);
     $this->nodes[] = $this->drupalCreateNode(array('uid' => $this->users[0]->id()));
     $this->nodes[] = $this->drupalCreateNode(array('uid' => 1));
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $config = $this->getConfiguration();
     $hello_text = isset($config['hello_text']) ? $config['hello_text'] : '';
     // Load the current user.
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $name = $user->get('name')->value;
     return array('#markup' => $hello_text . ' ' . $name);
 }
示例#24
0
 /**
  * Tests the listing.
  */
 public function testUserListing()
 {
     $this->drupalGet('admin/people');
     $this->assertResponse(403, 'Anonymous user does not have access to the user admin listing.');
     // Create a bunch of users.
     $accounts = array();
     for ($i = 0; $i < 3; $i++) {
         $account = $this->drupalCreateUser();
         $accounts[$account->label()] = $account;
     }
     // Create a blocked user.
     $account = $this->drupalCreateUser();
     $account->block();
     $account->save();
     $accounts[$account->label()] = $account;
     // Create a user at a certain timestamp.
     $account = $this->drupalCreateUser();
     $account->created = 1363219200;
     $account->save();
     $accounts[$account->label()] = $account;
     $timestamp_user = $account->label();
     $rid_1 = $this->drupalCreateRole(array(), 'custom_role_1', 'custom_role_1');
     $rid_2 = $this->drupalCreateRole(array(), 'custom_role_2', 'custom_role_2');
     $account = $this->drupalCreateUser();
     $account->addRole($rid_1);
     $account->addRole($rid_2);
     $account->save();
     $accounts[$account->label()] = $account;
     $role_account_name = $account->label();
     // Create an admin user and look at the listing.
     $admin_user = $this->drupalCreateUser(array('administer users'));
     $accounts[$admin_user->label()] = $admin_user;
     $accounts['admin'] = User::load(1);
     $this->drupalLogin($admin_user);
     $this->drupalGet('admin/people');
     $this->assertResponse(200, 'The admin user has access to the user admin listing.');
     $result = $this->xpath('//table[contains(@class, "responsive-enabled")]/tbody/tr');
     $result_accounts = array();
     foreach ($result as $account) {
         $name = (string) $account->td[0]->span;
         $roles = array();
         if (isset($account->td[2]->div->ul)) {
             foreach ($account->td[2]->div->ul->li as $element) {
                 $roles[] = (string) $element;
             }
         }
         $result_accounts[$name] = array('name' => $name, 'status' => (string) $account->td[1], 'roles' => $roles, 'member_for' => (string) $account->td[3], 'last_access' => (string) $account->td[4]);
     }
     $this->assertFalse(array_keys(array_diff_key($result_accounts, $accounts)), 'Ensure all accounts are listed.');
     foreach ($result_accounts as $name => $values) {
         $this->assertEqual($values['status'] == t('active'), $accounts[$name]->status->value, 'Ensure the status is displayed properly.');
     }
     $expected_roles = array('custom_role_1', 'custom_role_2');
     $this->assertEqual($result_accounts[$role_account_name]['roles'], $expected_roles, 'Ensure roles are listed properly.');
     $this->assertEqual($result_accounts[$timestamp_user]['member_for'], \Drupal::service('date.formatter')->formatTimeDiffSince($accounts[$timestamp_user]->created->value), 'Ensure the right member time is displayed.');
     $this->assertEqual($result_accounts[$timestamp_user]['last_access'], 'never', 'Ensure the last access time is "never".');
 }
示例#25
0
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     /** @var \Drupal\shortcut\ShortcutSetInterface $set */
     $set = $this->shortcutSetStorage->load($row->getDestinationProperty('set_name'));
     /** @var \Drupal\user\UserInterface $account */
     $account = User::load($row->getDestinationProperty('uid'));
     $this->shortcutSetStorage->assignUser($set, $account);
     return array($set->id(), $account->id());
 }
 /**
  * {@inheritdoc}
  */
 public function build(FacetInterface $facet, array $results)
 {
     /** @var \Drupal\facets\Result\ResultInterface $result */
     foreach ($results as &$result) {
         /** @var \Drupal\user\Entity\User $user */
         $user = User::load($result->getRawValue());
         $result->setDisplayValue($user->getDisplayName());
     }
     return $results;
 }
示例#27
0
 /**
  * {@inheritdoc}
  */
 protected function renderLink($data, ResultRow $values)
 {
     $uid = $this->getValue($values);
     if (!empty($uid)) {
         $account = User::load($uid);
         $username = array('#theme' => 'username', '#account' => $account);
         return drupal_render($username);
     }
     return $data;
 }
 /**
  * Verifies the expected behaviors of the installation result.
  */
 public function testInstaller()
 {
     $this->assertUrl('user/1');
     $this->assertResponse(200);
     // Verify German was configured but not English.
     $this->drupalGet('admin/config/regional/language');
     $this->assertText('German');
     $this->assertNoText('English');
     // The current container still has the english as current language, rebuild.
     $this->rebuildContainer();
     /** @var \Drupal\user\Entity\User $account */
     $account = User::load(0);
     $this->assertEqual($account->language()->getId(), 'en', 'Anonymous user is English.');
     $account = User::load(1);
     $this->assertEqual($account->language()->getId(), 'en', 'Administrator user is English.');
     $account = $this->drupalCreateUser();
     $this->assertEqual($account->language()->getId(), 'de', 'New user is German.');
     // Ensure that we can enable basic_auth on a non-english site.
     $this->drupalPostForm('admin/modules', array('modules[Web services][basic_auth][enable]' => TRUE), t('Install'));
     $this->assertResponse(200);
     // Assert that the theme CSS was added to the page.
     $edit = array('preprocess_css' => FALSE);
     $this->drupalPostForm('admin/config/development/performance', $edit, t('Save configuration'));
     $this->drupalGet('<front>');
     $this->assertRaw('classy/css/layout.css');
     // Verify the strings from the translation files were imported.
     $test_samples = ['Save and continue', 'Anonymous'];
     foreach ($test_samples as $sample) {
         $edit = array();
         $edit['langcode'] = 'de';
         $edit['translation'] = 'translated';
         $edit['string'] = $sample;
         $this->drupalPostForm('admin/config/regional/translate', $edit, t('Filter'));
         $this->assertText($sample . ' de');
     }
     /** @var \Drupal\language\ConfigurableLanguageManager $language_manager */
     $language_manager = \Drupal::languageManager();
     // Installed in German, configuration should be in German. No German or
     // English overrides should be present.
     $config = \Drupal::config('user.settings');
     $override_de = $language_manager->getLanguageConfigOverride('de', 'user.settings');
     $override_en = $language_manager->getLanguageConfigOverride('en', 'user.settings');
     $this->assertEqual($config->get('anonymous'), 'Anonymous de');
     $this->assertEqual($config->get('langcode'), 'de');
     $this->assertTrue($override_de->isNew());
     $this->assertTrue($override_en->isNew());
     // Assert that adding English makes the English override available.
     $edit = ['predefined_langcode' => 'en'];
     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
     $override_en = $language_manager->getLanguageConfigOverride('en', 'user.settings');
     $this->assertFalse($override_en->isNew());
     $this->assertEqual($override_en->get('anonymous'), 'Anonymous');
 }
示例#29
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $comment = $this->entity();
     $user_id = $comment->uid->target_id;
     $user = User::load($user_id);
     $key = $this->key();
     if (isset($user->{$key}->value)) {
         $format = $this->format();
         return array('#type' => 'processed_text', '#text' => $user->{$key}->value, '#format' => $user->{$format}->value, '#filter_types_to_skip' => array(), '#langcode' => '');
     }
     return array();
 }
示例#30
0
 /**
  * Submit handler for the customer select form.
  *
  * @param array $form
  *   The parent form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitCustomerForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     if ($values['customer_type'] == 'existing') {
         $values['mail'] = User::load($values['uid'])->getEmail();
     } else {
         $user = User::create(['name' => $values['mail'], 'mail' => $values['mail'], 'pass' => $values['generate'] ? user_password() : $values['pass'], 'status' => TRUE]);
         $user->save();
         $values['uid'] = $user->id();
     }
     $form_state->setValues($values);
 }