Esempio n. 1
0
function adduser_validate(Pieform $form, $values)
{
    global $USER, $TRANSPORTER;
    $authobj = AuthFactory::create($values['authinstance']);
    $institution = $authobj->institution;
    // Institutional admins can only set their own institutions' authinstances
    if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }
    $institution = new Institution($authobj->institution);
    // Don't exceed max user accounts for the institution
    if ($institution->isFull()) {
        $institution->send_admin_institution_is_full_message();
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
    }
    $username = $values['username'];
    $firstname = sanitize_firstname($values['firstname']);
    $lastname = sanitize_lastname($values['lastname']);
    $email = sanitize_email($values['email']);
    $password = $values['password'];
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
        }
    }
    if (method_exists($authobj, 'is_username_valid_admin')) {
        if (!$authobj->is_username_valid_admin($username)) {
            $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
        }
    } else {
        if (method_exists($authobj, 'is_username_valid')) {
            if (!$authobj->is_username_valid($username)) {
                $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
            }
        }
    }
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }
    if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
        $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
    }
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
        if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) {
            $form->reply(PIEFORM_ERR, array('message' => get_string('uploadedfiletoobig'), 'goto' => '/admin/users/add.php'));
            $form->set_error('leap2afile', get_string('uploadedfiletoobig'));
            return;
        } else {
            if (!$values['leap2afile']) {
                $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
                return;
            }
        }
        if ($values['leap2afile']['type'] == 'application/octet-stream') {
            require_once 'file.php';
            $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
        } else {
            $mimetype = trim($values['leap2afile']['type'], '"');
        }
        $date = time();
        $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
        safe_require('import', 'leap');
        $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
        $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
        try {
            $TRANSPORTER->extract_file();
            PluginImportLeap::validate_transported_data($TRANSPORTER);
        } catch (Exception $e) {
            $form->set_error('leap2afile', $e->getMessage());
        }
    } else {
        if (!$form->get_error('firstname') && empty($firstname)) {
            $form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('lastname') && empty($lastname)) {
            $form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('email')) {
            if (!$form->get_error('email') && empty($email)) {
                $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
            }
            if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
                $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
            }
        }
    }
}
Esempio n. 2
0
/**
 * Called when the login form is submitted. Validates the user and password, and
 * if they are valid, starts a new session for the user.
 *
 * @param object $form   The Pieform form object
 * @param array  $values The submitted values
 * @access private
 */
function login_submit(Pieform $form, $values)
{
    global $SESSION, $USER;
    $username = trim($values['login_username']);
    $password = $values['login_password'];
    $authenticated = false;
    try {
        $authenticated = $USER->login($username, $password);
        if (empty($authenticated)) {
            $SESSION->add_error_msg(get_string('loginfailed'));
            return;
        }
    } catch (AuthUnknownUserException $e) {
        // If the user doesn't exist, check for institutions that
        // want to create users automatically.
        try {
            // Reset the LiveUser object, since we are attempting to create a
            // new user
            $SESSION->destroy_session();
            $USER = new LiveUser();
            $authinstances = get_records_sql_array("\n                SELECT a.id, a.instancename, a.priority, a.authname, a.institution, i.suspended, i.displayname\n                FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name\n                WHERE a.authname != 'internal'\n                ORDER BY a.institution, a.priority, a.instancename", null);
            if ($authinstances == false) {
                throw new AuthUnknownUserException("\"{$username}\" is not known");
            }
            $USER->username = $username;
            reset($authinstances);
            while ((list(, $authinstance) = each($authinstances)) && false == $authenticated) {
                $auth = AuthFactory::create($authinstance->id);
                if (!$auth->can_auto_create_users()) {
                    continue;
                }
                // catch semi-fatal auth errors, but allow next auth instance to be
                // tried
                try {
                    if ($auth->authenticate_user_account($USER, $password)) {
                        $authenticated = true;
                    } else {
                        continue;
                    }
                } catch (AuthInstanceException $e) {
                    continue;
                }
                // Check now to see if the institution has its maximum quota of users
                require_once 'institution.php';
                $institution = new Institution($authinstance->institution);
                if ($institution->isFull()) {
                    $institution->send_admin_institution_is_full_message();
                    throw new AuthUnknownUserException('Institution has too many users');
                }
                $USER->authinstance = $authinstance->id;
                $userdata = $auth->get_user_info($username);
                if (empty($userdata)) {
                    throw new AuthUnknownUserException("\"{$username}\" is not known");
                }
                // Check for a suspended institution
                if ($authinstance->suspended) {
                    $sitename = get_config('sitename');
                    throw new AccessTotallyDeniedException(get_string('accesstotallydenied_institutionsuspended', 'mahara', $authinstance->displayname, $sitename));
                }
                // We have the data - create the user
                $USER->lastlogin = db_format_timestamp(time());
                if (isset($userdata->firstname)) {
                    $USER->firstname = sanitize_firstname($userdata->firstname);
                }
                if (isset($userdata->lastname)) {
                    $USER->lastname = sanitize_firstname($userdata->lastname);
                }
                if (isset($userdata->email)) {
                    $USER->email = sanitize_email($userdata->email);
                } else {
                    // The user will be asked to populate this when they log in.
                    $USER->email = null;
                }
                $profilefields = array();
                foreach (array('studentid', 'preferredname') as $pf) {
                    if (isset($userdata->{$pf})) {
                        $sanitize = 'sanitize_' . $pf;
                        if (($USER->{$pf} = $sanitize($userdata->{$pf})) !== '') {
                            $profilefields[$pf] = $USER->{$pf};
                        }
                    }
                }
                try {
                    // If this authinstance is a parent auth for some xmlrpc authinstance, pass it along to create_user
                    // so that this username also gets recorded as the username for sso from the remote sites.
                    $remoteauth = $auth->is_parent_authority();
                    create_user($USER, $profilefields, $institution, $remoteauth);
                    $USER->reanimate($USER->id, $authinstance->id);
                } catch (Exception $e) {
                    db_rollback();
                    throw $e;
                }
            }
            if (!$authenticated) {
                $SESSION->add_error_msg(get_string('loginfailed'));
                return;
            }
        } catch (AuthUnknownUserException $e) {
            // We weren't able to authenticate the user for some reason that
            // probably isn't their fault (e.g. ldap extension not available
            // when using ldap authentication)
            log_info($e->getMessage());
            $SESSION->add_error_msg(get_string('loginfailed'));
            return;
        }
    }
    auth_check_admin_section();
    // This is also checked in $USER->login(), but it's good to check it again here in case a buggy auth plugin
    // lets a suspended user through somehow.
    ensure_user_account_is_active();
    // User is allowed to log in
    //$USER->login($userdata);
    auth_check_required_fields();
}
Esempio n. 3
0
 /**
  * Create a test user
  * @param array $record
  * @throws SystemException if creating failed
  * @return int new user id
  */
 public function create_user($record)
 {
     // Data validation
     // Set default auth method for a new user is 'internal' for 'No institution' if not set
     if (empty($record['institution']) || empty($record['authname'])) {
         $record['institution'] = 'mahara';
         $record['authname'] = 'internal';
     }
     if (!($auth = get_record('auth_instance', 'institution', $record['institution'], 'authname', $record['authname']))) {
         throw new SystemException("The authentication method authname" . $record['authname'] . " for institution '" . $record['institution'] . "' does not exist.");
     }
     $record['authinstance'] = $auth->id;
     // Don't exceed max user accounts for the institution
     $institution = new Institution($record['institution']);
     if ($institution->isFull()) {
         throw new SystemException("Can not add new users to the institution '" . $record['institution'] . "' as it is full.");
     }
     $record['firstname'] = sanitize_firstname($record['firstname']);
     $record['lastname'] = sanitize_lastname($record['lastname']);
     $record['email'] = sanitize_email($record['email']);
     $authobj = AuthFactory::create($auth->id);
     if (method_exists($authobj, 'is_username_valid_admin') && !$authobj->is_username_valid_admin($record['username'])) {
         throw new SystemException("New username'" . $record['username'] . "' is not valid.");
     }
     if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($record['username'])) {
         throw new SystemException("New username'" . $record['username'] . "' is not valid.");
     }
     if (record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($record['username'])))) {
         throw new ErrorException("The username'" . $record['username'] . "' has been taken.");
     }
     if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($record['password'])) {
         throw new ErrorException("The password'" . $record['password'] . "' is not valid.");
     }
     if (record_exists('usr', 'email', $record['email']) || record_exists('artefact_internal_profile_email', 'email', $record['email'])) {
         throw new ErrorException("The email'" . $record['email'] . "' has been taken.");
     }
     // Create new user
     db_begin();
     raise_time_limit(180);
     $user = (object) array('authinstance' => $record['authinstance'], 'username' => $record['username'], 'firstname' => $record['firstname'], 'lastname' => $record['lastname'], 'email' => $record['email'], 'password' => $record['password'], 'passwordchange' => 0);
     if ($record['institution'] == 'mahara') {
         if ($record['role'] == 'admin') {
             $user->admin = 1;
         } else {
             if ($record['role'] == 'staff') {
                 $user->staff = 1;
             }
         }
     }
     $remoteauth = $record['authname'] != 'internal';
     if (!isset($record['remoteusername'])) {
         $record['remoteusername'] = null;
     }
     $user->id = create_user($user, array(), $record['institution'], $remoteauth, $record['remoteusername'], $record);
     if (isset($user->admin) && $user->admin) {
         require_once 'activity.php';
         activity_add_admin_defaults(array($user->id));
     }
     if ($record['institution'] != 'mahara') {
         if ($record['role'] == 'admin') {
             set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $record['institution']);
         } else {
             if ($record['role'] == 'staff') {
                 set_field('usr_institution', 'staff', 1, 'usr', $user->id, 'institution', $record['institution']);
             }
         }
     }
     db_commit();
     $this->usercounter++;
     return $user->id;
 }