Example #1
0
 /**
  * Creates multiple group memberships.
  *
  * Provide group membership data in the following format:
  *
  * | user  | group     | role on group        | membership status |
  * | Foo   | The Group | administrator member | Active            |
  *
  * @Given group memberships:
  */
 public function addGroupMemberships(TableNode $groupMembershipsTable)
 {
     foreach ($groupMembershipsTable->getHash() as $groupMembershipHash) {
         if (isset($groupMembershipHash['group']) && isset($groupMembershipHash['user'])) {
             $group = $this->getGroupByName($groupMembershipHash['group']);
             $user = user_load_by_name($groupMembershipHash['user']);
             // Add user to group with the proper group permissions and status
             if ($group && $user) {
                 // Add the user to the group
                 og_group("node", $group->nid->value(), array("entity type" => "user", "entity" => $user, "membership type" => OG_MEMBERSHIP_TYPE_DEFAULT, "state" => $this->getMembershipStatusByName($groupMembershipHash['membership status'])));
                 // Grant user roles
                 $group_role = $this->getGroupRoleByName($groupMembershipHash['role on group']);
                 og_role_grant("node", $group->nid->value(), $user->uid, $group_role);
             } else {
                 if (!$group) {
                     throw new \Exception(sprintf("No group was found with name %s.", $groupMembershipHash['group']));
                 }
                 if (!$user) {
                     throw new \Exception(sprintf("No user was found with name %s.", $groupMembershipHash['user']));
                 }
             }
         } else {
             throw new \Exception(sprintf("The group and user information is required."));
         }
     }
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function nodeCreate($node)
 {
     // Throw an exception if the node type is missing or does not exist.
     if (!isset($node->type) || !$node->type) {
         throw new \Exception("Cannot create content because it is missing the required property 'type'.");
     }
     $bundles = \Drupal::entityManager()->getBundleInfo('node');
     if (!in_array($node->type, array_keys($bundles))) {
         throw new \Exception("Cannot create content because provided content type '{$node->type}' does not exist.");
     }
     // Default status to 1 if not set.
     if (!isset($node->status)) {
         $node->status = 1;
     }
     // If 'author' is set, remap it to 'uid'.
     if (isset($node->author)) {
         $user = user_load_by_name($node->author);
         if ($user) {
             $node->uid = $user->id();
         }
     }
     $this->expandEntityFields('node', $node);
     $entity = entity_create('node', (array) $node);
     $entity->save();
     $node->nid = $entity->id();
     return $node;
 }
 /**
  * @Given I update the moderation state of :named_entity to :state
  * @Given I update the moderation state of :named_entity to :state on date :date
  * @Given :workflow_user updates the moderation state of :named_entity to :state
  * @Given :workflow_user updates the moderation state of :named_entity to :state on date :date
  *
  * Transition a Moderated Node from one state to another.
  *
  * @param String|null $user The string of the username.
  * @param String $named_entity A named entity stored in the entity store.
  * @param String $state The state that you want to transition to.
  * @param String|null $date A valid php datetime string. Supports relative dates.
  * @throws \Exception
  */
 public function transitionModerationState($workflow_user = null, $named_entity, $state, $date = null)
 {
     global $user;
     // Save the original user to set it back later
     $global_user = $user;
     $node = $this->getModerationNode($named_entity);
     $possible_states = workbench_moderation_state_labels();
     $state_key = array_search($state, $possible_states);
     if (!$state_key) {
         $possible_states = implode(", ", $possible_states);
         throw new \Exception("State '{$state}' is not available. All possible states are [{$possible_states}].");
     }
     $current_user = $workflow_user ? user_load_by_name($workflow_user) : $this->getCurrentUser();
     if (!$current_user) {
         throw new \Exception("No user is logged in.");
     }
     $my_revision = $node->workbench_moderation['my_revision'];
     $state_machine_name = array_search($state, $possible_states);
     // If node is moderated to the same state but with different time, then the moderation isn't performed but the time is updated.
     if ($my_revision->state != $state_machine_name) {
         $next_states = workbench_moderation_states_next($my_revision->state, $current_user, $node);
         if (empty($next_states)) {
             $next_states = array();
         }
         if (!isset($next_states[$state_key])) {
             $next_states = implode(", ", $next_states);
             throw new \Exception("State '{$possible_states[$state_key]}' is not available to transition to. Transitions available to user '{$current_user->name}' are [{$next_states}]");
         }
         // Change global user to the current user in order to allow
         // workflow moderation to get the right user.
         $user = $current_user;
         // This function actually updates the transition.
         workbench_moderation_moderate($node, $state_key);
         // the workbench_moderation_moderate defer some status updates on the
         // node (currently the "Publish" status) to the process shutdown. Which
         // does not work well on Behat since scenarios are run on a single drupal
         // bootstrap.
         // To work around this setup. After calling the
         // `workbench_moderation_moderate` callback we check if a call to the
         // `workbench_moderation_store` function is part of the shutdown
         // execution and run it.
         $callbacks =& drupal_register_shutdown_function();
         while (list($key, $callback) = each($callbacks)) {
             if ($callback['callback'] == 'workbench_moderation_store') {
                 call_user_func_array($callback['callback'], $callback['arguments']);
                 unset($callbacks[$key]);
             }
         }
         // Back global user to the original user. Probably an anonymous.
         $user = $global_user;
     }
     // If a specific date is requested, then updated it after the fact.
     if (isset($date)) {
         $timestamp = strtotime($date, REQUEST_TIME);
         if (!$timestamp) {
             throw new \Exception("Error creating datetime from string '{$date}'");
         }
         db_update('workbench_moderation_node_history')->fields(array('stamp' => $timestamp))->condition('nid', $node->nid, '=')->condition('vid', $node->vid, '=')->execute();
     }
 }
Example #4
0
 /**
  * Update profile
  * FIXME
  *
  * @return void
  */
 protected function updateProfile()
 {
     if ($this->isCreateProfile()) {
         $error = user_validate_name(\XLite\Core\Request::getInstance()->username);
         if ($error) {
             // Username validation error
             $this->valid = false;
             \XLite\Core\Event::invalidElement('username', $error);
         } elseif (user_load_by_name(\XLite\Core\Request::getInstance()->username)) {
             // Username is already exists
             $this->valid = false;
             $label = static::t('This user name is used for an existing account. Enter another user name or sign in', array('URL' => $this->getLoginURL()));
             \XLite\Core\Event::invalidElement('username', $label);
         } elseif (\XLite\Core\Request::getInstance()->email && user_load_multiple(array(), array('mail' => \XLite\Core\Request::getInstance()->email))) {
             // E-mail is already exists in Drupal DB
             $this->valid = false;
             $label = static::t('This email address is used for an existing account. Enter another user name or sign in', array('URL' => $this->getLoginURL()));
             \XLite\Core\Event::invalidElement('email', $label);
         }
     }
     parent::updateProfile();
     if ($this->isCreateProfile() && $this->valid) {
         // Save username is session (temporary, wait place order procedure)
         \XLite\Core\Session::getInstance()->order_username = \XLite\Core\Request::getInstance()->create_profile ? \XLite\Core\Request::getInstance()->username : false;
     }
 }
 /**
  * Test node creation by editor.
  *
  * 1. Editor creates Draft node
  * 2. Editor set status from Draft to Final Draft
  * 3. The node appears in the users's overview screen.
  */
 public function testModerateToBeApproved()
 {
     $this->loginAs('editor1');
     $node = $this->drupalCreateNode(array('language' => 'en', 'title' => $this->nodeTitle1, 'type' => 'news', 'workbench_access' => 1007));
     workbench_moderation_moderate($node, 'final_draft');
     $this->loginAs('review_manager1');
     // Set node status To Be Reviewed.
     $options = array('title_field[en][0][value]' => $this->nodeTitle1, 'workbench_moderation_state_new' => 'needs_review');
     $this->drupalPost("node/{$node->nid}/edit", $options, t('Save'));
     entity_get_controller('node')->resetCache(array($node->nid));
     $node = node_load($node->nid);
     $this->assertEquals('needs_review', $node->workbench_moderation['current']->state);
     // Set the reviewer to project_manager1
     $pm1 = user_load_by_name('project_manager1');
     $options = array('project_manager' => $pm1->uid);
     $this->drupalPost("node/{$node->nid}/review", $options, t('Change'));
     $this->drupalGet("node/{$node->nid}/review");
     $this->assertText('project_manager1');
     // Define the list of approvers.
     // Cannot use drupalPost here.
     $ap1 = user_load_by_name('approver1');
     $ap2 = user_load_by_name('approver2 ');
     $form_state = array('node' => $node, 'values' => array('rows' => array($ap1->uid => array('weight' => -10), $ap2->uid => array('weight' => -11))));
     module_load_include('inc', 'osha_workflow', 'osha_workflow.admin');
     drupal_form_submit('osha_workflow_node_approval_form', $form_state, $node);
     $this->drupalGet("node/{$node->nid}/approve");
     $this->assertText($ap1->name);
     $this->assertText($ap2->name);
     $this->loginAs('project_manager1');
     $options = array('workbench_moderation_state_new' => 'to_be_approved');
     $this->drupalPost("node/{$node->nid}/edit", $options, t('Save'));
     entity_get_controller('node')->resetCache(array($node->nid));
     $node = node_load($node->nid);
     $this->assertEquals('to_be_approved', $node->workbench_moderation['current']->state);
 }
 /**
  * Test user registration integration.
  */
 public function testUserRegisterForm()
 {
     $id = $this->type->id();
     $field_name = $this->field->getName();
     $this->field->setRequired(TRUE);
     $this->field->save();
     // Allow registration without administrative approval and log in user
     // directly after registering.
     \Drupal::configFactory()->getEditable('user.settings')->set('register', USER_REGISTER_VISITORS)->set('verify_mail', 0)->save();
     user_role_grant_permissions(AccountInterface::AUTHENTICATED_ROLE, ['view own test profile']);
     // Verify that the additional profile field is attached and required.
     $name = $this->randomMachineName();
     $pass_raw = $this->randomMachineName();
     $edit = ['name' => $name, 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => $pass_raw, 'pass[pass2]' => $pass_raw];
     $this->drupalPostForm('user/register', $edit, t('Create new account'));
     $this->assertRaw(new FormattableMarkup('@name field is required.', ['@name' => $this->field->getLabel()]));
     // Verify that we can register.
     $edit["entity_" . $id . "[{$field_name}][0][value]"] = $this->randomMachineName();
     $this->drupalPostForm(NULL, $edit, t('Create new account'));
     $this->assertText(new FormattableMarkup('Registration successful. You are now logged in.', []));
     $new_user = user_load_by_name($name);
     $this->assertTrue($new_user->isActive(), 'New account is active after registration.');
     // Verify that a new profile was created for the new user ID.
     $profile = \Drupal::entityTypeManager()->getStorage('profile')->loadByUser($new_user, $this->type->id());
     $this->assertEqual($profile->get($field_name)->value, $edit["entity_" . $id . "[{$field_name}][0][value]"], 'Field value found in loaded profile.');
     // Verify that the profile field value appears on the user account page.
     $this->drupalGet('user');
     $this->assertText($edit["entity_" . $id . "[{$field_name}][0][value]"], 'Field value found on user account page.');
 }
 /**
  * Login as custom account.
  *
  * @param string $username
  *   Username to login with
  * @param string $password
  *   Password. By default all dev instance are set to 'password'.
  */
 public function loginAs($username, $password = '******')
 {
     global $user;
     $user = user_load_by_name($username);
     $this->assertNotNull($user, "Could not login {$username}");
     $user->pass_raw = $password;
     $this->drupalLogin($user);
 }
Example #8
0
 public function validateConfigurationForm(array &$form, array &$form_state)
 {
     $values =& $form_state['values']['processor']['configuration'];
     if ($author = user_load_by_name($values['author'])) {
         $values['author'] = $author->id();
     } else {
         $values['author'] = 0;
     }
 }
Example #9
0
 /**
  * Login via rest to get the user's access token.
  *
  * @param $user
  *   The user name.
  *
  * @return string
  *   The user access token.
  */
 private function restLogin($user)
 {
     if (isset($this->accessToken[$user])) {
         return $this->accessToken[$user]['access_token'];
     }
     $handler = new RestfulAccessTokenAuthentication(['entity_type' => 'restful_token_auth', 'bundle' => 'access_token']);
     $handler->setAccount(user_load_by_name($user));
     $data = $handler->getOrCreateToken();
     $this->accessToken[$user] = $data;
     return $data['access_token'];
 }
 public function test_osha_workflow_get_set_project_manager()
 {
     $this->assertNull(osha_workflow_get_project_manager(-1));
     $node = $this->createNodeNews();
     $pm3 = user_load_by_name('project_manager3');
     osha_workflow_set_project_manager($node->nid, $pm3->uid);
     $pm = osha_workflow_get_project_manager($node->nid);
     $this->assertEquals($pm3->uid, $pm->uid);
     $this->assertFalse(osha_workflow_is_assigned_project_manager($node->nid));
     $this->loginAs('project_manager3');
     $this->assertTrue(osha_workflow_is_assigned_project_manager($node->nid));
     node_delete($node->nid);
 }
 /**
  * Create a user through the administration interface and ensure that it
  * displays in the user list.
  */
 public function testUserAdd()
 {
     $user = $this->drupalCreateUser(array('administer users'));
     $this->drupalLogin($user);
     $this->assertEqual($user->getCreatedTime(), REQUEST_TIME, 'Creating a user sets default "created" timestamp.');
     $this->assertEqual($user->getChangedTime(), REQUEST_TIME, 'Creating a user sets default "changed" timestamp.');
     // Create a field.
     $field_name = 'test_field';
     FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'user', 'module' => 'image', 'type' => 'image', 'cardinality' => 1, 'locked' => FALSE, 'indexes' => array('target_id' => array('target_id')), 'settings' => array('uri_scheme' => 'public')))->save();
     FieldConfig::create(['field_name' => $field_name, 'entity_type' => 'user', 'label' => 'Picture', 'bundle' => 'user', 'description' => t('Your virtual face or picture.'), 'required' => FALSE, 'settings' => array('file_extensions' => 'png gif jpg jpeg', 'file_directory' => 'pictures', 'max_filesize' => '30 KB', 'alt_field' => 0, 'title_field' => 0, 'max_resolution' => '85x85', 'min_resolution' => '')])->save();
     // Test user creation page for valid fields.
     $this->drupalGet('admin/people/create');
     $this->assertFieldbyId('edit-status-0', 0, 'The user status option Blocked exists.', 'User login');
     $this->assertFieldbyId('edit-status-1', 1, 'The user status option Active exists.', 'User login');
     $this->assertFieldByXPath('//input[@type="radio" and @id="edit-status-1" and @checked="checked"]', NULL, 'Default setting for user status is active.');
     // Test that browser autocomplete behavior does not occur.
     $this->assertNoRaw('data-user-info-from-browser', 'Ensure form attribute, data-user-info-from-browser, does not exist.');
     // Test that the password strength indicator displays.
     $config = $this->config('user.settings');
     $config->set('password_strength', TRUE)->save();
     $this->drupalGet('admin/people/create');
     $this->assertRaw(t('Password strength:'), 'The password strength indicator is displayed.');
     $config->set('password_strength', FALSE)->save();
     $this->drupalGet('admin/people/create');
     $this->assertNoRaw(t('Password strength:'), 'The password strength indicator is not displayed.');
     // We create two users, notifying one and not notifying the other, to
     // ensure that the tests work in both cases.
     foreach (array(FALSE, TRUE) as $notify) {
         $name = $this->randomMachineName();
         $edit = array('name' => $name, 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => $pass = $this->randomString(), 'pass[pass2]' => $pass, 'notify' => $notify);
         $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
         if ($notify) {
             $this->assertText(t('A welcome message with further instructions has been emailed to the new user @name.', array('@name' => $edit['name'])), 'User created');
             $this->assertEqual(count($this->drupalGetMails()), 1, 'Notification email sent');
         } else {
             $this->assertText(t('Created a new user account for @name. No email has been sent.', array('@name' => $edit['name'])), 'User created');
             $this->assertEqual(count($this->drupalGetMails()), 0, 'Notification email not sent');
         }
         $this->drupalGet('admin/people');
         $this->assertText($edit['name'], 'User found in list of users');
         $user = user_load_by_name($name);
         $this->assertEqual($user->isActive(), 'User is not blocked');
     }
     // Test that the password '0' is considered a password.
     // @see https://www.drupal.org/node/2563751.
     $name = $this->randomMachineName();
     $edit = array('name' => $name, 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => 0, 'pass[pass2]' => 0, 'notify' => FALSE);
     $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
     $this->assertText("Created a new user account for {$name}. No email has been sent");
     $this->assertNoText('Password field is required');
 }
 /**
  * Check whether user is loggedin to cosign, is a drupal user, and is logged into drupal
  *
  * @return
  *   User object
  */
 public static function cosign_user_status($cosign_username)
 {
     $user = \Drupal::currentUser();
     $uname = $user->getAccountName();
     $drupal_user = user_load_by_name($cosign_username);
     if (!empty($uname)) {
         //youre already logged in
         //make sure you are the cosign user. if not log out. This is unlikely
         if ($cosign_username != $uname) {
             user_logout();
             return null;
         }
     }
     if (!empty($cosign_username)) {
         $is_friend_account = CosignSharedFunctions::cosign_is_friend_account($cosign_username);
         // If friend accounts are not allowed, log them out
         if (\Drupal::config('cosign.settings')->get('cosign_allow_friend_accounts') == 0 && $is_friend_account) {
             CosignSharedFunctions::cosign_friend_not_allowed();
             if (\Drupal::config('cosign.settings')->get('cosign_allow_anons_on_https') == 1) {
                 return user_load(0);
             } else {
                 return null;
             }
         }
     }
     if (!empty($cosign_username) && !empty($drupal_user) && empty($uname)) {
         //login the cosign user
         CosignSharedFunctions::cosign_login_user($drupal_user);
     } elseif (!empty($cosign_username) && empty($drupal_user)) {
         //cosign user doesn't have a drupal account
         if (\Drupal::config('cosign.settings')->get('cosign_autocreate') == 1) {
             $new_user = CosignSharedFunctions::cosign_create_new_user($cosign_username);
             user_load($new_user->id(), TRUE);
         } else {
             //drupal_set_message(t('This site does not auto create users from cosign. Please contact the <a href="mailto:'. \Drupal::config("system.site")->get("mail").'">site administrator</a> to have an account created.'), 'warning');
             user_load(0);
         }
     } elseif (empty($cosign_username) && \Drupal::config('cosign.settings')->get('cosign_allow_anons_on_https') == 0) {
         //no cosign account found
         user_logout();
         return null;
     }
     $user = \Drupal::currentUser();
     if (!$user) {
         $user = user_load(0);
     }
     if ($user->id() == 0 && \Drupal::config('cosign.settings')->get('cosign_allow_anons_on_https') == 1) {
         //drupal_set_message(t('You do not have a valid cosign username. Browsing as anonymous user over https.'));
     }
     return $user;
 }
 /**
  * Functional test for language handling during user creation.
  */
 function testLocalUserCreation()
 {
     // User to add and remove language and create new users.
     $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'administer users'));
     $this->drupalLogin($admin_user);
     // Add predefined language.
     $langcode = 'fr';
     $language = new Language(array('id' => $langcode));
     language_save($language);
     // Set language negotiation.
     $edit = array('language_interface[enabled][language-url]' => TRUE);
     $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
     $this->assertText(t('Language negotiation configuration saved.'), 'Set language negotiation.');
     // Check if the language selector is available on admin/people/create and
     // set to the currently active language.
     $this->drupalGet($langcode . '/admin/people/create');
     $this->assertOptionSelected("edit-preferred-langcode", $langcode, 'Global language set in the language selector.');
     // Create a user with the admin/people/create form and check if the correct
     // language is set.
     $username = $this->randomName(10);
     $edit = array('name' => $username, 'mail' => $this->randomName(4) . '@example.com', 'pass[pass1]' => $username, 'pass[pass2]' => $username);
     $this->drupalPostForm($langcode . '/admin/people/create', $edit, t('Create new account'));
     $user = user_load_by_name($username);
     $this->assertEqual($user->getPreferredLangcode(), $langcode, 'New user has correct preferred language set.');
     $this->assertEqual($user->language()->id, $langcode, 'New user has correct profile language set.');
     // Register a new user and check if the language selector is hidden.
     $this->drupalLogout();
     $this->drupalGet($langcode . '/user/register');
     $this->assertNoFieldByName('language[fr]', 'Language selector is not accessible.');
     $username = $this->randomName(10);
     $edit = array('name' => $username, 'mail' => $this->randomName(4) . '@example.com');
     $this->drupalPostForm($langcode . '/user/register', $edit, t('Create new account'));
     $user = user_load_by_name($username);
     $this->assertEqual($user->getPreferredLangcode(), $langcode, 'New user has correct preferred language set.');
     $this->assertEqual($user->language()->id, $langcode, 'New user has correct profile language set.');
     // Test if the admin can use the language selector and if the
     // correct language is was saved.
     $user_edit = $langcode . '/user/' . $user->id() . '/edit';
     $this->drupalLogin($admin_user);
     $this->drupalGet($user_edit);
     $this->assertOptionSelected("edit-preferred-langcode", $langcode, 'Language selector is accessible and correct language is selected.');
     // Set pass_raw so we can login the new user.
     $user->pass_raw = $this->randomName(10);
     $edit = array('pass[pass1]' => $user->pass_raw, 'pass[pass2]' => $user->pass_raw);
     $this->drupalPostForm($user_edit, $edit, t('Save'));
     $this->drupalLogin($user);
     $this->drupalGet($user_edit);
     $this->assertOptionSelected("edit-preferred-langcode", $langcode, 'Language selector is accessible and correct language is selected.');
 }
Example #14
0
 /**
  * Tests Standard installation profile.
  */
 public function testCasAutoAssignedRoles()
 {
     $role_id = $this->drupalCreateRole([]);
     $role_id_2 = $this->drupalCreateRole([]);
     $edit = ['user_accounts[auto_register]' => TRUE, 'user_accounts[auto_assigned_roles_enable]' => TRUE, 'user_accounts[auto_assigned_roles][]' => [$role_id, $role_id_2]];
     $this->drupalPostForm('/admin/config/people/cas', $edit, 'Save configuration');
     $this->assertEquals([$role_id, $role_id_2], $this->config('cas.settings')->get('user_accounts.auto_assigned_roles'));
     $cas_property_bag = new CasPropertyBag('test_cas_user_name');
     \Drupal::service('cas.login')->loginToDrupal($cas_property_bag, 'fake_ticket_string');
     $user = user_load_by_name('test_cas_user_name');
     $this->assertTrue($user->hasRole($role_id), 'The user has the auto assigned role: ' . $role_id);
     $this->assertTrue($user->hasRole($role_id_2), 'The user has the auto assigned role: ' . $role_id_2);
     Role::load($role_id_2)->delete();
     $this->assertEquals([$role_id], $this->config('cas.settings')->get('user_accounts.auto_assigned_roles'));
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function processInbound($path, Request $request)
 {
     if (preg_match('!^/user/([^/]+)(/.*)?!', $path, $matches)) {
         if ($account = user_load_by_name($matches[1])) {
             $matches += array(2 => '');
             $path = '/user/' . $account->id() . $matches[2];
         }
     }
     // Rewrite community/ to forum/.
     $path = preg_replace('@^/community(.*)@', '/forum$1', $path);
     if ($path == '/url-alter-test/bar') {
         $path = '/url-alter-test/foo';
     }
     return $path;
 }
 public function xxtestUserCanEditApprovers()
 {
     global $user;
     $user = user_load(1);
     $node = $this->drupalCreateNode(array('type' => 'news', 'language' => 'en', 'uid' => 1, 'title' => 'TEST NODE'));
     $user = user_load(0);
     $this->assertFalse(OshaWorkflowPermissions::userCanAccessApprovalScreen($node, NULL));
     $this->assertFalse(OshaWorkflowPermissions::userCanAccessApprovalScreen((object) array(), $user));
     $user = user_load(1);
     $this->assertTrue(OshaWorkflowPermissions::userCanAccessApprovalScreen($node, $user));
     $user = user_load_by_name('review_manager1');
     $this->assertTrue(OshaWorkflowPermissions::userCanAccessApprovalScreen($node, $user));
     $this->drupalLogout();
     node_delete($node->nid);
 }
 /**
  * Test creating a user with arbitrary uid.
  */
 function testUserImport()
 {
     // User ID must be a number that is not in the database.
     $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField();
     $test_uid = $max_uid + mt_rand(1000, 1000000);
     $test_name = $this->randomMachineName();
     // Create the base user, based on drupalCreateUser().
     $user = entity_create('user', array('name' => $test_name, 'uid' => $test_uid, 'mail' => $test_name . '@example.com', 'pass' => user_password(), 'status' => 1));
     $user->enforceIsNew();
     $user->save();
     // Test if created user exists.
     $user_by_uid = user_load($test_uid);
     $this->assertTrue($user_by_uid, 'Loading user by uid.');
     $user_by_name = user_load_by_name($test_name);
     $this->assertTrue($user_by_name, 'Loading user by name.');
 }
 /**
  * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processInbound().
  */
 public function processInbound($path, Request $request)
 {
     if (preg_match('!^user/([^/]+)(/.*)?!', $path, $matches)) {
         if ($account = user_load_by_name($matches[1])) {
             $matches += array(2 => '');
             $path = 'user/' . $account->id() . $matches[2];
         }
     }
     // Rewrite community/ to forum/.
     if ($path == 'community' || strpos($path, 'community/') === 0) {
         $path = 'forum' . substr($path, 9);
     }
     if ($path == 'url-alter-test/bar') {
         $path = 'url-alter-test/foo';
     }
     return $path;
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function applies(Request $request)
 {
     $username = CosignSharedFunctions::cosign_retrieve_remote_user();
     $drupal_user = user_load_by_name($username);
     //This session variable is set and sticks even after user_logout() causing numerous problems. if we put cosign module priority after the user module (priority 0 or below in services.yml) the symfony session sticks and the previous user gets logged in. if we put it above the user module (above priority 0) the user gets relogged in every time because drupal's session hasn't been set yet...even though symfony's has.
     //TODO This should be the proper way to get this but it doesnt get it -
     //$symfony_uid = $request->getSession()-> get('_sf2_attributes');
     if ($drupal_user && $drupal_user->id() == $_SESSION['_sf2_attributes']['uid']) {
         //the user is already logged in. symfony knows, drupal doesnt yet. bypass cosign so we dont login again
         return FALSE;
     }
     if (CosignSharedFunctions::cosign_is_https() && $request->getRequestUri() != '/user/logout' && (\Drupal::config('cosign.settings')->get('cosign_allow_cosign_anons') == 0 || \Drupal::config('cosign.settings')->get('cosign_allow_anons_on_https') == 0 || strpos($request->getRequestUri(), 'user/login') || strpos($request->getRequestUri(), 'user/register'))) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
Example #20
0
 /**
  * Test creating a user with arbitrary uid.
  */
 function testUserImport()
 {
     // User ID must be a number that is not in the database.
     $uids = \Drupal::entityManager()->getStorage('user')->getQuery()->sort('uid', 'DESC')->range(0, 1)->execute();
     $max_uid = reset($uids);
     $test_uid = $max_uid + mt_rand(1000, 1000000);
     $test_name = $this->randomMachineName();
     // Create the base user, based on drupalCreateUser().
     $user = entity_create('user', array('name' => $test_name, 'uid' => $test_uid, 'mail' => $test_name . '@example.com', 'pass' => user_password(), 'status' => 1));
     $user->enforceIsNew();
     $user->save();
     // Test if created user exists.
     $user_by_uid = User::load($test_uid);
     $this->assertTrue($user_by_uid, 'Loading user by uid.');
     $user_by_name = user_load_by_name($test_name);
     $this->assertTrue($user_by_name, 'Loading user by name.');
 }
 /**
  * {@inheritdoc}
  */
 public function parse(ContextInterface $context, InlineParserContext $inline_context)
 {
     $cursor = $inline_context->getCursor();
     // The @ symbol must not have any other characters immediately prior.
     $previous_char = $cursor->peek(-1);
     if ($previous_char !== NULL && $previous_char !== ' ') {
         // peek() doesn't modify the cursor, so no need to restore state first.
         return FALSE;
     }
     // Save the cursor state in case we need to rewind and bail.
     $previous_state = $cursor->saveState();
     // Advance past the @ symbol to keep parsing simpler.
     $cursor->advance();
     // Parse the handle.
     $text = $cursor->match('/^[^\\s]+/');
     $url = '';
     $title = '';
     $type = $this->getSetting('type');
     if ($type === 'user') {
         $user = user_load_by_name($text);
         if ((!$user || !$user->uid) && is_numeric($text)) {
             $user = user_load((int) $text);
         }
         if ($user && $user->uid) {
             $url = url("user/{$user->uid}", ['absolute' => TRUE]);
             $title = t('View user profile.');
             if ($this->getSetting('format_username')) {
                 $text = format_username($user);
             }
         } else {
             $text = FALSE;
         }
     } elseif ($type === 'url' && ($url = $this->getSetting('url')) && strpos($url, '[text]') !== FALSE) {
         $url = str_replace('[text]', $text, $url);
     } else {
         $text = FALSE;
     }
     // Regex failed to match; this isn't a valid @ handle.
     if (empty($text) || empty($url)) {
         $cursor->restoreState($previous_state);
         return FALSE;
     }
     $inline_context->getInlines()->add(new Link($url, '@' . $text, $title));
     return TRUE;
 }
 /**
  * Tests that when creating a user the role can be assigned. And that it can
  * be removed again.
  */
 function testCreateUserWithRole()
 {
     $rid = $this->drupalCreateRole(array('administer users'));
     // Create a new user and add the role at the same time.
     $edit = array('name' => $this->randomMachineName(), 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => $pass = $this->randomString(), 'pass[pass2]' => $pass, "roles[{$rid}]" => $rid);
     $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
     $this->assertText(t('Created a new user account for @name.', array('@name' => $edit['name'])));
     // Get the newly added user.
     $account = user_load_by_name($edit['name']);
     $this->drupalGet('user/' . $account->id() . '/edit');
     $this->assertFieldChecked('edit-roles-' . $rid, 'Role is assigned.');
     $this->userLoadAndCheckRoleAssigned($account, $rid);
     // Remove the role again.
     $this->drupalPostForm('user/' . $account->id() . '/edit', array("roles[{$rid}]" => FALSE), t('Save'));
     $this->assertText(t('The changes have been saved.'));
     $this->assertNoFieldChecked('edit-roles-' . $rid, 'Role is removed from user.');
     $this->userLoadAndCheckRoleAssigned($account, $rid, FALSE);
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function nodeCreate($node)
 {
     // Default status to 1 if not set.
     if (!isset($node->status)) {
         $node->status = 1;
     }
     // If 'author' is set, remap it to 'uid'.
     if (isset($node->author)) {
         $user = user_load_by_name($node->author);
         if ($user) {
             $node->uid = $user->id();
         }
     }
     $this->expandEntityFields('node', $node);
     $entity = entity_create('node', (array) $node);
     $entity->save();
     $node->nid = $entity->id();
     return $node;
 }
 /**
  * {@inheritdoc}
  */
 protected function generateElements(array $values)
 {
     $num = $values['num'];
     $kill = $values['kill'];
     if ($kill) {
         $this->setMessage($this->t('Old examples have been deleted.'));
     }
     //Creating user in order to demonstrate
     // how to override default business login generation.
     $edit = array('uid' => NULL, 'name' => 'example_devel_generate', 'pass' => '', 'mail' => '*****@*****.**', 'status' => 1, 'created' => REQUEST_TIME, 'roles' => '', 'devel_generate' => TRUE);
     $account = user_load_by_name('example_devel_generate');
     if (!$account) {
         $account = entity_create('user', $edit);
     }
     // Populate all fields with sample values.
     $this->populateFields($node);
     $account->save();
     $this->setMessage($this->t('!num_examples created.', array('!num_examples' => $this->formatPlural($num, '1 example', '@count examples'))));
 }
function validateInvitedFreelancers($form, $form_state)
{
    if (!isset($form['field_freelancers_to_invite'])) {
        form_set_error('field_freelancers_to_invite', 'Please enter at least one Creative Pro to invite');
    }
    //debugLong($form_state['values']['field_freelancers_to_invite'], '_validate_freelancers_to_invite');
    $freelancers_to_invite = explode(',', $form_state['values']['field_freelancers_to_invite']);
    //debugLong($freelancers_to_invite, '_validate_freelancers_to_invite_exploded');
    if (empty($freelancers_to_invite[0])) {
        form_set_error('field_freelancers_to_invite', 'Enter at least one Creative Pro');
    }
    $invalid = array();
    $notApproved = array();
    foreach ($freelancers_to_invite as $name) {
        $f = user_load_by_name(trim($name));
        if ($f == false) {
            array_push($invalid, $name);
        } else {
            if (!user_has_role(8, $f)) {
                array_push($notApproved, $name);
            }
        }
    }
    if (!empty($invalid)) {
        $invalidInStr = implode(', ', $invalid);
        $errorMessage = 'Not creative pros: ' . $invalidInStr;
    }
    if (!empty($notApproved)) {
        $notApprovedInStr = implode(', ', $notApproved);
        if (isset($errorMessage)) {
            $errorMessage .= "<br>Freelancers not yet approved by Tap: " . $notApprovedInStr;
        } else {
            $errorMessage = "Freelancers not yet approved by Tap: " . $notApprovedInStr;
        }
    }
    if (!empty($errorMessage)) {
        form_set_error('field_freelancers_to_invite', $errorMessage);
    }
    $trimmed = array_map('trim', $freelancers_to_invite);
    $form_state['values']['field_freelancers_to_invite'] = implode(',', $trimmed);
}
Example #26
0
/**
 * Checking site administrator's username and password.
 */
function check_username_password()
{
    $sitename = variable_get('site_name', "Default site name");
    $usernames = array('admin', 'admin123', 'siteadmin', 'siteadmin123', $sitename);
    $query = db_select('users', 'u')->fields('u', array('name'))->condition('u.uid', 1)->execute()->fetchAssoc();
    if (in_array($query['name'], $usernames)) {
        $data = "<li><b>Error </b>Change site administrator's username ie <b>" . $query['name'] . "</b></li>";
        fwrite($GLOBALS['createdFile'], $data);
    }
    $passwords = array('admin', 'admin123', 'siteadmin', 'siteadmin123', $sitename);
    $passwords[] = $query['name'];
    $account = user_load_by_name($query['name']);
    foreach ($passwords as $password) {
        $pass = user_check_password($password, $account);
        if ($pass == TRUE) {
            $data = "<li><b>Error </b>Need to change site administrator's password immediately.</li>";
            fwrite($GLOBALS['createdFile'], $data);
            break;
        }
    }
}
Example #27
0
 /**
  * {@inheritDoc}
  */
 public function nodeCreate($node)
 {
     // Set original if not set.
     if (!isset($node->original)) {
         $node->original = clone $node;
     }
     // Assign authorship if none exists and `author` is passed.
     if (!isset($node->uid) && !empty($node->author) && ($user = user_load_by_name($node->author))) {
         $node->uid = $user->uid;
     }
     // Convert properties to expected structure.
     $this->expandEntityProperties($node);
     // Attempt to decipher any fields that may be specified.
     $node = $this->expandEntityFields($node);
     // Set defaults that haven't already been set.
     $defaults = clone $node;
     node_object_prepare($defaults);
     $node = (object) array_merge((array) $defaults, (array) $node);
     node_save($node);
     return $node;
 }
Example #28
0
 /**
  * Create a user through the administration interface and ensure that it
  * displays in the user list.
  */
 protected function testUserAdd()
 {
     $user = $this->drupalCreateUser(array('administer users'));
     $this->drupalLogin($user);
     // Create a field and an instance.
     $field_name = 'test_field';
     entity_create('field_storage_config', array('name' => $field_name, 'entity_type' => 'user', 'module' => 'image', 'type' => 'image', 'cardinality' => 1, 'locked' => FALSE, 'indexes' => array('target_id' => array('target_id')), 'settings' => array('uri_scheme' => 'public')))->save();
     entity_create('field_instance_config', array('field_name' => $field_name, 'entity_type' => 'user', 'label' => 'Picture', 'bundle' => 'user', 'description' => t('Your virtual face or picture.'), 'required' => FALSE, 'settings' => array('file_extensions' => 'png gif jpg jpeg', 'file_directory' => 'pictures', 'max_filesize' => '30 KB', 'alt_field' => 0, 'title_field' => 0, 'max_resolution' => '85x85', 'min_resolution' => '')))->save();
     // Test user creation page for valid fields.
     $this->drupalGet('admin/people/create');
     $this->assertFieldbyId('edit-status-0', 0, 'The user status option Blocked exists.', 'User login');
     $this->assertFieldbyId('edit-status-1', 1, 'The user status option Active exists.', 'User login');
     $this->assertFieldByXPath('//input[@type="radio" and @id="edit-status-1" and @checked="checked"]', NULL, 'Default setting for user status is active.');
     // Test that the password strength indicator displays.
     $config = \Drupal::config('user.settings');
     $config->set('password_strength', TRUE)->save();
     $this->drupalGet('admin/people/create');
     $this->assertRaw(t('Password strength:'), 'The password strength indicator is displayed.');
     $config->set('password_strength', FALSE)->save();
     $this->drupalGet('admin/people/create');
     $this->assertNoRaw(t('Password strength:'), 'The password strength indicator is not displayed.');
     // We create two users, notifying one and not notifying the other, to
     // ensure that the tests work in both cases.
     foreach (array(FALSE, TRUE) as $notify) {
         $name = $this->randomName();
         $edit = array('name' => $name, 'mail' => $this->randomName() . '@example.com', 'pass[pass1]' => $pass = $this->randomString(), 'pass[pass2]' => $pass, 'notify' => $notify);
         $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
         if ($notify) {
             $this->assertText(t('A welcome message with further instructions has been emailed to the new user @name.', array('@name' => $edit['name'])), 'User created');
             $this->assertEqual(count($this->drupalGetMails()), 1, 'Notification email sent');
         } else {
             $this->assertText(t('Created a new user account for @name. No email has been sent.', array('@name' => $edit['name'])), 'User created');
             $this->assertEqual(count($this->drupalGetMails()), 0, 'Notification email not sent');
         }
         $this->drupalGet('admin/people');
         $this->assertText($edit['name'], 'User found in list of users');
         $user = user_load_by_name($name);
         $this->assertEqual($user->isActive(), 'User is not blocked');
     }
 }
 /**
  * (non-PHPdoc)
  * @see AbstractCallback::getListeUser()
  * 
  * Fonction pour récupérer Le référent (et Directeur si différent) 
  * de l’ADEFIM rattachée à partir de la liste d'ID Entreprise
  * 
  */
 public function getListeUser() {
     
     $users = array();
     
     $ids_entreprise = $this->param->id_entreprises;
     
     db_set_active(@DB_SLAVE);
     
     $query = db_select('comptes_adefims', 'ca');
     $query->join('fonctions_adefims', 'fa', 'ca.id_fonction_adefim = fa.id');
     $query->join('adefims', 'a', 'ca.id_adefim = a.id');
     $query->join('v_adefims_entreprise', 'lae', 'lae.id_adefim = a.id');
     $query->join('entreprises', 'e', 'lae.id_entreprise = e.id');
     $query->fields('ca', array('id','nom_utilisateur'));
     $query->condition('a.est_actif' , 1, '=');
     $query->condition('ca.est_actif' , 1, '=');
     //filtre par entreprise
     $query->condition('e.id', $ids_entreprise, 'IN');
     //filtre par fonction Directeur et Référent
     $query->condition('fa.id' , array('I.1','I.3'), 'IN');
     
     $results = $query->execute()->fetchAll();
     
     db_set_active();
     
     //Récupération des uid des users Adefim depuis drupal
     foreach ($results as $user_adefim) {
         $user = user_load_by_name(rtrim($user_adefim->nom_utilisateur));
         if ($user != false) {
             $users[] = $user->uid;
         }
     }
     
     // Supprimer les doublons si plusieurs entreprises
     $users = array_unique($users);
     
     return $users;
     
 }
Example #30
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $operation = $input->getArgument('operation');
     $user = $input->getArgument('user');
     $role = $input->getArgument('role');
     $systemRoles = $this->drupalApi->getRoles();
     if (is_numeric($user)) {
         $userObject = user_load($user);
     } else {
         $userObject = user_load_by_name($user);
     }
     if (!is_object($userObject)) {
         if (!filter_var($user, FILTER_VALIDATE_EMAIL) === false) {
             $userObject = user_load_by_mail($user);
         }
     }
     if (!is_object($userObject)) {
         $io->error(sprintf($this->trans('commands.user.role.messages.no-user-found'), $user));
         return 1;
     }
     if (!array_key_exists($role, $systemRoles)) {
         $io->error(sprintf($this->trans('commands.user.role.messages.no-role-found'), $role));
         return 1;
     }
     if ("add" == $operation) {
         $userObject->addRole($role);
         $userObject->save();
         $io->success(sprintf($this->trans('commands.user.role.messages.add-success'), $userObject->name->value . " (" . $userObject->mail->value . ") ", $role));
     }
     if ("remove" == $operation) {
         $userObject->removeRole($role);
         $userObject->save();
         $io->success(sprintf($this->trans('commands.user.role.messages.remove-success'), $userObject->name->value . " (" . $userObject->mail->value . ") ", $role));
     }
 }