/**
  * Returns a new user with role 'applicant'.
  *
  * Requires 'recruiter_resume' feature.
  */
 public function createApplicantUser()
 {
     $role = user_role_load_by_name('applicant');
     // @todo role ids are completely broken, if modules are enable in the wrong
     // order.
     return $this->createUser($role);
 }
 /**
  * Provide the actual editing form.
  */
 function edit_form(&$form, &$form_state)
 {
     parent::edit_form($form, $form_state);
     $item = $form_state['item'];
     $form['info']['admin_title']['#required'] = TRUE;
     $form['info']['admin_title']['#maxlength'] = 80;
     $form['path'] = array('#type' => 'textarea', '#title' => t('Paths'), '#default_value' => $item->path, '#maxlength' => 128, '#size' => 45, '#description' => t('Specify pages by using their paths. Enter one path per line. The \'*\' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.', array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>')), '#required' => TRUE);
     $form['help'] = array('#type' => 'textarea', '#title' => t('Help message'), '#default_value' => $item->help, '#description' => t('Specify a help message.'), '#required' => TRUE);
     $form['options'] = array('#type' => 'vertical_tabs');
     $form['options_roles'] = array('#type' => 'fieldset', '#title' => t('Roles'), '#collapsible' => TRUE, '#group' => 'options', '#weight' => -50);
     $item->options = unserialize($item->options);
     $roles = user_roles(FALSE, 'view custom help text');
     // Get all Authenticated roles
     if (isset($roles[DRUPAL_AUTHENTICATED_RID])) {
         $roles += array_diff(user_roles(TRUE), $roles);
     }
     if (user_access('administer permissions')) {
         $permission_link = l(t('View custom help text'), 'admin/people/permissions', array('fragment' => 'module-custom_help_text'));
     } else {
         $permission_link = t('View custom help text');
     }
     $form['options_roles']['roles'] = array('#type' => 'checkboxes', '#options' => $roles, '#title' => t('User roles that can view the custom help text'), '#required' => TRUE, '#description' => t('Check the roles that needs to view the help message and have currently the permission \'!permission_url\'.', array('!permission_url' => $permission_link)));
     if (!empty($item->options['roles'])) {
         foreach ($item->options['roles'] as $role_name) {
             if ($role = user_role_load_by_name($role_name)) {
                 $form['options_roles']['roles']['#default_value'][] = $role->rid;
             }
         }
     } else {
         $form['options_roles']['roles']['#default_value'] = array();
     }
 }
 public function testGetUsersByRole()
 {
     $role = 'Review Manager';
     $users = OshaWorkflowPermissions::getUsersByRole($role);
     $this->assertNotEmpty($users);
     $role = user_role_load_by_name('Review Manager');
     $users = OshaWorkflowPermissions::getUsersByRole($role->rid);
     $this->assertNotEmpty($users);
 }
예제 #4
0
 /**
  * Load existing role from database
  *
  * @param NodeInterface $node
  * @param Context $context
  *
  * @return stdClass
  */
 protected function loadExistingRole(NodeInterface $node, Context $context)
 {
     switch ($node->getName()) {
         case 'anonymous':
             return user_role_load(DRUPAL_ANONYMOUS_RID);
         case 'authenticated':
             return user_role_load(DRUPAL_AUTHENTICATED_RID);
         default:
             return user_role_load_by_name($this->getRoleName($node, $context));
     }
 }
/**
 * Configure permissions.
 *
 * @todo this is here because I cannot add it inside module due to SQL error:
 * SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot
 * be null.
 *
 * {@inheritdoc}
 */
function osha_configure_permissions()
{
    if ($role = user_role_load_by_name('administrator')) {
        $vocabularies = array('activity', 'article_types', 'esener', 'nace_codes', 'section', 'thesaurus', 'wiki_categories', 'workflow_status', 'publication_types', 'newsletter_sections');
        $permissions = array();
        foreach ($vocabularies as $voc_name) {
            if ($voc = taxonomy_vocabulary_machine_name_load($voc_name)) {
                $permissions[] = 'add terms in ' . $voc_name;
                $permissions[] = 'edit terms in ' . $voc->vid;
                $permissions[] = 'delete terms in ' . $voc->vid;
            }
        }
        $permissions[] = 'access workbench access by role';
        $permissions[] = 'translate taxonomy_term entities';
        $permissions[] = 'edit any content in rejected';
        $permissions[] = 'edit any content in approved';
        $permissions[] = 'edit any content in final_draft';
        $permissions[] = 'edit any content in to_be_approved';
        // Workbench access permissions.
        $moderated_types = workbench_moderation_moderate_node_types();
        $transitions = workbench_moderation_transitions();
        foreach ($transitions as $transition) {
            $permissions[] = "moderate content from {$transition->from_name} to {$transition->to_name}";
            foreach ($moderated_types as $node_type) {
                //@todo: $permissions[] = "moderate $node_type state from {$transition->from_name} to {$transition->to_name}";
            }
        }
        $permissions[] = 'create moderators_group entity collections';
        $permissions[] = 'edit moderators_group entity collections';
        $permissions[] = 'view moderators_group entity collections';
        $permissions[] = 'delete moderators_group entity collections';
        $permissions[] = 'add content to moderators_group entity collections';
        $permissions[] = 'manage content in moderators_group entity collections';
        user_role_grant_permissions($role->rid, $permissions);
        user_role_revoke_permissions($role->rid, array('use workbench_moderation needs review tab'));
    }
    $roles = array(OSHA_WORKFLOW_ROLE_TRANSLATION_MANAGER, OSHA_WORKFLOW_ROLE_TRANSLATION_LIAISON, OSHA_WORKFLOW_ROLE_LAYOUT_VALIDATOR, OSHA_WORKFLOW_ROLE_CONTENT_VALIDATOR);
    foreach ($roles as $role_name) {
        if ($role = user_role_load_by_name($role_name)) {
            user_role_grant_permissions($role->rid, array('access workbench'));
        }
    }
}
 public function setUp()
 {
     // For benchmarking.
     $this->start = time();
     // Enable any modules required for the test.
     parent::setUp('better_exposed_filters', 'date', 'date_views', 'list', 'number', 'taxonomy', 'text', 'views', 'views_ui');
     // One of these days I'll figure out why Features is breaking all my tests.
     module_enable(array('bef_test_content'));
     // User with edit views perms
     $this->admin_user = $this->drupalCreateUser();
     $role = user_role_load_by_name('administrator');
     $this->assertTrue(!empty($role->rid), 'Found the "administrator" role.');
     user_save($this->admin_user, array('roles' => array($role->rid => $role->rid)));
     $this->drupalLogin($this->admin_user);
     // Build a basic view for use in tests.
     $this->createView();
     // $this->createDisplay('Page', array('path' => array('path' => 'bef_test_page')));
     // Add field to default display
     // $this->addField('node.title');
     // Turn of Better Exposed Filters
     $this->setBefExposedForm();
 }
예제 #7
0
function hoithi_preprocess_user_register_form(&$vars)
{
    //thisinh
    $thisinh_role = user_role_load_by_name('thisinh');
    if ($thisinh_role) {
        $vars['form']['account']['roles'][$thisinh_role->rid]['#checked'] = TRUE;
    }
    $vars['name'] = render($vars['form']['account']['name']);
    $vars['mail'] = render($vars['form']['account']['mail']);
    $vars['pass'] = render($vars['form']['account']['pass']);
    $vars['roles'] = render($vars['form']['account']['roles']);
    $vars['hovaten'] = render($vars['form']['field_hovaten']);
    $vars['hovaten'] = render($vars['form']['field_hovaten']);
    $vars['ngaysinh'] = render($vars['form']['field_ngaysinh']);
    $vars['gioitinh'] = render($vars['form']['field_gioitinh']);
    $vars['sodienthoai'] = render($vars['form']['field_sodienthoai']);
    $vars['socmnd'] = render($vars['form']['field_socmnd']);
    $vars['ngaycap'] = render($vars['form']['field_ngaycap']);
    $vars['noicap'] = render($vars['form']['field_noicap']);
    $vars['quequan'] = render($vars['form']['field_quequan']);
    //$vars['submit'] = render($vars['form']['actions']['submit']);
    $vars['rendered'] = drupal_render_children($vars['form']);
}
예제 #8
0
 /**
  * {@inheritDoc}
  */
 public function userAddRole(\stdClass $user, $role_name)
 {
     $role = user_role_load_by_name($role_name);
     if (!$role) {
         throw new \RuntimeException(sprintf('No role "%s" exists.', $role_name));
     }
     user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
 }
예제 #9
0
 /**
  * @Then /^the administrator role should have all permissions$/
  */
 public function theAdministratorRoleShouldHaveAllPermissions()
 {
     // Get list of all permissions
     $permissions = array();
     foreach (module_list(FALSE, FALSE, TRUE) as $module) {
         // Drupal 7
         if (module_invoke($module, 'permission')) {
             $permissions = array_merge($permissions, array_keys(module_invoke($module, 'permission')));
         }
     }
     $administrator_role = user_role_load_by_name('administrator');
     $administrator_perms = db_query("SELECT permission FROM {role_permission} WHERE rid = :admin_rid", array(':admin_rid' => $administrator_role->rid))->fetchCol();
     foreach ($permissions as $perm) {
         if (!in_array($perm, $administrator_perms)) {
             echo $perm;
             throw new Exception(sprintf("Administrator role missing permission %s", $perm));
         }
     }
 }
 /**
  * Create a user with a particular role.
  *
  * @param array|string $role_names
  *   String role or array of role names to assign to user. Note that the user
  *   always has the default permissions derived from the "authenticated users"
  *   role.
  * @param string $password
  *   Preferred password to set for the user.
  * @param array $edit_overrides
  *   Values for user or user profile fields to override.
  *
  * @return object|bool
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 protected function drupalCreateUserWithRoles($role_names = [], $password = NULL, $edit_overrides = [])
 {
     // Create a user assigned to that role.
     $edit = [];
     $edit['mail'] = Random::email();
     $edit['name'] = $edit['mail'];
     $edit['pass'] = is_null($password) ? user_password() : $password;
     $edit['status'] = 1;
     $edit['roles'] = [];
     if (!empty($role_names)) {
         $role_names = is_array($role_names) ? $role_names : [$role_names];
         foreach ($role_names as $rolename) {
             $role = user_role_load_by_name($rolename);
             $edit['roles'][$role->rid] = $role->name;
         }
     }
     // Merge fields with provided $edit_overrides.
     $edit_overrides = array_merge($edit, $edit_overrides);
     // Build an empty user object, including all default fields.
     $account = drupal_anonymous_user();
     $account->roles = array_merge($account->roles, $edit_overrides['roles']);
     foreach (field_info_instances('user', 'user') as $field_name => $info) {
         if (!isset($account->{$field_name})) {
             $account->{$field_name} = [];
         }
     }
     $account = user_save($account, $edit_overrides);
     if (empty($account->uid)) {
         return FALSE;
     }
     $account->pass_raw = $edit_overrides['pass'];
     $this->assertTrue(!empty($account->uid), t('User created with name %name (%uid) and pass %pass and roles %roles', ['%roles' => implode(', ', $role_names), '%name' => $edit['name'], '%uid' => $account->uid, '%pass' => $edit['pass']]), t('User login'));
     return $account;
 }
예제 #11
0
 /**
  * @Then /^I should not be able to change the "(?P<role_name>[^"]*)" role$/
  */
 public function iShouldNotBeAbleToChangeTheRole($role_name)
 {
     $administrator_role = user_role_load_by_name($role_name);
     $this->assertSession()->elementNotExists('css', '#edit-roles-change-' . $administrator_role->rid);
 }
예제 #12
0
 /**
  * @Given a/an :role user named :username exists
  */
 public function userOfRoleExists($role_name, $username)
 {
     $role = user_role_load_by_name($role_name);
     $user = (object) array('name' => $username, 'pass' => user_password(), 'email' => preg_replace('/\\s+/', '_', $username) . '@lacunastories.com', 'roles' => array($role->rid => $role->name));
     $this->userCreate($user);
 }
예제 #13
0
function _workflow_rebuild_roles(array $roles, array $role_map)
{
    // See also https://drupal.org/node/1702626 .
    $new_roles = array();
    foreach ($roles as $key => $rid) {
        if ($rid == -1) {
            $new_roles[$rid] = $rid;
        } else {
            if ($role = user_role_load_by_name($role_map[$rid])) {
                $new_roles[$role->rid] = $role->rid;
            }
        }
    }
    return $new_roles;
}
예제 #14
0
 /**
  * Converts an array of role ids or role names to an array of role_id =>
  * role_name key/paid values.
  *
  * @param array $roles
  *   An array of role ids or role names.
  *
  * @return array
  *   An associative array with role id as key and role name as value.
  *
  * @throws \Exception
  *   if provided role id or role name does not exist.
  */
 private static function formatRoles($roles)
 {
     if (is_string($roles) || is_numeric($roles)) {
         $roles = array($roles);
     }
     $output_roles = array();
     foreach ($roles as $rid) {
         if (is_numeric($rid) && ($role = user_role_load($rid))) {
             $output_roles[$role->rid] = $role->name;
         } elseif (is_string($rid) && ($role = user_role_load_by_name($rid))) {
             $output_roles[$role->rid] = $role->name;
         } else {
             throw new \Exception("Role {$rid} does not exist.");
         }
     }
     return $output_roles;
 }
예제 #15
0
 /**
  * Revoke permissions to a specific role, if it exists.
  *
  * @param string $role
  *    Role machine name.
  * @param string $permission
  *    Permission machine name.
  *
  * @return bool
  *    TRUE if operation was successful, FALSE otherwise.
  */
 public function revokePermission($role, $permission)
 {
     $role_object = user_role_load_by_name($role);
     if ($role_object) {
         user_role_revoke_permissions($role_object->rid, array($permission));
         return TRUE;
     } else {
         return FALSE;
     }
 }
예제 #16
0
function onelogin_saml_auth($auth)
{
    $username = '';
    $email = '';
    $autocreate = variable_get('saml_options_autocreate', FALSE);
    // Get the NameId.
    $nameId = $auth->getNameId();
    if (empty($nameId)) {
        drupal_set_message("A NameId could not be found. Please supply a NameId in your SAML Response.", 'error', FALSE);
        drupal_goto();
    }
    // Get SAML attributes
    $attrs = $auth->getAttributes();
    $usernameFromEmail = variable_get('saml_options_username_from_email', FALSE);
    if (!empty($attrs)) {
        $usernameMapping = variable_get('saml_attr_mapping_username');
        $mailMapping = variable_get('saml_attr_mapping_email');
        // Try to get $email and $username from attributes of the SAML Response
        if (!empty($usernameMapping) && isset($attrs[$usernameMapping]) && !empty($attrs[$usernameMapping][0])) {
            $username = $attrs[$usernameMapping][0];
        }
        if (!empty($mailMapping) && isset($attrs[$mailMapping]) && !empty($attrs[$mailMapping][0])) {
            $email = $attrs[$mailMapping][0];
        }
    }
    // If there are attrs but the mail is in NameID try to obtain it
    if (empty($email) && strpos($nameId, '@')) {
        $email = $nameId;
    }
    if (empty($username) && $usernameFromEmail) {
        $username = str_replace('@', '.', $email);
    }
    $matcher = variable_get('saml_options_account_matcher');
    if ($matcher == 'username') {
        if (empty($username)) {
            drupal_set_message("Username value not found on the SAML Response. Username was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an usermail.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('name', $username);
    } else {
        if (empty($email)) {
            drupal_set_message("Email value not found on the SAML Response. Email was selected as the account matcher field. Review at the settings the username mapping and be sure that the IdP provides this value", 'error', FALSE);
            drupal_goto();
        }
        // Query for active users given an e-mail address.
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'user')->propertyCondition('status', 1)->propertyCondition('mail', $email);
    }
    $syncroles = variable_get('saml_options_syncroles', FALSE);
    $roles = array();
    if ($syncroles) {
        // saml_attr_mapping_role
        $roleMapping = variable_get('saml_attr_mapping_role', '');
        if (!empty($roleMapping) && isset($attrs[$roleMapping]) && !empty($attrs[$roleMapping])) {
            $adminsRole = explode(',', variable_get('saml_role_mapping_administrator', ''));
            // Add here your customRoleMapping directly
            // $customRole = array ('value1', $value2);
            $administrator = user_role_load_by_name('administrator');
            $adminWeight = $administrator->rid;
            $roleWeight = 0;
            foreach ($attrs[$roleMapping] as $samlRole) {
                $samlRole = trim($samlRole);
                if (empty($samlRole)) {
                    break;
                } else {
                    if (in_array($samlRole, $adminsRole)) {
                        if ($roleWeight < $adminWeight) {
                            $roleWeight = $adminWeight;
                        }
                        break;
                    } else {
                        if ($loadedRole = user_role_load_by_name($samlRole)) {
                            $roles[$loadedRole->rid] = $loadedRole->name;
                        }
                    }
                }
            }
            switch ($roleWeight) {
                // case 5:
                //   $roles = array(5 => 'customrole');
                //   break;
                case $adminWeight:
                    $roles[$adminWeight] = 'administrator';
                    break;
                case DRUPAL_AUTHENTICATED_RID:
                    // default value => 2
                // default value => 2
                default:
                    $roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
                    break;
            }
        }
    }
    // If a user exists, attempt to authenticate.
    $result = $query->execute();
    if ($result && ($user = user_load(key($result['user'])))) {
        $GLOBALS['user'] = $user;
        $form_state['uid'] = $user->uid;
        if (!empty($roles)) {
            try {
                $fields = array('roles' => $roles);
                user_save($user, $fields);
            } catch (Exception $e) {
                return FALSE;
            }
        }
        user_login_finalize($form_state);
        user_cookie_save(array('drupal_saml_login' => '1'));
    } else {
        if ($autocreate) {
            // If auto-privisioning is enabled but there are no required attributes, we need to stop.
            if (empty($email) || empty($username)) {
                drupal_set_message("Auto-provisioning accounts requires a username and email address. Please supply both in your SAML response.", 'error', FALSE);
                drupal_goto();
            }
            $fields = array('name' => $username, 'mail' => $email, 'pass' => user_password(16), 'status' => 1, 'init' => $email, 'timezone' => date_default_timezone_get());
            if (!empty($roles)) {
                $fields['roles'] = $roles;
            }
            try {
                $user = user_save(NULL, $fields);
                $GLOBALS['user'] = $user;
                $form_state['uid'] = $user->uid;
                user_login_finalize($form_state);
                user_cookie_save(array('drupal_saml_login' => '1'));
            } catch (Exception $e) {
                return FALSE;
            }
        } else {
            drupal_set_message("User '" . ($matcher == 'username' ? $username : $email) . "' not found.", 'error', FALSE);
            drupal_goto();
        }
    }
}
예제 #17
0
function _workflow_rebuild_roles(array $roles, array $role_map)
{
    $cached_roles =& drupal_static(__FUNCTION__, array());
    // See also https://drupal.org/node/1702626 .
    $new_roles = array();
    foreach ($roles as $key => $rid) {
        if ($rid == -1) {
            $new_roles[$rid] = $rid;
        } else {
            if (!isset($cached_roles[$role_map[$rid]])) {
                if ($role = user_role_load_by_name($role_map[$rid])) {
                    $cached_roles[$role_map[$rid]] = $role->rid;
                    $new_roles[$role->rid] = $cached_roles[$role_map[$rid]];
                }
            } else {
                $new_roles[$rid] = $cached_roles[$role_map[$rid]];
            }
        }
    }
    return $new_roles;
}
예제 #18
0
 /**
  * {@inheritdoc}
  */
 public function roleDelete($role_name)
 {
     $role = user_role_load_by_name($role_name);
     user_role_delete((int) $role->rid);
 }
예제 #19
0
function bootstrap_theme_approve_contributor($account)
{
    global $user;
    $role = user_role_load_by_name(USER_TYPE_CONTRIBUTOR);
    $account->roles[$role->rid] = USER_TYPE_CONTRIBUTOR;
    user_save($account);
    bootstrap_theme_send_message($user, $account, 'You are now contributor.', 'You are now contributor.');
    drupal_goto('user/' . $account->uid);
}