function _scratchpadify_install_configure_form_submit($form, &$form_state)
{
    global $user;
    variable_set('site_name', $form_state['values']['site_name']);
    variable_set('site_mail', $form_state['values']['site_mail']);
    variable_set('date_default_timezone', $form_state['values']['date_default_timezone']);
    // Enable update.module if this option was selected.
    if ($form_state['values']['update_status_module'][1]) {
        // Stop enabling the update module, it's a right royal pain in the arse.
        //drupal_install_modules(array('update'));
    }
    // Turn this off temporarily so that we can pass a password through.
    variable_set('user_email_verification', FALSE);
    $form_state['old_values'] = $form_state['values'];
    $form_state['values'] = $form_state['values']['account'];
    // We precreated user 1 with placeholder values. Let's save the real values.
    $account = user_load(1);
    $merge_data = array('init' => $form_state['values']['mail'], 'roles' => array(), 'status' => 0);
    user_save($account, array_merge($form_state['values'], $merge_data));
    // Log in the first user.
    user_authenticate($form_state['values']);
    $form_state['values'] = $form_state['old_values'];
    unset($form_state['old_values']);
    variable_set('user_email_verification', TRUE);
    if (isset($form_state['values']['clean_url'])) {
        variable_set('clean_url', $form_state['values']['clean_url']);
    }
    // The user is now logged in, but has no session ID yet, which
    // would be required later in the request, so remember it.
    $user->sid = session_id();
    // Record when this install ran.
    variable_set('install_time', time());
}
 /**
  * Create a new user.
  *
  * @param array $data
  *   Array with the user's data from GitHub
  * @param array $options
  *   Options array as passed to drupal_http_request().
  * @param string $access_token
  *   The GitHub access token.
  *
  * @return \stdClass
  *   The newly saved user object.
  */
 protected function createUser($data, $options, $access_token)
 {
     $fields = array('name' => $data['login'], 'mail' => $this->getEmailFromGithub($options), 'pass' => user_password(8), 'status' => TRUE, 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'), '_github' => array('access_token' => $access_token, 'data' => $data));
     // The first parameter is left blank so a new user is created.
     $account = user_save('', $fields);
     return $account;
 }
Ejemplo n.º 3
0
/**
 * hook_ldapauth_create
 *
 * Ldapauth will invoke this after a new Drupal user has been created from
 * the LDAP data and saved.
 *
 * @param User $account The user object for the new user.
 */
function hook_ldapauth_create($account)
{
    // Some example code to create an e-mail if ldap didn't provide one
    if ($account->name == $account->mail) {
        user_save($account, array('mail' => $account->name . "@mydomain.com"));
    }
}
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function save($entity)
 {
     if ($entity instanceof User) {
         $entity->setIsNew(false);
     }
     return user_save($entity);
 }
function create_new_user(&$row)
{
    msg('create_new_user');
    if (!$row->is_cell_valid && !$row->is_email_valid) {
        msg("no email and no cell");
        $log = import_user_log_get_default($user->uid, $row->record_id, 'import', 'no-cell-or-email');
        import_user_log_insert($log);
        return false;
    }
    if (user_exists_by_phone($row)) {
        msg('user_exists_by_phone');
        return false;
    }
    if (user_exists_by_email($row)) {
        msg('user_exists_by_email');
        return false;
    }
    msg('creating');
    $log_type = 'import';
    $log_value = 'new';
    $existing_log = import_user_log_get_by_rid_type($row->record_id, $log_type);
    if ($existing_log) {
        msg('already have a log for this id,type ' . $row->record_id . ',' . $log_type);
        return false;
    }
    // cell
    $number = $row->cell;
    if (strlen($number) > 0) {
        $sms_user[0] = array(status => 2, number => $number);
    }
    // password
    // just a random sha hash including time so we can set the password
    // we don't know/don't care what it is
    // it's secure and will need to be reset by the user if they register via email later
    $token = base64_encode(hash_hmac('sha256', $number, drupal_get_private_key() . time(), TRUE));
    $token = strtr($token, array('+' => '-', '/' => '_', '=' => ''));
    $details = array('name' => strlen($row->handle) > 1 ? $row->handle . $row->record_id : $number, 'pass' => $token, 'mail' => $row->is_email_valid ? $row->email : $number, 'access' => 0, 'status' => 1, 'sms_user' => $sms_user);
    $user = user_save(null, $details);
    // set values for the imported profile fields
    healthimo_profile_save($user, 'profile_age', $row->age, null);
    healthimo_profile_save($user, 'profile_zip_code', $row->zip, null);
    healthimo_profile_save($user, 'profile_gender', $row->gender, null);
    healthimo_profile_save($user, 'profile_goal', $row->goal, null);
    healthimo_profile_save($user, 'profile_areas_of_interest_reply', $row->interest_areas, null);
    healthimo_profile_save($user, 'profile_areas_of_interest_diabetes', $row->interest_diabetes, null);
    //healthimo_profile_save($user, 'xxxxxxxxxxx', $row->interest_asthma, null);
    if ($user) {
        msg("import_user created user {$user->uid}");
        // link to import record
        $log = import_user_log_get_default($user->uid, $row->record_id, $log_type, $log_value);
        import_user_log_insert($log);
        print_r($user);
        return $user;
    }
    return false;
}
Ejemplo n.º 6
0
 function drupalLdapUpdateUser($edit = array(), $ldap_authenticated = FALSE, $user)
 {
     if (count($edit)) {
         $user = user_save($user, $edit);
     }
     if ($ldap_authenticated) {
         user_set_authmaps($user, array('authname_ldap_authentication' => $user->name));
     }
     return $user;
 }
Ejemplo n.º 7
0
 public function actionCreate()
 {
     if (isset($_POST['phone']) & isset($_POST['title']) & isset($_POST['content']) & isset($_POST['place']) & isset($_POST['create_time']) & isset($_POST['uid'])) {
         //用户积分修改
         $u = user_load($_POST['uid']);
         $edit = array('field_jifen' => array('und' => array(0 => array('value' => $u->field_jifen['und'][0]['value'] + 3))));
         user_save($u, $edit);
         $node->title = $_POST['title'];
         $node->field_phone['und'][0]['value'] = $_POST['phone'];
         $node->type = "sr";
         $node->body['und'][0]['value'] = $_POST['content'];
         $node->uid = $_POST['uid'];
         $node->language = 'zh-hans';
         $node->status = 0;
         //(1 or 0): published or not
         $node->promote = 0;
         //(1 or 0): promoted to front page
         $node->comment = 2;
         // 0 = comments disabled, 1 = read only, 2 = read/write
         //$node->field_riq['und'][0]['value'] =date('Y:m:d H:i:s');
         $node->field_riq['und'][0]['value'] = $_POST['create_time'];
         $node->field_src['und'][0]['value'] = $_POST['place'];
         $node->field_status['und'][0]['value'] = '处理中';
         //默认为匿名
         if (isset($_POST['name'])) {
             $node->field_shimin['und'][0]['value'] = $_POST['name'];
         }
         $image = CUploadedFile::getInstanceByName('img');
         if (is_object($image) && get_class($image) === 'CUploadedFile') {
             $dir = Yii::getPathOfAlias('webroot') . '/assets/urban/';
             //$ext = $image->getExtensionName();
             $fileName = uniqid() . '.jpg';
             $name = $dir . $fileName;
             $image->saveAs($name, true);
             $file = (object) array('uid' => $_POST['uid'], 'uri' => $name, 'filemime' => file_get_mimetype($filepath), 'status' => 1);
             $file = file_copy($file, 'public://pictures/urban');
             $node->field_tux['und'][0] = (array) $file;
         }
         $node = node_submit($node);
         // Prepare node for saving
         node_save($node);
         $basic = new basic();
         $basic->error_code = 0;
         //$basic->error_msg="no input parameters";
         $jsonObj = CJSON::encode($basic);
         echo $jsonObj;
     } else {
         $basic = new basic();
         $basic->error_code = 1;
         $basic->error_msg = "no input parameters";
         $jsonObj = CJSON::encode($basic);
         echo $jsonObj;
     }
 }
Ejemplo n.º 8
0
 /**
  * Assign a specific role to an user, give its UID.
  *
  * @param string $role_name
  *    Role machine name.
  * @param string $uid
  *    User UID.
  *
  * @return bool
  *    TRUE if operation was successful, FALSE otherwise.
  */
 public function assignRoleToUser($role_name, $uid)
 {
     $account = user_load($uid);
     $role = user_role_load_by_name($role_name);
     if ($role && $account) {
         $account->roles[$role->rid] = $role->name;
         user_save($account);
         return TRUE;
     }
     return FALSE;
 }
Ejemplo n.º 9
0
 public function postReset()
 {
     $drupal = new \erdiko\drupal\models\User();
     $account = \user_load_by_mail($_POST['mail']);
     $edit = array();
     if ($_POST['pass']['pass1'] == $_POST['pass']['pass2']) {
         $edit['pass'] = $_POST['pass']['pass1'];
         \user_save($account, $edit);
         $this->setContent('Your password was successfully changed.');
     } else {
         $this->setContent('The password and confirmation password do not match.');
     }
 }
 /**
  * Helper function that creates a user object with the given role.
  */
 protected function createUser($role)
 {
     $edit = array();
     $edit['name'] = $this->randomName();
     $edit['mail'] = $edit['name'] . '@example.com';
     // @todo role ids are completely broken, if modules are enable in the wrong
     // order.
     $edit['roles'] = array($role->rid => $role->name);
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     $user = user_save(drupal_anonymous_user(), $edit);
     $user->pass_raw = $edit['pass'];
     return $user;
 }
Ejemplo n.º 11
0
 /**
  * @Given I am logged in with new user :username
  */
 public function iAmLoggedInWithNewUser($username)
 {
     //This will generate a random password, you could set your own here
     $password = user_password(8);
     //set up the user fields
     $fields = array('name' => $username . user_password(), 'mail' => $username . '@email.com', 'pass' => $password, 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'));
     //the first parameter is left blank so a new user is created
     $account = user_save('', $fields);
     // Now for the actual login.
     $this->getSession()->visit('/user');
     $this->getSession()->getPage()->fillField('edit-name', $username);
     $this->getSession()->getPage()->fillField('edit-pass', $password);
     $this->getSession()->getPage()->pressButton('edit-submit');
 }
Ejemplo n.º 12
0
function create_drupal_user()
{
    $user_successfully_created = "false";
    $server_base = variable_get('apiary_research_base_url', 'http://localhost');
    include_once drupal_get_path('module', 'apiary_project') . '/apiaryPermissionsClass.php';
    $user_name = '';
    if (user_access(apiaryPermissionsClass::$ADMINISTER_APIARY)) {
        if (isset($_POST['name']) && $_POST['name'] != '') {
            if (isset($_POST['mail']) && $_POST['mail'] != '') {
                $name = $_POST['name'];
                $mail = $_POST['mail'];
                if (isset($_POST['pass']) && $_POST['pass'] != '') {
                    $pass = $_POST['pass'];
                    //using drupals user_save function does the md5 hash
                    //$pass = md5($_POST['pass']);
                } else {
                    $pass = user_password();
                    //drupal function to create a md5 hash password
                }
                $require_role_to_use_apiary_workflow = 'administrator';
                //this gets assigned to the created user
                $results = db_query("SELECT rid FROM {role} WHERE NAME='%s'", $require_role_to_use_apiary_workflow);
                $result = db_fetch_object($results);
                $rid = $result->rid;
                $newuser = array('name' => $name, 'mail' => $mail, 'status' => 1, 'pass' => $pass, 'roles' => array($rid => $require_role_to_use_apiary_workflow));
                $new_user = user_save('', $newuser);
                if ($new_user != false) {
                    $user_successfully_created = "true";
                    $user_name = $name;
                    $msg = "User " . $new_user->name . " successfully created.";
                } else {
                    $msg = "User " . $new_user->name . " failed to be created.";
                }
            } else {
                $msg = "No e-mail address was provided.";
            }
        } else {
            $msg = "No username was provided.";
        }
    } else {
        $msg = "You do not have permissions to create new users.";
    }
    $returnJSON['user_name'] = $user_name;
    $returnJSON['user_successfully_created'] = $user_successfully_created;
    $returnJSON['msg'] = $msg;
    echo json_encode($returnJSON);
}
Ejemplo n.º 13
0
function install()
{
    // @TODO Replace this table to one function.
    db_query('DROP TABLE IF EXISTS `permissions`');
    db_query('CREATE TABLE `permissions` (`rid` int NOT NULL, `type` varchar(255) CHARACTER SET utf8 NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8');
    db_query('INSERT INTO `permissions` (`rid`, `type`) VALUES (\'1\', \'user anonymous\')');
    db_query('INSERT INTO `permissions` (`rid`, `type`) VALUES (\'2\', \'user authorized\')');
    db_query('DROP TABLE IF EXISTS `roles`');
    db_query('CREATE TABLE `roles` (`rid` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) CHARACTER SET utf8 NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8');
    db_query('INSERT INTO `roles` (`rid`, `name`) VALUES (\'1\', \'Aнонимный\')');
    db_query('INSERT INTO `roles` (`rid`, `name`) VALUES (\'2\', \'Авторизованный\')');
    db_query('INSERT INTO `roles` (`rid`, `name`) VALUES (\'3\', \'Редактор\')');
    entity_create('users');
    $admin = (object) array('name' => array('Artem'), 'mail' => array('*****@*****.**'), 'password' => array('123456'));
    user_save($admin);
    $editor = (object) array('name' => array('Редактор Стас'), 'mail' => array('*****@*****.**'), 'password' => array('654321'), 'roles' => array(2 => 2, 3 => 3));
    user_save($editor);
}
Ejemplo n.º 14
0
 /**
  * Setup the test.
  */
 function setUp()
 {
     parent::setUp('block_test');
     // Create an admin user, log in and enable test blocks.
     $this->admin_user = $this->drupalCreateUser(array('administer blocks', 'access administration pages'));
     $this->drupalLogin($this->admin_user);
     // Create additional users to test caching modes.
     $this->normal_user = $this->drupalCreateUser();
     $this->normal_user_alt = $this->drupalCreateUser();
     // Sync the roles, since drupalCreateUser() creates separate roles for
     // the same permission sets.
     user_save($this->normal_user_alt, array('roles' => $this->normal_user->roles));
     $this->normal_user_alt->roles = $this->normal_user->roles;
     // Enable block caching.
     variable_set('block_cache', TRUE);
     // Enable our test block.
     $edit['block_test_test_cache[region]'] = 'sidebar_first';
     $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
 }
Ejemplo n.º 15
0
 public function run($args)
 {
     //$users=Yw::model()->findAll();
     $criteria = new CDbCriteria();
     $criteria->condition = 'type=:type AND id<=:idmax AND id>:idmin';
     $criteria->params = array(':type' => 0, ':idmax' => 60000, ':idmin' => 50000);
     $criteria->order = 'id ASC';
     $users = User::model()->findAll($criteria);
     foreach ($users as $user) {
         $account = new stdClass();
         $account->name = $user->account;
         $account->pass = $user->psw;
         $account->field_nick['und'][0]['value'] = $user->nick;
         $account->mail = $user->account . '@sina.com';
         $roles = array(4 => true);
         $account->roles = $roles;
         $account = user_save($account);
         unset($account);
     }
 }
 /**
  * Tests authorization.
  */
 public function testAuthorize()
 {
     // Create a user with limited permissions. We can't use
     // $this->drupalCreateUser here because we need to to set a specific user
     // name.
     $edit = array('name' => 'Poor user', 'mail' => '*****@*****.**', 'pass' => user_password(), 'status' => 1);
     $account = user_save(drupal_anonymous_user(), $edit);
     // // Adding a mapping to the user_name will invoke authorization.
     $this->addMappings('comment', array(5 => array('source' => 'mail', 'target' => 'user_mail')));
     $url = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds_comment_processor') . '/tests/test.csv';
     $nid = $this->createFeedNode('comment', $url, 'Comment test');
     $this->assertText('Failed importing 1 comment');
     $this->assertText('User ' . $account->name . ' is not permitted to post comments.');
     $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {comment}")->fetchField());
     user_role_change_permissions(2, array('post comments' => TRUE));
     $this->drupalPost("node/{$nid}/import", array(), 'Import');
     $this->assertText('Created 1 comment.');
     $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {comment}")->fetchField());
     $comment = comment_load(1);
     $this->assertEqual(0, $comment->status);
 }
 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();
 }
Ejemplo n.º 18
0
function createNewUser($form_state)
{
    //This will generate a random password, you could set your own here
    $password = user_password(8);
    $userName = $form_state['values']['firstName'] . ' ' . $form_state['values']['lastName'];
    //set up the user fields
    $fields = array('name' => $form_state['values']['primaryEmail'], 'mail' => $form_state['values']['primaryEmail'], 'pass' => $password, 'status' => 1, 'init' => 'email address', 'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user'));
    //the first parameter is left blank so a new user is created
    $account = user_save('', $fields);
    // Manually set the password so it appears in the e-mail.
    $account->password = $fields['pass'];
    // Send the e-mail through the user module.
    $params['url'] = user_pass_reset_url($account);
    $params['teamName'] = dbGetTeamName($form_state['TID']);
    drupal_mail('users', 'userCreated', $form_state['values']['primaryEmail'], NULL, $params, '*****@*****.**');
    $fields = array('firstName', 'lastName');
    $profileData = getFields($fields, $form_state['values']);
    $profileData = stripTags($profileData, '');
    $profileData['UID'] = $account->uid;
    dbCreateProfile($profileData);
    // creating new profile
    return $profileData['UID'];
}
 /**
  * Overrides Entity::save().
  *
  * Maintains the role, adding or removing it from the owner when necessary.
  */
 public function save()
 {
     if ($this->uid && $this->product_id) {
         $role = $this->wrapper->product->commerce_license_role->value();
         $owner = $this->wrapper->owner->value();
         $save_owner = FALSE;
         if (!empty($this->license_id)) {
             $this->original = entity_load_unchanged('commerce_license', $this->license_id);
             // A plan change occurred. Remove the previous role.
             if ($this->original->product_id && $this->product_id != $this->original->product_id) {
                 $previous_role = $this->original->wrapper->product->commerce_license_role->value();
                 if (isset($owner->roles[$previous_role])) {
                     unset($owner->roles[$previous_role]);
                     $save_owner = TRUE;
                 }
             }
         }
         // The owner of an active license must have the role.
         if ($this->status == COMMERCE_LICENSE_ACTIVE) {
             if (!isset($owner->roles[$role])) {
                 $owner->roles[$role] = $role;
                 $save_owner = TRUE;
             }
         } elseif ($this->status > COMMERCE_LICENSE_ACTIVE) {
             // The owner of an inactive license must not have the role.
             if (isset($owner->roles[$role])) {
                 unset($owner->roles[$role]);
                 $save_owner = TRUE;
             }
         }
         // If a role was added or removed, save the owner.
         if ($save_owner) {
             user_save($owner);
         }
     }
     parent::save();
 }
function brukar_client_login($data)
{
    global $user;
    $edit = array('name' => t(variable_get('brukar_name', '!name'), array('!name' => $data['name'], '!sident' => substr($data['id'], 0, 4), '!ident' => $data['id'])), 'mail' => $data['mail'], 'status' => 1, 'data' => array('brukar' => $data));
    if ($user->uid != 0) {
        user_save($user, $edit);
        user_set_authmaps($user, array('authname_brukar' => $data['id']));
        drupal_goto('user');
    }
    $authmap_user = db_query('SELECT uid FROM {authmap} WHERE module = :module AND authname = :ident', array(':ident' => $data['id'], ':module' => 'brukar'))->fetch();
    if ($authmap_user === FALSE) {
        $provided = module_invoke_all('brukar_client_user', $edit);
        $user = !empty($provided) ? $provided[0] : user_save(user_load_by_mail($data['mail']), $edit);
        user_set_authmaps($user, array('authname_brukar' => $data['id']));
    } else {
        $user = user_save(user_load($authmap_user->uid), $edit);
    }
    $form_state = (array) $user;
    user_login_submit(array(), $form_state);
    // Better solution available?
    $query = $_GET;
    unset($query['q']);
    drupal_goto($_GET['q'] == variable_get('site_frontpage') ? '<front>' : url($_GET['q'], array('absolute' => TRUE, 'query' => $query)));
}
Ejemplo n.º 21
0
/**
 * Save the user initially.
 *
 * @param object $user
 *   Values to store in user object.
 * @param array $role
 *   Role given to all imported users.
 *
 * @return object $account
 *   Drupal user object.
 */
function import_users_save_user_init($user, $roles)
{
    if (empty($user->name) || empty($user->pass)) {
        return FALSE;
    }
    $account = new stdClass();
    $account->is_new = TRUE;
    $account->name = $user->name;
    $account->mail = $account->init = $user->mail;
    $account->status = TRUE;
    $account->roles = $roles;
    if (!empty($user->created)) {
        $account->created = $user->created;
    }
    $account->timezone = variable_get('date_default_timezone', '');
    return user_save($account, array('pass' => $user->pass));
}
 /**
  * Create a user with a given set of permissions. The permissions correspond to the
  * names given on the privileges page.
  *
  * @param $role
  *   Role for the user: admin, manager, user
  * @param $groups
  *   Optional: An array of group nids or group node objects to which the newly
  *   created account should be a member of.
  * @return
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 function atriumCreateUser($role = 'user', $groups = array())
 {
     // Abbreviate 'authenticated user' to just 'user'.
     $role = $role === 'user' ? 'authenticated user' : $role;
     $rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role));
     if ($rid) {
         // Create a user assigned to that role.
         $edit = array();
         $edit['name'] = $this->randomName();
         $edit['mail'] = $edit['name'] . '@example.com';
         $edit['roles'] = array($rid => $rid);
         $edit['pass'] = user_password();
         $edit['status'] = 1;
         $account = user_save('', $edit);
         // Add groups.
         if (!empty($account->uid) && !empty($groups)) {
             foreach ($groups as $value) {
                 $gid = is_object($value) && !empty($value->nid) ? $value->nid : $value;
                 og_save_subscription($gid, $account->uid, array('is_active' => TRUE));
             }
             // Reload user account with OG associations.
             og_get_subscriptions($account->uid, 1, TRUE);
             // Reset static cache.
             $account = user_load($account->uid);
         }
         $this->assertTrue(!empty($account->uid), t('User created with name %name, pass %pass and mail %mail', array('%name' => $edit['name'], '%pass' => $edit['pass'], '%mail' => $edit['mail'])), t('User login'));
         if (!empty($account->uid)) {
             // Add the raw password so that we can log in as this user.
             $account->pass_raw = $edit['pass'];
             return $account;
         }
     }
     return FALSE;
 }
 /**
  * Create a user with a given set of permissions. The permissions correspond to the
  * names given on the privileges page.
  *
  * @param $permissions
  *   Array of permission names to assign to user.
  * @return
  *   A fully loaded user object with pass_raw property, or FALSE if account
  *   creation fails.
  */
 protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'skip comment approval'))
 {
     // Create a role with the given permission set.
     if (!($rid = $this->drupalCreateRole($permissions))) {
         return FALSE;
     }
     // Create a user assigned to that role.
     $edit = array();
     $edit['name'] = $this->randomName();
     $edit['mail'] = $edit['name'] . '@example.com';
     $edit['roles'] = array($rid => $rid);
     $edit['pass'] = user_password();
     $edit['status'] = 1;
     $account = user_save(drupal_anonymous_user(), $edit);
     $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
     if (empty($account->uid)) {
         return FALSE;
     }
     // Add the raw password so that we can log in as this user.
     $account->pass_raw = $edit['pass'];
     return $account;
 }
Ejemplo n.º 24
0
			<?php 
}
?>
		</ul>
	</nav>

	<section>
	<?php 
if (logged_in() && isset(user()->saved_status_messages)) {
    if (is_array($_SESSION['status_messages'])) {
        $_SESSION['status_messages'] = array_merge($_SESSION['status_messages'], user()->saved_status_messages);
    } else {
        $_SESSION['status_messages'] = user()->saved_status_messages;
    }
    unset(user()->saved_status_messages);
    user_save();
}
if (isset($_SESSION['status_messages']) && $_SESSION['status_messages']) {
    ?>
			<ul id="status">
			<?php 
    foreach ($_SESSION['status_messages'] as $message) {
        echo '<li>' . $message . '</li>';
    }
    ?>
			</ul>
		<?php 
    $displayed_status_messages = count($_SESSION['status_messages']);
}
if (file_exists(basename($q) . '.inc.php')) {
    require basename($q) . '.inc.php';
Ejemplo n.º 25
0
/**
 * Verify user and update user's status
 * @param       params  User fields, includes email
 */
function civicrm_drupal_user_update_and_redirect($params)
{
    global $user;
    if (!($params['email'] && $params['drupalID'] && $params['password'])) {
        return false;
    }
    $user_fields['uid'] = $params['drupalID'];
    $user_fields['mail'] = $params['email'];
    $user = user_load($user_fields);
    if (!$user->uid) {
        return false;
    }
    $update = array();
    $update['status'] = 1;
    $update['pass'] = $params['password'];
    $user = user_save($user, $update);
    // Login the user
    $edit = array();
    user_module_invoke('login', $edit, $user);
    // redirect user to locker
    drupal_goto('locker');
}
Ejemplo n.º 26
0
 public function submitPassword($password, $userId)
 {
     $account = \user_load($userId);
     // actually returns a user object but can be used as an account object
     //$newhash = \user_hash_password($password);
     $user = \user_save($account, $edit = array('pass' => $password), $category = 'account');
     return $user;
     if ($user) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 27
0
 function updateCMSName($ufID, $ufName)
 {
     // CRM-5555
     if (function_exists('user_load')) {
         $user = user_load($ufID);
         if ($user->mail != $ufName) {
             user_save($user, array('mail' => $ufName));
             $user = user_load($ufID);
         }
     }
 }
/**
 * Create a new user based on informations from the Shibboleth handler if it's necessary or log in.
 *
 * If already authenticated - do nothing
 * If Shibboleth doesn't provide User information - error message
 * Else if user exists, and mail override (shib_auth_req_shib_only) enabled, override existing user info
 * If not exists, and Shibboleth provides mail address, create an account for this user
 * If there's no mail attribute, ask for the mail address on a generated form if mail override (shib_auth_req_shib_only) is disabled
 * In this case, the account will be created with this e-mail address.
 *
 * This function also gives roles to the user, if certain server fields were provided by the Shibboleth server
 */
function shib_auth_init()
{
    global $user;
    $shib_headers_exist = $_SERVER['HTTP_SHIB_IDENTITY_PROVIDER'] || $_SERVER['Shib-Identity-Provider'];
    if (shib_auth_isDebug()) {
        $debug_message = print_r($_SERVER, TRUE);
        drupal_set_message('<pre>' . $debug_message . '</pre>');
    }
    // if the user IS logged in as non-admin, but we're missing Shibboleth identity
    if (!$shib_headers_exist && $_SESSION['authentication'] == 'shib_auth' && variable_get('shib_auth_auto_destroy_session', FALSE) && $user->uid && $user->uid != 1) {
        drupal_set_message(t('Your session is expired. Please log in again!'), "error");
        unset($_SESSION['authentication']);
        session_destroy();
        $user = drupal_anonymous_user();
    }
    $uname = $_SERVER[variable_get('shib_auth_username_variable', 'REMOTE_USER')];
    $umail = $_SERVER[variable_get('shib_auth_username_email', 'HTTP_SHIB_MAIL')];
    $umail_single = preg_replace('/;.*/', '', $umail);
    // Ensure that the user is the same as the one who has initiated the session
    if (isset($_SESSION['uname'])) {
        if ($_SESSION['uname'] != $uname) {
            unset($_SESSION['authentication']);
            unset($_SESSION['uname']);
            session_destroy();
            $user = drupal_anonymous_user();
        }
    } else {
        $_SESSION['uname'] = $uname;
    }
    // If
    // - The user isn't logged in
    // - There is Shibboleth authentication in the background
    // - The settings are fine and there has been a valid username set up
    // - The settings are fine and there has been a valid user email address set up
    if (!$user->uid && $shib_headers_exist) {
        //If custom mail form will be generated, generate it only once
        if (isset($_SESSION['redirected_to_custom_mail_form']) && $_SESSION['redirected_to_custom_mail_form']) {
            unset($_SESSION['redirected_to_custom_mail_form']);
        } else {
            //Shib didn't provide username, or the admin gave wrong server variable on the shib config form
            if (!$uname) {
                $message = t('Username is missing. Please contact your Shibboleth administrator!');
                drupal_set_message($message, "error");
                watchdog('shib_auth', $message, WATCHDOG_CRITICAL);
            } else {
                $username_query = db_query("SELECT * FROM {users} WHERE name='%s'", $uname);
                $new_user = !db_fetch_object($username_query);
                //The user exists in the drupal user database, login her
                if (!$new_user) {
                    user_external_login_register($uname, "shib_auth");
                    $_SESSION['authentication'] = 'shib_auth';
                    //if we have an e-mail address from the shib server
                    if ($umail_single) {
                        //and the Shibboleth mail address override was enabled in the admin config
                        if (variable_get('shib_auth_mail_shib_only', 0) == 0) {
                            //check if there isn't any user with this e-mail (whose name is different)
                            $email_for_other_user_query = db_query("SELECT * FROM {users} WHERE mail='%s' AND name <> '%s'", $umail_single, $uname);
                            $email_for_other_user = db_fetch_object($username_and_email_query);
                            if ($email_for_other_user) {
                                drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error');
                            } else {
                                $user = user_save($user, array('mail' => $umail_single));
                            }
                        }
                    }
                } else {
                    //If we have an e-mail address from the shib server, and there isn't any user with this address, create an account with these infos
                    if ($umail_single) {
                        $email_already_used_query = db_query("SELECT * FROM {users} WHERE mail='%s'", $umail_single);
                        $email_already_used = db_fetch_object($email_already_used_query);
                        // If the mail address is used, give an error
                        if ($email_already_used) {
                            drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error');
                        } else {
                            user_external_login_register($uname, "shib_auth");
                            $_SESSION['authentication'] = 'shib_auth';
                            $user = user_save($user, array('mail' => $umail_single));
                        }
                    } else {
                        if (variable_get('shib_auth_mail_shib_only', 0) == 0) {
                            $message = t('E-mail address is missing. Please contact your Shibboleth administrator!');
                            drupal_set_message($message, "error");
                            watchdog('shib_auth', $message, WATCHDOG_CRITICAL);
                        } else {
                            // if the custom mail was enabled on the admin form
                            if ($_POST['form_id'] == 'shib_auth_custom_email' && $_POST['custom_mail']) {
                                $custom_mail = $_POST['custom_mail'];
                            }
                            //if the user provided the custom mail string, and it is not empty
                            if (isset($custom_mail) && $custom_mail) {
                                // and it isn't used by another registered drupal user
                                $email_already_used_query = db_query("SELECT * FROM {users} WHERE mail='%s'", $custom_mail);
                                $email_already_used = db_fetch_object($email_already_used_query);
                                if ($email_already_used) {
                                    drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error');
                                } else {
                                    user_external_login_register($uname, "shib_auth");
                                    $_SESSION['authentication'] = 'shib_auth';
                                    $user = user_save($user, array('mail' => $custom_mail));
                                }
                                //then the user is redirected to the page, which she wanted to open before the auth process had been initiated
                                if (isset($_SESSION['redirected_to_custom_mail_form_url'])) {
                                    $redirect_url = $_SESSION['redirected_to_custom_mail_form_url'];
                                    unset($_SESSION['redirected_to_custom_mail_form_url']);
                                    drupal_goto($redirect_url);
                                }
                            } else {
                                $_SESSION['redirected_to_custom_mail_form'] = TRUE;
                                $_SESSION['redirected_to_custom_mail_form_url'] = $_GET['q'];
                                drupal_goto('shib_auth/get_custom_mail');
                            }
                        }
                    }
                }
            }
        }
    }
    //The admin can define authorization rules based on the server variables - which are provided by Shibboleth -
    //to give roles to users, if the IdP provide certain authorization or authentication string
    //the rules can be defined as a server field - Regexp - role(s) trio
    // Store rules for further examination
    $former_rules = serialize($user->roles);
    // Examine all previously saved rule
    $rules = db_query("SELECT * FROM {shib_auth}");
    while ($rule = db_fetch_array($rules)) {
        $fieldname = $rule['field'];
        $expression = '/' . urldecode($rule['regexpression']) . '/';
        //check out, if the given server field exists
        if (isset($_SERVER[$fieldname])) {
            foreach (explode(';', $_SERVER[$fieldname]) as $value) {
                //check if the RegEx can be fit to one of the value of the server field
                if (preg_match($expression, trim($value))) {
                    $roles = unserialize(urldecode($rule['role']));
                    //if there is a match, give this user the specified role(s)
                    if (!empty($roles)) {
                        foreach ($roles as $key => $value) {
                            $user->roles[$key] = $value;
                        }
                    }
                }
            }
        }
    }
    $user->roles = array_filter($user->roles);
    // If the user roles array has been changed then reset the permission cache
    if (serialize($user->roles) != $former_rules) {
        // Hack to reset the permissions
        user_access('access content', $account, TRUE);
    }
}
Ejemplo n.º 29
0
 /**
  * {@inheritDoc}
  */
 public function userCreate(\stdClass $user)
 {
     // Default status to TRUE if not explicitly creating a blocked user.
     if (!isset($user->status)) {
         $user->status = 1;
     }
     // Convert roles to proper structure.
     if (isset($user->roles)) {
         foreach ($user->roles as $key => $rid) {
             $role = user_role_load($rid);
             unset($user->roles[$key]);
             $user->roles[$rid] = $role->name;
         }
     }
     // Clone user object, otherwise user_save() changes the password to the
     // hashed password.
     $account = clone $user;
     user_save($account, (array) $user);
     // Store UID.
     $user->uid = $account->uid;
 }
Ejemplo n.º 30
0
 /**
  * Create missed Drupal accounts 
  * 
  * @return void
  */
 protected function createMissedDrupalAccounts()
 {
     if (!defined('LC_SUPPRESS_EMAIL_ALREADY_EXISTS_MESSAGE')) {
         define('LC_SUPPRESS_EMAIL_ALREADY_EXISTS_MESSAGE', true);
     }
     foreach ($this->accountsMissedInDrupal as $k => $account) {
         if ($this->checkUserAccountsPerStepCounter()) {
             $newAccount = new \stdclass();
             $newAccountData = array('is_new' => true, 'name' => $this->getNameFromEmail($account['login']), 'mail' => $account['login'], 'pass' => user_password(), 'status' => true);
             if (user_save($newAccount, $newAccountData)) {
                 $this->drupalAccountNames[] = $newAccount->name;
                 \XLite\Core\Database::getRepo('XLite\\Model\\Profile')->linkProfiles(\XLite\Core\Database::getRepo('XLite\\Model\\Profile')->find($account['profile_id']), $newAccount->uid);
                 if (variable_get('lc_user_sync_notify', false)) {
                     // Send notification with one time login URL and instructions
                     _user_mail_notify('password_reset', $newAccount);
                 }
                 unset($this->accountsMissedInDrupal[$k]);
             }
         } else {
             break;
         }
     }
 }